QT-事件-定时器、事件过滤器

   widget.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#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;
}

 

 

posted @   wuyuan2011woaini  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示