自定义类TMyLabel ,继承自QLabel
TMyLabel 中重新实现了 event 方法,重写了mouseDoubleClickEvent 发射信号
在主窗体中放入TMyLabel组件,将TMyLabel mouseDoubleClickEvent 信号, 绑定到实现方法do_doubleClick()槽函数
TMyLabel.h
#ifndef TMYLABEL_H
#define TMYLABEL_H
#include <QLabel>
//引用鼠标事件 鼠标双击事件mouseDoubleClickEvent才能自动带出来参数
#include <QMouseEvent>
class TMyLabel : public QLabel
{
Q_OBJECT
public:
// TMyLabel();
TMyLabel(QWidget *parent=nullptr);//重写构造函数
bool event(QEvent *e);//重写event()函数
protected:
void mouseDoubleClickEvent(QMouseEvent *event);//重写鼠标的双击事件
signals:
void doubleClick();//自定义信号发射函数
};
#endif // TMYLABEL_H
TMyLabel.cpp
#include "tmylabel.h"
// TMyLabel::TMyLabel(QWidget *parent): {}
TMyLabel::TMyLabel(QWidget *parent):QLabel(parent)
{
this->setAttribute(Qt::WA_Hover,true);//必须设置这个属性,鼠标才能有Hover事件
}
bool TMyLabel::event(QEvent *e)
{
if(e->type()==QEvent::HoverEnter)
{//鼠标移入时,将调色板的字体颜色设置为红色
QPalette palet=this->palette();
palet.setColor(QPalette::WindowText,Qt::red);
this->setPalette(palet);
}
else if(e->type()==QEvent::HoverLeave)//鼠标移出
{//鼠标移出的时候 颜色再变回黑色
QPalette palet = this->palette();
palet.setColor(QPalette::WindowText,Qt::black);
this->setPalette(palet);
}
return QLabel::event(e);//执行父类的的event() 执行父类要执行的事情
}
void TMyLabel::mouseDoubleClickEvent(QMouseEvent *event)
{
Q_UNUSED(event);
emit doubleClick();//发射信号 用来父组件连接到执行槽
}
主窗体设计
主窗体 TMyLableMouseMoveExample.h
#ifndef TMYLABLEMOUSEMOVEEXAMPLE_H
#define TMYLABLEMOUSEMOVEEXAMPLE_H
#include <QWidget>
#include <QMouseEvent>
namespace Ui {
class TMyLableMouseMoveExample;
}
class TMyLableMouseMoveExample : public QWidget
{
Q_OBJECT
public:
explicit TMyLableMouseMoveExample(QWidget *parent = nullptr);
~TMyLableMouseMoveExample();
protected:
void mouseDoubleClickEvent(QMouseEvent *event);
private slots:
void do_doubleClick();
private:
Ui::TMyLableMouseMoveExample *ui;
};
#endif // TMYLABLEMOUSEMOVEEXAMPLE_H
主窗体TMyLableMouseMoveExample.cpp
#include "tmylablemousemoveexample.h"
#include "ui_tmylablemousemoveexample.h"
TMyLableMouseMoveExample::TMyLableMouseMoveExample(QWidget *parent)
: QWidget(parent)
, ui(new Ui::TMyLableMouseMoveExample)
{
ui->setupUi(this);
connect(ui->lab,SIGNAL(doubleClick())
,this,SLOT(do_doubleClick()));
}
TMyLableMouseMoveExample::~TMyLableMouseMoveExample()
{
delete ui;
}
void TMyLableMouseMoveExample::mouseDoubleClickEvent(QMouseEvent *event)
{
Q_UNUSED(event);
ui->lab->setText("窗口被双击了");
ui->lab->adjustSize();
}
void TMyLableMouseMoveExample::do_doubleClick()
{
ui->lab->setText("信号槽响应:TMyLabel被双击了");
ui->lab->adjustSize();
}
效果