Qt事件过滤

1.相关说明

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

2.相关界面

Qt事件过滤_第1张图片

Qt事件过滤_第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);
}

你可能感兴趣的:(Qt6,qt,命令模式,开发语言,qt6.3)