Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to call a message box from a multi threaded loop. My loop is running in a function (ReadThread) that called from the QtConcurrent::run. In that function the application is continue sly reading a hardware device. I want to pop up a message box based on the hardware response.

How I can call a message box from ReadThread() function? I am not interested to use QFutureWatcher. In my another code I want to continue the same loop. after closing the messagebox.

C++
m_Future->waitForFinished();
*m_Future = QtConcurrent::run(this, &MainWindow::ReadThread);


What I have tried:

C++
m_Future->waitForFinished();
*m_Future = QtConcurrent::run(this, &MainWindow::ReadThread);

C++
void MainWindow::ReadThread()
{
  while(true)
  {
    if(ui->fanviewer->ReadAndUpdateFanData() == false)
    {
       QMessageBox::information(this,tr("An error occured"), tr("Reading     failed."));
     return;
    }
 }
}
Posted
Updated 28-Apr-16 23:59pm
v3

1 solution

User interactions should be always performed in the main GUI thread.

A possible solution would be using an event that signals your main thread to display the message.

Define the event ID as public member in the MainWindow header file. Note that the value must be application wide unique (the below example assumes that the first available value QEvent::User is already used somewhere):
static const int ReadThreadErrEv = QEvent::User + 1;


Handle the customEvent[^] (don't forget to add the declaration to the header file):
void MainWindow::customEvent(QEvent *event)
{
    if (static_cast<int>(event->type()) == ReadThreadErrEv)
    {
        QMessageBox::information(this,
            tr("An error occured"), 
            tr("Reading failed. Check error log for more details"));
    }
}


Fire the event in the worker thread (note that a pointer to your main window is passed as additional argument):
void MainWindow::ReadThread(MainWindow *pMainWindow)
{
    if(ui->fanviewer->ReadAndUpdateFanData() == false)
    {
        QCoreApplication::postEvent(pMainWindow, 
            new QEvent((QEvent::Type)MainWindow::ReadThreadErrEv));
    }
}


Start the thread passing the MainWindow pointer. Note that I have moved the wait function to be called after the thread has started:
*m_Future = QtConcurrent::run(this, &MainWindow::ReadThread, this);
m_Future->waitForFinished();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900