简体   繁体   中英

close QMessageBox when certain condition is fulfilled

This is working:

#ifndef MYWARMUPMESSAGEBOX_H
#define MYWARMUPMESSAGEBOX_H

#include <QMessageBox>
#include <QPushButton>
#include <QTimer>

class myWarmUpMessageBox : public QMessageBox
{
    Q_OBJECT

private:

   QString _text;
   int _timeoutSeconds;
   QTimer _timer;
   int num = 0;

public:
explicit myWarmUpMessageBox(QWidget * parent):
   QMessageBox(parent)
   {
       connect(&_timer, SIGNAL(timeout()), this, SLOT(updateText()));
       _timer.start(500);
   }

   virtual void showEvent(QShowEvent * e)
   {
       QMessageBox::showEvent(e);
       updateText();
   }

public slots:

void updateText()
{
    num+=1;
    setText(QString::number(num));

    if(num>3)
        this->close();
}

I am using this QMessageBox in a QMainWindow in its close event.

void MainWindow::closeEvent(QCloseEvent *event)
{
    myWarmUpMessageBox * myBox = new myWarmUpMessageBox(this);
    myBox->exec();
    event->accept();
}

The QMessageBox pops up, counts to 3 diappears, and subsenquently the QMainWindow closes.

BUT it is not working if the condition for closing is fulfilled immediately, ie when saying

if(num>0)
    this->close();

which is true when the timer is triggered the first time, the program brakes. Why???

You have to let the QMessageBox to open fully and maximized and then only you need to close it, otherwise the QMessageBox Dialog may not be registered/fully loaded yet, for the close function to be successful.

same goes for closeevent also, if you try to access any Dialog widget properties inside Dialog closeevent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM