I wanted to know what would be the best approach of adding a countdown timer to a QMessageBox
? For instance when a message box is displayed the countdown timer starts for say 5 seconds. If the user doesn't respond to the Message box the message box picks up a default choice.
QMessageBox with a countdown timer
3k views Asked by MistyD At
3
There are 3 answers
0
On
How about something like this:
#include <QMessageBox>
#include <QPushButton>
#include <QTimer>
class TimedMessageBox : public QMessageBox
{
Q_OBJECT
public:
TimedMessageBox(int timeoutSeconds, const QString & title, const QString & text, Icon icon, int button0, int button1, int button2, QWidget * parent, WindowFlags flags = (WindowFlags)Dialog|MSWindowsFixedSizeDialogHint)
: QMessageBox(title, text, icon, button0, button1, button2, parent, flags)
, _timeoutSeconds(timeoutSeconds+1)
, _text(text)
{
connect(&_timer, SIGNAL(timeout()), this, SLOT(Tick()));
_timer.setInterval(1000);
}
virtual void showEvent(QShowEvent * e)
{
QMessageBox::showEvent(e);
Tick();
_timer.start();
}
private slots:
void Tick()
{
if (--_timeoutSeconds >= 0) setText(_text.arg(_timeoutSeconds));
else
{
_timer.stop();
defaultButton()->animateClick();
}
}
private:
QString _text;
int _timeoutSeconds;
QTimer _timer;
};
[...]
TimedMessageBox * tmb = new TimedMessageBox(10, tr("Timed Message Box"), tr("%1 seconds to go..."), QMessageBox::Warning, QMessageBox::Ok | QMessageBox::Default, QMessageBox::Cancel, QMessageBox::NoButton, this);
int ret = tmb->exec();
delete tmb;
printf("ret=%i\n", ret);
Use
QTimer::singleShot
with eitherclose()
,accept()
orreject()
slots if you don't need to display the timeout. If you need, then subclassQMessageBox
orQDialog
and reimplement methods as you want them to be, e.g. reimplementQObject::timerEvent
to make text update.