目录
引出
QT学习(6)——QT中的定时器事件,两种实现方式;事件的分发event,事件过滤器
定时器事件
QTimerEvent
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
// 重写定时器事件
void timerEvent(QTimerEvent *);
int id1; // 定时器1的唯一标识
int id2; // 定时器2的唯一标识
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
如何定义多个定义器事件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// 启动定时器
// 参数1 间隔 单位 毫秒
id1 = startTimer(1000);
id2 = startTimer(2000);
}
void Widget::timerEvent(QTimerEvent * ev)
{
if(ev->timerId()==id1){
static int num =1;
// label1 每间隔1秒
ui->label_2->setText(QString::number(num++));
}
// label2 每间隔2s
if(ev->timerId()==id2){
static int num2 = 1;
ui->label_3->setText(QString::number(num2++));
}
// label3 每间隔3s
}
Widget::~Widget()
{
delete ui;
}
QTimer
定时器实现的另一种方式:实例化定时器QTimer 然后加到对象树上
进行定时信号的发送和处理
#include "widget.h"
#include "ui_widget.h"
#include <QTimer> // 定时器的类
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// 启动定时器
// 参数1 间隔 单位 毫秒
id1 = startTimer(1000);
id2 = startTimer(2000);
// 定时器的第二种方式,实例化,加到对象树上
QTimer *timer = new QTimer(this);
// 启动定时器
timer->start(500); // 每隔500ms
connect(timer,&QTimer::timeout,
[=](){
static int num = 1;
ui->label_4->setText(QString::number(num++));
});
// 点击暂停按钮,停止定时器
connect(ui->btnStop,&QPushButton::clicked,
[=](){
timer->stop();
}