Qt事件过滤

发布时间:2024年01月21日

1.相关说明

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

2.相关界面

3.相关代码

#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);
}

文章来源:https://blog.csdn.net/hdsHDS6/article/details/135709417
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。