QMessageBox with a countdown timer

3k views Asked by At

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.

3

There are 3 answers

0
Oleg Pyzhcov On

Use QTimer::singleShot with either close(), accept() or reject() slots if you don't need to display the timeout. If you need, then subclass QMessageBox or QDialog and reimplement methods as you want them to be, e.g. reimplement QObject::timerEvent to make text update.

0
Jeremy Friesner 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);
0
Violet Giraffe On

If you want the message box to display the timer value I think you're better off making your own QDialog subclass. Otherwise it sounds simple - display your message with show, start the timer, connect to the timeout slot and manipulate your dialog.