Qt QLable response click click event

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

button()

The main code


  
  
  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. MainWindow::MainWindow(QWidget *parent) :
  4. QMainWindow(parent),
  5. ui( new Ui::MainWindow)
  6. {
  7. ui-> setupUi ( this );
  8. ui-> label-> installEventFilter ( the this ); // event filter installation
  9. }
  10. ~ MainWindow :: MainWindow ()
  11. {
  12. delete ui;
  13. }
  14. bool MainWindow::eventFilter(QObject *obj, QEvent *event)
  15. {
  16. IF (obj == ui-> label) // specify a QLabel
  17. {
  18. if (event->type() == QEvent::MouseButtonPress) //mouse button pressed
  19. {
  20. QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
  21. if(mouseEvent->button() == Qt::LeftButton)
  22. {
  23. :: Information QMessageBox ( NULL , "click" , "click me" ,
  24. QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
  25. return true;
  26. }
  27. else
  28. {
  29. return false;
  30. }
  31. }
  32. else
  33. {
  34. return false ;
  35. }
  36. }
  37. else
  38. {
  39. // pass the event on to the parent class
  40. return QMainWindow::eventFilter(obj, event);
  41. }
  42. }



The second method

Using inheritance QLabel, rewriting the event handler callback function mousePressEvent

Renderings

Renderings

The main code


  
  
  1. #include "mylabel.h"
  2. MyLabel::MyLabel( const QString & text,QWidget *parent) : QLabel(parent)
  3. {
  4. setText(text);
  5. }
  6. MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
  7. {
  8. }
  9. void MyLabel::mousePressEvent(QMouseEvent *event)
  10. {
  11. //Qt::LeftButton
  12. //Qt::RightButton
  13. if(event->button()== Qt::LeftButton)
  14. {
  15. :: Information QMessageBox ( NULL , "click" , "click me" ,
  16. QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
  17. }
  18. }

The third method

Rewrite event()function

The main code


  
  
  1. #include "mylabel.h"
  2. MyLabel::MyLabel( const QString & text,QWidget *parent) : QLabel(parent)
  3. {
  4. setText(text);
  5. }
  6. MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
  7. {
  8. }
  9. bool MyLabel::event(QEvent *e)
  10. {
  11. if (e->type() == QEvent::MouseButtonPress)
  12. {
  13. QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(e);
  14. if(mouseEvent->button() == Qt::LeftButton)
  15. {
  16. :: Information QMessageBox ( NULL , "click" , "click me" ,
  17. QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
  18. return true;
  19. }
  20. }
  21. return QLabel::event(e);
  22. }

All three methods of engineering the code upload to csdn, Qt 5.9.0
Published 42 original articles · won praise 148 · views 410 000 +

Guess you like

Origin blog.csdn.net/baidu_37503452/article/details/104381399