Qt事件过滤器

1 介绍

        事件过滤器是一种机制,当某个QObject没有所需要的事件功能时,可将其委托其它QObject,通过eventFilter成员函数来过滤实现功能。

2 主要构成

委托:

ui->QObject1->installEventFilter(QObject2);

eventFilter声明

virtual bool eventFilter(QObject *watched, QEvent *event) override;

        在Qt creator中,可以使用如下步骤简化实现:

        a)右键widget

Qt事件过滤器_第1张图片 

        b)选择insert  Virtual。。。:

Qt事件过滤器_第2张图片

        c)选择eventFilter,并勾选如下,稍后将定义粘贴到对应的.cpp文件中即可

Qt事件过滤器_第3张图片

Qt事件过滤器_第4张图片

 3 示例代码:使用事件过滤器对label实现单双击事件响应

       widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include 
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //将label委托给widget
    ui->labelSC->setText("单击我");
    ui->labelSC->installEventFilter(this);
    ui->labelDC->installEventFilter(this);
}

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

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->labelSC)
    {
        if(event->type() == QEvent::Enter)
            ui->labelSC->setStyleSheet("background-color:rgb(170,255,255)");
        else if(event->type() == QEvent::Leave)
        {
            ui->labelSC->setText("单击我");
            ui->labelSC->setStyleSheet("");
        }
        else if(event->type() == QEvent::MouseButtonPress)
            ui->labelSC->setText("MouseButtonPress");
        else if(event->type() == QEvent::MouseButtonRelease)
            ui->labelSC->setText("MouseButtonRelease");
    }
    if(watched == ui->labelDC)
    {
        if(event->type() == QEvent::Enter)
            ui->labelDC->setStyleSheet("background-color:rgb(170,0,255)");
        else if(event->type() == QEvent::Leave)
        {
            ui->labelDC->setText("双击我");
            ui->labelDC->setStyleSheet("");
        }
        else if(event->type() == QEvent::MouseButtonDblClick)
            ui->labelDC->setText("MouseButtonDblClick");
        else if(event->type() == QEvent::MouseButtonRelease)
            ui->labelDC->setText("MouseButtonRelease");
    }
    return QWidget::eventFilter(watched, event);
}

        widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;

    // QObject interface
public:
    virtual bool eventFilter(QObject *watched, QEvent *event) override;
};


#endif // WIDGET_H

 

 

你可能感兴趣的:(c++qt,qt,开发语言)