Search code examples
c++qtmouseeventqlabel

Make Qlabel clickable or double clickable in Qt


I am beginner in Qt, now I want to make my label clickable, I have searched so much online, but no one gives my a real example of how they made it. So can someone teach me step by step? Now my basic thinking is creating a new .c file and new .h file respectively and then include them into my mainwindow.c and then connect it with the existing label in ui form. These are what I was trying to do, but can not make it. Hope someone can teach and better put the step picture in the command, thanks. Here is the clicklabel.h code:

#ifndef CLICKEDLABEL_H
#define CLICKEDLABEL_H

#include <QWidget>
#include <QLabel>

class ClickedLabel : public QLabel
{
    Q_OBJECT
public:
    ClickedLabel(QWidget *parent=0): QLabel(parent){}
    ~ClickedLabel() {}
signals:
    void clicked(ClickedLabel* click); 
protected:
    void mouseReleaseEvent(QMouseEvent*); 
};

#endif // CLICKEDLABEL_H

This the clicklabel.c code:

#include "clicklabel.h"
void ClickedLabel::mouseReleaseEvent(QMouseEvent *)
{
    emit clicked(this); 
}

These are what I added into my mainwindow.c( the name of the label is click_test):

void data_labeling::on_label_clicked()
{
    QString path="/home/j/Pictures/images.jpeg";
    QPixmap cat(path);
    connect(ui->click_test, SIGNAL(clicked()), this, 
SLOT(on_label_clicked()));
    ui->click_test->setPixmap(cat);
    ui->click_test->resize(cat.width(),cat.height());

}

Of course I have promoted it to clicklabel.h and also I have added void on_label_click() to my mainwindow.h under private slots, but nothing happened.


Solution

  • Create a new class derived from QLabel, reimplement mousePressEvent to emit custom pressed() signal (or any other functionality you need)

    If you need to use your clickable label in ui files, follow these steps:

    1. Add QLabel to the form

    2. Right-click on added label and select Promote to...

    3. Enter your clickable label class name and its header file name

    4. Press add, than select your label in the tree and select promote

    enter image description here

    enter image description here

    Now you can use your subclassed label (this tutorial actually works for any subclassed widget) as any QWidget using ui->