PDA

View Full Version : QMessageBox from QtConcurrent::run



arunkumaraymuo
29th April 2016, 11:12
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?



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

yeye_olive
29th April 2016, 12:42
All GUI operations, such as displaying a message box, must be executed by the same thread (which is often called the GUI thread). This is a limitation, not only of Qt, but also of all other widget toolkits I know of.

You must not directly display the message box from your ReadThread function. However, what you can do is send some kind of notification to the GUI thread that will make it display the message box. This can be achieved with QMetaObject::invokeMethod(), for instance; add a slot to your main window and invoke it from ReadThread with QMetaObject::invokeMethod(); in the slot, display the message box. You can add parameters to the slot, e.g. values to display in the message box.

Keep in mind that a message box blocks all user interaction. Surely you don't want the user to be spammed by thousands of message boxes triggered by your code running in a loop.