MistyD
MistyD

Reputation: 17233

QMessageBox with a countdown timer

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.

Upvotes: 3

Views: 3173

Answers (3)

Jeremy Friesner
Jeremy Friesner

Reputation: 73181

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);

Upvotes: 7

Oleg Pyzhcov
Oleg Pyzhcov

Reputation: 7353

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.

Upvotes: 1

Violet Giraffe
Violet Giraffe

Reputation: 33607

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.

Upvotes: 0

Related Questions