Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - 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 ui->label->setText("<a>ads</a>") and onLinkHovered but it's not work correct.

I must change text on hover.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
{
    Q_OBJECT
public:
    CustomLabel(QWidget* parent = nullptr) : QLabel(parent){ }

protected:
    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='www.google.com'>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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...