Clickable QLabel

From Qt Wiki
Revision as of 07:13, 18 May 2017 by Marco Sulla (talk | contribs) (Added includes, changed constructor)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

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!



#include <QLabel>
#include <QWidget>
#include <Qt>

class ClickableLabel : public QLabel { 

    explicit ClickableLabel(QWidget* parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());

    void clicked();

    void mousePressEvent(QMouseEvent* event);




#include "clickablelabel.h"

ClickableLabel::ClickableLabel(QWidget* parent, Qt::WindowFlags f)
    : QLabel(parent) {

ClickableLabel::~ClickableLabel() {}

void ClickableLabel::mousePressEvent(QMouseEvent* event) {
    emit clicked();

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.