【问题标题】:QMessageBox with a countdown timer带有倒数计时器的 QMessageBox
【发布时间】:2013-09-12 06:48:56
【问题描述】:

我想知道将倒数计时器添加到 QMessageBox 的最佳方法是什么?例如,当显示一个消息框时,倒数计时器会启动 5 秒。如果用户没有响应消息框,则消息框会选择一个默认选项。

【问题讨论】:

    标签: c++ qt qmessagebox


    【解决方案1】:

    这样的事情怎么样:

    #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】:

      如果您不需要显示超时,请将QTimer::singleShot 与close()、accept() 或reject() 插槽一起使用。如果需要,则将 QMessageBox 或 QDialog 子类化并按照您的需要重新实现方法,例如重新实现QObject::timerEvent 进行文本更新。

      【讨论】:

        【解决方案3】:

        如果您希望消息框显示计时器值,我认为您最好创建自己的 QDialog 子类。否则,这听起来很简单 - 使用 show 显示您的消息,启动计时器,连接到 timeout 插槽并操作您的对话框。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-29
          • 1970-01-01
          • 2013-01-26
          • 2019-08-08
          • 1970-01-01
          • 2018-11-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多