QT中QMessageBox添加倒计时

QMessageBox添加倒计时,一定时间内选择确定或者取消,否则倒计时结束,默认选择确定

 QT中QMessageBox添加倒计时

 直接上代码

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    w.resize(800,600);
    return a.exec();
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimer>
#include <QPushButton>
#include <QMessageBox>
#include <QDebug>
#include <iostream>
class Widget : public QWidget
{
  Q_OBJECT

public:
  Widget(QWidget* parent = 0);
  ~Widget();

private:

  QTimer*      timer_countdown;
  QPushButton* btn;
  QMessageBox* msgbox;
  QPushButton* okbtn;
  QPushButton* cancelbtn;
  double       msgbox_time_;
public slots:
  void count_time();
  void btnclick();
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#define TOTAL_TIME 8.0
#define INTERVAL 0.1
Widget::Widget(QWidget* parent)
  : QWidget(parent)
{
  btn = new QPushButton("点我一下", this);
  btn->setFixedSize(100, 50);

  msgbox = new QMessageBox(this);
  msgbox->setGeometry(QRect(200, 150, 400, 300));
  okbtn     = new QPushButton("确定");
  cancelbtn = new QPushButton("取消");
  msgbox->addButton(okbtn, QMessageBox::AcceptRole);
  msgbox->addButton(cancelbtn, QMessageBox::RejectRole);
  msgbox->setText(tr("确定需要发送任务?"));
  msgbox->setStyleSheet("QPushButton {min-width: 5em; min-height: 2em;}");

  timer_countdown = new QTimer(this);
  connect(timer_countdown, SIGNAL(timeout()), this, SLOT(count_time()));
  connect(btn, SIGNAL(clicked()), this, SLOT(btnclick()));
}

Widget::~Widget()
{
}

void Widget::count_time()
{
  double letf_time = TOTAL_TIME - msgbox_time_;
  if( letf_time <= 0 )
  {
    okbtn->click();
    return;
  }
  else
  {
    QString output;
    output.sprintf("%2.1f秒 后发送任务 ", letf_time);
    msgbox->setText(output);
  }
  msgbox_time_ += INTERVAL;
}

void Widget::btnclick()
{
  timer_countdown->start(INTERVAL*1000);
  msgbox_time_ = 0.0;
  msgbox->exec();
  if (msgbox->clickedButton() == okbtn)
  {
    qDebug()<<"确定被按下了";
    timer_countdown->stop();
  }
  else
  {
    qDebug()<<"取消被按下了";
    timer_countdown->stop();
  }
}

 

上一篇:前端小问题杂记


下一篇:python初级(302) 3 easygui简单使用二