QT 给控件添加事件过滤

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    int number = 0;
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    bool eventFilter(QObject *obj, QEvent *e);

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->textEdit->setAttribute(Qt::WA_Hover,true);//开启悬停事件
    ui->textEdit->installEventFilter(this);
}

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

bool Widget::eventFilter(QObject *obj, QEvent *e)
{
    if(obj == ui->textEdit)
    {
        //if(e->type() == QEvent::Wheel)
        if(e->type() == QEvent::HoverEnter)
        {
            qDebug() << "helloworld!";
            qDebug() << number++;



        }



    }


}

你可能感兴趣的:(QT开发)