Stepan Vanzuriak Stepan Vanzuriak - 1 year ago 183
C++ Question

How to create qt label hover effect?

I must use hover event on Qt label, but I can't found no information about that.
I try use something like

but it's not work correct.

I must change text on hover.

Answer Source

The most flexible solution would be to create your own widget which inherits from QLabel. This way, you could override the enterEvent and leaveEvent @Jeremy and @Moe are writing about which are protected. As a part of these methods implementation you could change the text or decoration accordingly. For example:

class CustomLabel : public QLabel
    CustomLabel(QWidget* parent = nullptr) : QLabel(parent){ }

    void enterEvent(QEvent *ev) override
        setStyleSheet("QLabel { background-color : blue; }");

    void leaveEvent(QEvent *ev) override
        setStyleSheet("QLabel { background-color : green; }");

Another approach, but a lot less flexible would be to set the href attribute for the link tag you have specified in label text. This way text would be treated as actual link and you could use the linkHovered signal to connect to. For example:

ui->label->setText("<a href=''>link</a>");
connect(ui->label, &QLabel::linkHovered, this, [this](const QString&)
    // do smth with the widget/text

However, please denote that this way you could only make a modification on the hover event. So if you need to bring the label back to its original state, the first option is the way to go.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download