Clickable QLabel
Jump to navigation
Jump to search
h1. 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
class ClickableLabel : public QLabel<br />{
Q_OBJECT
public:<br /> explicit ClickableLabel( const QString&amp; text ="", QWidget * parent = 0 );<br /> ~ClickableLabel();
signals:<br /> void clicked();
protected:<br /> void mousePressEvent ( QMouseEvent * event ) ;<br />};
Source
<br />ClickableLabel::ClickableLabel( const QString&amp; text, QWidget * parent ) :<br /> QLabel(parent)
{<br /> this->setText(text);<br /> }
ClickableLabel::~ClickableLabel()<br /> {<br /> }
void ClickableLabel::mousePressEvent ( QMouseEvent * event )
{<br /> emit clicked();<br /> }<br />
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.