如何创建Qt标签悬停效果? [英] How to create qt label hover effect?

查看:48
本文介绍了如何创建Qt标签悬停效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在Qt标签上使用悬停事件,但找不到有关此的信息.我尝试使用类似 ui-> label-> setText(< a> ads</a>") onLinkHovered 之类的方法,但是它无法正常工作./p>

我必须在悬停时更改文本.

解决方案

最灵活的解决方案是创建自己的继承自QLabel的小部件.这样,您可以覆盖 enterEvent leaveEvent @Jeremy和@Moe编写有关受保护的内容.作为这些方法实现的一部分,您可以相应地更改文本或修饰.例如:

  CustomLabel类:公共QLabel{Q_OBJECT上市:CustomLabel(QWidget * parent = nullptr):QLabel(parent){}受保护的:void enterEvent(QEvent * ev)覆盖{setStyleSheet("QLabel {background-color:blue;}");}void LeaveEvent(QEvent * ev)覆盖{setStyleSheet("QLabel {background-color:green;}");}}; 

另一种方法,但灵活性较差的是为标签文本中指定的链接标签设置href属性.这样,文本将被视为实际链接,您可以使用linkHovered信号进行连接.例如:

  ui-> label-> setText(< a href ='www.google.com'> link</a>"));connect(ui-> label,& QLabel :: linkHovered,this,[this](const QString&){//处理小部件/文本}); 

但是,请表示这种方式只能对悬停事件进行修改.因此,如果您需要将标签恢复到其原始状态,则第一种选择是处理方法.

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.

解决方案

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.

这篇关于如何创建Qt标签悬停效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆