参考: https://wiki.qt.io/Clickable_QLabel

头文件:

  1. #ifndef CLICKABLELABEL_H
  2. #define CLICKABLELABEL_H
  3. #include <QLabel>
  4. #include <QMouseEvent>
  5. #include <QWidget>
  6. class ClickableLabel : public QLabel {
  7. Q_OBJECT
  8. public:
  9. ClickableLabel(QWidget* parent = nullptr);
  10. ~ClickableLabel();
  11. signals:
  12. void clicked();
  13. protected:
  14. virtual void mousePressEvent(QMouseEvent* event);
  15. };
  16. #endif // CLICKABLELABEL_H

实现

  1. #include "clickablelabel.h"
  2. ClickableLabel::ClickableLabel(QWidget *parent)
  3. {
  4. }
  5. ClickableLabel::~ClickableLabel() { }
  6. void ClickableLabel::mousePressEvent(QMouseEvent* event)
  7. {
  8. if (event->button() == Qt::LeftButton) {
  9. emit clicked();
  10. }
  11. }

使用

  1. ClickableLabel* label = new ClickableLabel();
  2. connect(label, &ClickableLabel::clicked, this, &ClassName::SlotRemoveTableRow);