QMessageBox with a countdown timer

懵懂的女人 提交于 2019-12-07 13:28:58

问题


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.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/18687084/qmessagebox-with-a-countdown-timer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!