Search code examples
c++qtqmessagebox

Closing QMessageBox on timer, setText not showing


The following piece of code closes my QMessageBox after 2 secs. But my text shows when the box is closing, It flashes really quick before the box closes. What is going on here?

 QMessageBox *msgBox = new QMessageBox();
 msgBox->setText("Coördinate is being created, please wait...");
 msgBox->show();
 QTimer::singleShot(2000, msgBox, SLOT(hide()));

enter image description here

This shows, and then just before closing I can see the text.

update

Working in a single thread program: Method WriteMultipleACLCommands() is taking up a lot of time. Maybe thats the issue?

  QMessageBox *msgBox = new QMessageBox();
  msgBox->setText("Coördinate is being created, please wait...");
  msgBox->show();
  QTimer::singleShot(2000, msgBox, SLOT(hide()));
  singleton_SerialPortManager->WriteMultipleACLCommands();
  //function writes a few bytes onto a serial connection

Solution

  • After the update,

    Of course it is an issue if you don't return from the calling function right away - you are blocking the event loop, hence updates to all widgets!

    Possible Solution

    You can make WriteMultipleACLCommands Q_INVOKABLE (or a slot) and invoke it as Qt::QueuedConnection:

    QMetaObject::invokeMethod(singleton_SerialPortManager, "WriteMultipleACLCommands", Qt::QueuedConnection);

    This way you just post an event to the events queue and return right away. After that the message box will receive an update, then, at some point WriteMultipleACLCommands will be called as well.