从0开始。点击开始按钮后开始计时,每1秒更新一次。中间可以点击关闭按钮暂停计时。
QTime类提供定时器。发射timeout信号
QProgressBar 和 QTime相关联。
#include "mywidget.h"
#include "ui_mywidget.h"
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MyWidget)
{
ui->setupUi(this);
this->setWindowTitle(QString("计时器"));
QTimer *time = new QTimer(this);
static int i = 0;
QPushButton *start = new QPushButton(this);
start->setText("开始");
start->move(50,100);
QPushButton *close = new QPushButton(this);
close->setText("关闭");
close->move(170,100);
QProgressBar *dis = new QProgressBar(this);
dis->setRange(0,100);
dis->setValue(i);
dis->move(120,10);
connect(time,&QTimer::timeout,
[=]
()
{
dis->setValue(++i);
}
);
connect(start,&QPushButton::clicked,
[=]
()
{
time->start(1000);
}
);
connect(close,&QPushButton::clicked,
[=]
()
{
time->stop();
}
);
}
MyWidget::~MyWidget()
{
delete ui;
}