Qt事件过滤

1.相关说明

监控鼠标进入组件、出组件、点击组件、双击组件的事件,需要重写eventFilter函数

2.相关界面

3.相关代码

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->labSC->installEventFilter(this);
    ui->labDC->installEventFilter(this);
}

Widget::~Widget()
{
    delete ui;
}


bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->labSC){
        if(event->type() == QEvent::Enter){
            ui->labSC->setStyleSheet("background-color:rgb(170,255,255)");
        }else if(event->type() == QEvent::Leave){
            ui->labSC->setText("单击");
            ui->labSC->setStyleSheet("");
        }else if(event->type() == QEvent::MouseButtonPress){
            ui->labSC->setText("button pressed");
        }else if(event->type() == QEvent::MouseButtonRelease){
            ui->labSC->setText("button released");
        }
    }
    if(watched == ui->labDC){
        if(event->type() == QEvent::Enter){
            ui->labDC->setStyleSheet("background-color:rgb(85,255,255)");
        }else if(event->type() == QEvent::Leave){
            ui->labDC->setText("双击");
            ui->labDC->setStyleSheet("");
        }else if(event->type() == QEvent::MouseButtonDblClick){
            ui->labDC->setText("button double clicked");
        }
    }
    if(watched == ui->labNo){
        if(event->type() == QEvent::Enter){
            ui->labNo->setStyleSheet("background-color:rgb(85,255,255)");
        }else if(event->type() == QEvent::Leave){
            ui->labNo->setText("No");
            ui->labNo->setStyleSheet("");
        }
    }
    return QWidget::eventFilter(watched, event);
}
相关推荐
wt_cs2 分钟前
身份认证C#集成方案-数字时代身份证实名认证利器
开发语言·c#
ghost14324 分钟前
Python自学第2天:条件语句,循环语句
开发语言·python·学习
Chandler2436 分钟前
Go:低级编程
开发语言·后端·golang
^_^ 纵歌1 小时前
用python比较两个mp4是否实质相同
开发语言·python·音频·视频
一直走下去-明1 小时前
使用python帮助艺术家完成角色动画和服装模型等任务
开发语言·图像处理·pytorch·python·opencv·ai作画
长流小哥1 小时前
Linux网络编程实战:从字节序到UDP协议栈的深度解析与开发指南
linux·c语言·开发语言·网络·udp
幼儿园园霸柒柒1 小时前
第七章:7.2求方程a*x*x+b*x+c=0的根,用3个函数,分别求当:b*b-4*a*c大于0、等于0和小于0时的根并输出结果。从主函数输入a、b、c的值
c语言·开发语言·算法·c#
不知道叫什么呀1 小时前
【C语言基础】C++ 中的 `vector` 及其 C 语言实现详解
c语言·开发语言·c++
muyouking112 小时前
0.深入探秘 Rust Web 框架 Axum
开发语言·前端·rust
勇敢牛牛_2 小时前
【Rust基础】使用Rocket构建基于SSE的流式回复
开发语言·后端·rust