Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto close QMessageBox

Tags:

qt

qmessagebox

I'm building a Qt Symbian Project and I want to show a notification for the user that should auto close after some seconds. I have seen that Nokia uses this a lot in their ui.

Right now I'm using the code below so that the user can close the QMessageBox but I would like it if it was possible to auto close the QMessageBox after 1 or 2 seconds. How can I do this using Qt?

QMessageBox msgBox;
msgBox.setText("Hello!");
msgBox.setIcon(QMessageBox::Information);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
like image 609
Martin Avatar asked Feb 10 '10 12:02

Martin


3 Answers

Thanks really much! My solution:

I created my own class (MessageBox) this is my code for showing it:

MessageBox msgBox;
msgBox.setText("Hello!");
msgBox.setIcon(QMessageBox::Information);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setAutoClose(true);
msgBox.setTimeout(3); //Closes after three seconds
msgBox.exec();

This is my class:

class MessageBox : public QMessageBox

int timeout;
bool autoClose;
int currentTime;

void MessageBox::showEvent ( QShowEvent * event ) {
    currentTime = 0;
    if (autoClose) {
    this->startTimer(1000);
    }
}

void MessageBox::timerEvent(QTimerEvent *event)
{
    currentTime++;
    if (currentTime>=timeout) {
    this->done(0);
    }
}
like image 77
Martin Avatar answered Nov 07 '22 20:11

Martin


I would suggest to subclass QMessageBox to add your own desired behavior...

It would be interesting to add methods like setAutoClose(bool) and setAutoCloseTimeout(int) and trigger a QTimer on showEvent when the AutoClose option is enabled !

This way, you could even alter the apparence of your QMessageBox and had a text saying "This box will close automatically in XXX seconds..." or a progress bar, etc...

like image 45
Andy M Avatar answered Nov 07 '22 19:11

Andy M


Instead you can use Singleshot Timer to close any dialog box or QLabel with much ease:

QTimer *timer;
QTimer::singleShot(10000, msgBox, SLOT(close()));
like image 45
Tachi Avatar answered Nov 07 '22 20:11

Tachi