创建定时器方式一
要触发定时器事件,首先要创建一个定时器 ,只要是继承 QWidget ,都有一个静态成员函数 startTimer 。
在 xxxmainwindow.cpp 中,
SerialMainWindow::SerialMainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::SerialMainWindow)
{
ui->setupUi(this);
//创建定时器,第一个参数是定时时间,单位为 ms .
startTimer(1000);
xxx;
}
然后,重写 timerEvent 事件处理器函数。
在 xxxmainwindow.h 中,
#ifndef SERIALMAINWINDOW_H
#define SERIALMAINWINDOW_H
#include <QMainWindow>
...
#include <QTimerEvent>
...
class SerialMainWindow : public QMainWindow
{
Q_OBJECT
public:
SerialMainWindow(QWidget *parent = nullptr);
~SerialMainWindow();
...;
private slots:
protected:
void timerEvent(QTimerEvent* event);
private:
Ui::SerialMainWindow *ui;
};
#endif // SERIALMAINWINDOW_H
在 xxxmainwindow.cpp 中,
void SerialMainWindow::timerEvent(QTimerEvent *event)
{
qDebug()<<"闹钟响了";
}
运行程序,每经过1秒钟,就会在应用程序输出窗口输出:
关于返回值问题。
当有一个返回值时:
当不止一个返回值(定时器)时,
创建定时器方式二
还有另外一种定时器,是 QT封装好的。
下面,完成这样的一种案例。
当点击启动按钮后,点击 Start 后,计时开始,数值每秒加 1 ,点击停止后,计时停止。
首先,设计 UI ,拖拽一个 LCD Number 控件和两个按钮控件。
下图所示,
代码如下:
在 xxxmainwindow.h 中
#ifndef SERIALMAINWINDOW_H
#define SERIALMAINWINDOW_H
#include <QMainWindow>
#include <xxx>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class SerialMainWindow; }
QT_END_NAMESPACE
class SerialMainWindow : public QMainWindow
{
Q_OBJECT
public:
SerialMainWindow(QWidget *parent = nullptr);
~SerialMainWindow();
xxx;
private slots:
xxx;
void on_btnStart_clicked();
void on_btnStop_clicked();
protected:
xxx;
private:
Ui::SerialMainWindow *ui;
//实例化对象
xxx;
QTimer *timer;
};
#endif // SERIALMAINWINDOW_H
在 xxxmainwindow.cpp 中
#include "serialmainwindow.h"
#include "ui_serialmainwindow.h"
SerialMainWindow::SerialMainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::SerialMainWindow)
{
ui->setupUi(this);
}
SerialMainWindow::~SerialMainWindow()
{
delete ui;
}
void SerialMainWindow::on_btnStart_clicked()
{
timer = new QTimer(this);
//毫秒做单位
timer->start(1000);
//每隔1s发送信号
connect(timer,&QTimer::timeout,[=](){
static int num=1;
this->ui->lcdNumber->display(num++);
});
}
void SerialMainWindow::on_btnStop_clicked()
{
timer->stop();
}
当连续多次点击 Start 后,又会怎么样呢?
总结:该代码只是演示代码,一次只能点击一次Start ,不能连续点击,当连续点击后,计时时间会变快,如上图所示,并且 Stop 按钮的功能会失效。只能点击一次 Start ,再点击一次 Stop ,如果要继续计时的话,就再点击一次 Start,Start 和 Stop 要配对使用。
如何改进呢?
初始时,Stop 按钮禁止,点击一次 Start 之后,就将 Start 按钮给禁止,同时使能 Stop 按钮,当点击 Stop 按钮后,就再将 Start 按钮给禁止,同时Stop 按钮禁止。
代码改进如下:
void SerialMainWindow::on_btnStart_clicked()
{
timer = new QTimer(this);
//毫秒做单位
timer->start(1000);
//每隔1s发送信号
connect(timer,&QTimer::timeout,[=](){
static int num=1;
ui->btnStart->setDisabled(true);
ui->btnStop->setDisabled(false);
this->ui->lcdNumber->display(num++);
});
}
void SerialMainWindow::on_btnStop_clicked()
{
timer->stop();
ui->btnStart->setDisabled(false);
ui->btnStop->setDisabled(true);
}
补充:
1、start();或start(0); 此函数的默认值为0。超时间隔为0的QTimer将在处理完窗口系统的事件队列中的所有事件后立即超时。
2、elapsed();的作用是返回自上次调用start()或restart()以来已经过的毫秒数。