QT-事件-定时器、事件过滤器
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public :
explicit Widget(QWidget *parent = 0);
~Widget();
//重写定时器的事件
void timerEvent(QTimerEvent *);
int id1; //定时器1的唯一标示
int id2; //定时器2的唯一标示
//重写事件过滤器的事件
bool eventFilter(QObject *, QEvent *);
private :
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include //定时器类
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui( new Ui::Widget)
{
ui->setupUi( this );
//启动定时器
id1 = startTimer(1000); //参数1 间隔 单位 毫秒
id2 = startTimer(2000);
//定时器第二种方式
QTimer * timer = new QTimer( this );
//启动定时器
timer->start(500);
connect(timer,&QTimer::timeout,[=](){
static int num = 1;
//label4 每隔0.5秒+1
ui->label_4->setText(QString::number(num++));
});
//点击暂停按钮 实现停止定时器
connect(ui->btn,&QPushButton::clicked,[=](){
timer->stop();
});
//给label1 安装事件过滤器
// 步骤1 安装事件过滤器
ui->label->installEventFilter( this );
}
// 步骤2 重写 eventfilter事件
bool Widget::eventFilter(QObject * obj , QEvent * e)
{
if (obj == ui->label)
{
if (e->type() == QEvent::MouseButtonPress)
{
QMouseEvent * ev = static_cast (e);
QString str = QString( "事件过滤器中::鼠标按下了 x = %1 y = %2 globalX = %3 globalY = %4 " ).arg(ev->x()).arg(ev->y()).arg(ev->globalX()).arg(ev->globalY());
qDebug() << str;
return true ; //true代表用户自己处理这个事件,不向下分发
}
}
//其他默认处理
return QWidget::eventFilter(obj,e);
}
void Widget::timerEvent(QTimerEvent * ev)
{
if (ev->timerId() == id1)
{
static int num = 1;
//label2 每隔1秒+1
ui->label_2->setText( QString::number(num++));
}
if (ev->timerId() == id2)
{
//label3 每隔2秒 +1
static int num2 = 1;
ui->label_3->setText( QString::number(num2++));
}
}
Widget::~Widget()
{
delete ui;
}


天道酬勤 循序渐进 技压群雄
浙公网安备 33010602011771号