https://blog.csdn.net/usister/article/details/76098620
first method
Use eventFilter event filter, with reference to specific methods https://www.devbean.net/2012/10/qt-study-road-2-event-filter/
Renderings
The main code
-
#include "mainwindow.h"
-
#include "ui_mainwindow.h"
-
-
MainWindow::MainWindow(QWidget *parent) :
-
QMainWindow(parent),
-
ui(
new Ui::MainWindow)
-
{
-
ui-> setupUi ( this );
-
ui-> label-> installEventFilter ( the this ); // event filter installation
-
}
-
-
~ MainWindow :: MainWindow ()
-
{
-
delete
ui;
-
}
-
-
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
-
{
-
IF
(obj == ui-> label)
// specify a QLabel
-
{
-
if (event->type() == QEvent::MouseButtonPress)
//mouse button pressed
-
{
-
QMouseEvent *mouseEvent =
static_cast<QMouseEvent*>(event);
-
if(mouseEvent->button() == Qt::LeftButton)
-
{
-
:: Information QMessageBox ( NULL , "click" , "click me" ,
-
QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
-
return
true;
-
}
-
else
-
{
-
return
false;
-
}
-
}
-
else
-
{
-
return
false
;
-
}
-
}
-
else
-
{
-
// pass the event on to the parent class
-
return QMainWindow::eventFilter(obj, event);
-
}
-
}
The second method
Using inheritance QLabel, rewriting the event handler callback function mousePressEvent
Renderings
The main code
-
#include "mylabel.h"
-
-
MyLabel::MyLabel(
const QString & text,QWidget *parent) : QLabel(parent)
-
{
-
setText(text);
-
}
-
-
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
-
{
-
-
}
-
-
void MyLabel::mousePressEvent(QMouseEvent *event)
-
{
-
//Qt::LeftButton
-
//Qt::RightButton
-
if(event->button()== Qt::LeftButton)
-
{
-
:: Information QMessageBox ( NULL , "click" , "click me" ,
-
QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
-
}
-
}
The third method
Rewrite event()
function
The main code
-
#include "mylabel.h"
-
-
MyLabel::MyLabel(
const QString & text,QWidget *parent) : QLabel(parent)
-
{
-
setText(text);
-
}
-
-
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
-
{
-
-
}
-
-
bool MyLabel::event(QEvent *e)
-
{
-
if (e->type() == QEvent::MouseButtonPress)
-
{
-
QMouseEvent *mouseEvent =
static_cast<QMouseEvent*>(e);
-
if(mouseEvent->button() == Qt::LeftButton)
-
{
-
:: Information QMessageBox ( NULL , "click" , "click me" ,
-
QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
-
return
true;
-
}
-
}
-
return QLabel::event(e);
-
}
All three methods of engineering the code upload to csdn, Qt 5.9.0