Make Qlabel clickable or double clickable in Qt

主宰稳场 提交于 2019-12-02 06:31:54
Bearded Beaver

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

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

you can use qpushbutton instead , but it you desperately need qlable , you can do this

clickable.h

class Clickable :public QLabel
    {
        Q_OBJECT
            signals :
        void clicked();
    public:
        void mousePressEvent(QMouseEvent* event);

        using QLabel::QLabel;
    };

clickable.cpp

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

UPDATE: this implementation I used in my source code. I cant past compleate code , but here is the part where i used it. source.h

...
private: 
    QLabel* label1;
    QLabel* label2;
...

source.cpp ...

label1 = new Clickable("label1 text", this);
label2 = new Clickable("label2 text", this);
...
connect(label1 , SIGNAL(clicked()), this, SLOT(label1clicked()));
connect(label2 , SIGNAL(clicked()), this, SLOT(label1clicked()));
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!