我想知道将倒数计时器添加到 QMessageBox
的最佳方法是什么?例如,当显示消息框时,倒数计时器将启动 5 秒。如果用户没有响应消息框,消息框会选择默认选项。
最佳答案
这样的事情怎么样:
#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);
关于c++ - 带有倒数计时器的 QMessageBox,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18687084/