通过使用eventFilter 事件过滤器,实现QLabel的 Enter、Leave 、MouseButtonPress、MouseButtonDblClick、MouseButtonRelease
EventFilterExample.h
#ifndef EVENTFILTEREXAMPLE_H
#define EVENTFILTEREXAMPLE_H
#include <QWidget>
namespace Ui {
class EventFilterExample;
}
class EventFilterExample : public QWidget
{
Q_OBJECT
public:
explicit EventFilterExample(QWidget *parent = nullptr);
~EventFilterExample();
bool eventFilter(QObject *watched, QEvent *event);
private:
Ui::EventFilterExample *ui;
};
#endif // EVENTFILTEREXAMPLE_H
EventFilterExample.cpp
#include "eventfilterexample.h"
#include "ui_eventfilterexample.h"
EventFilterExample::EventFilterExample(QWidget *parent)
: QWidget(parent)
, ui(new Ui::EventFilterExample)
{
ui->setupUi(this);
//给label控件安装事件过滤器
ui->labHover->installEventFilter(this);
ui->labDoubleClick->installEventFilter(this);
}
EventFilterExample::~EventFilterExample()
{
delete ui;
}
bool EventFilterExample::eventFilter(QObject *watched, QEvent *event)
{
if(watched== ui->labHover)
{
if(event->type()==QEvent::Enter)
{
ui->labHover->setStyleSheet("background-color:rgb(170, 255, 255);");
}
else if(event->type()==QEvent::Leave)
{
ui->labHover->setStyleSheet("");
ui->labHover->setText("靠近我,点击我~");
}
else if(event->type()== QEvent::MouseButtonPress)
{
ui->labHover->setText("Button Pressed");
}
else if(event->type()== QEvent::MouseButtonRelease)
ui->labHover->setText("Button Released");
}
if(watched == ui->labDoubleClick)
{
if(event->type()== QEvent::Enter)
{
ui->labDoubleClick->setStyleSheet("background-color: rgb(85, 255, 127);");
}
else if(event->type()==QEvent::Leave)
{
ui->labDoubleClick->setStyleSheet("");
ui->labDoubleClick->setText("可双击的标签");
}
else if(event->type()==QEvent::MouseButtonDblClick)
{
ui->labDoubleClick->setText("Double Clicked");
}
}
return QWidget::eventFilter(watched,event);
}
效果
总结
需要在构造函数中,给控件安装事件过滤器,才起作用
//给label控件安装事件过滤器
ui->labHover->installEventFilter(this);
ui->labDoubleClick->installEventFilter(this);