A ‘Click’able QLabel

A “clicked” signal may sometimes be required from a label, but there is no “clicked” signal emitted by QLabel.
You can work around this easily by making a QPushButton like a label by setting the ‘flat’ property.

However, if there are other properties of a QLabel object that you need, here is a code snippet for a custom QLabel which can emit a signal : ‘clicked’.
In other words, a Clickable QLabel!

Header

  1. class ClickableLabel : public QLabel
  2. {
  3.  
  4. Q_OBJECT
  5.  
  6. public:
  7.     explicit ClickableLabel( const QString& text ="", QWidget * parent = 0 );
  8.     ~ClickableLabel();
  9.  
  10. signals:
  11.     void clicked();
  12.  
  13. protected:
  14.     void mousePressEvent ( QMouseEvent * event ) ;
  15. };

Source

  1. ClickableLabel::ClickableLabel( const QString& text, QWidget * parent ) :
  2.     QLabel(parent)
  3.  
  4.   {
  5.       this->setText(text);
  6.   }
  7.  
  8.   ClickableLabel::~ClickableLabel()
  9.   {
  10.   }
  11.  
  12.   void ClickableLabel::mousePressEvent ( QMouseEvent * event )
  13.  
  14.   {
  15.       emit clicked();
  16.   }

What we do here is simple : Catch the mouse press event on the label. Then emit ‘clicked’ signal. We could as well make the signal be emitted when mouse gets released. This is let to be a decision of the developer.

Categories: