在悬停并按下时更改 QPushButton 图标 [英] Change QPushButton Icon on hover and pressed

查看:51
本文介绍了在悬停并按下时更改 QPushButton 图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在悬停和按下时更改 QpushButton 的图标,我正在使用带有样式表的 QtDesigner.我试过这个

I'm trying to change the Icon of a QpushButton on hover and pressed, I'm using QtDesigner with stylesheets. I tried this

QpushButton{
       qproperty-icon:url(:/images/start.png);
}

QPushButton:hover
{
       qproperty-icon:url(:/images/start_hov.png);
}

但它不起作用.

我尝试从 QtDesigner 菜单进行设置但效果不佳.

推荐答案

不幸的是,它是一个 Qt 的 bug 仍未修复.有一个 解决方法建议 在对该错误的评论中,基本上您可以使用空的 qproperty-icon 并保留所需的空间,同时实际更改 background-image 属性:

Unfortunately, it is a bug of Qt which is still not fixed. There's a workaround suggestion within the comments to that bug, basically you could use empty qproperty-icon and reserve the space necessary for it while actually changing background-image property instead:

QPushButton {
    qproperty-icon: url(" "); /* empty image */
    qproperty-iconSize: 16px 16px; /* space for the background image */
    background-image: url(":/images/start.png");
    background-repeat: no-repeat;
}

QPushButton:hover {
    background-image: url(":/images/start_hov.png");
    background-repeat: no-repeat;
}

但最终结果看起来……真的不是很令人满意.如果您在运行时使用 C++ 更改按钮的图标,您可以获得更好的结果,这是一个使用事件过滤器的简单示例:

But the end result looks... not very satisfactory really. You can get much better results if you use C++ to change the button's icon at runtime, here's a simple example using event filter:

#include <QObject>
#include <QPushButton>
#include <QEvent>

class ButtonHoverWatcher : public QObject
{
    Q_OBJECT
public:
    explicit ButtonHoverWatcher(QObject * parent = Q_NULLPTR);
    virtual bool eventFilter(QObject * watched, QEvent * event) Q_DECL_OVERRIDE;
};

ButtonHoverWatcher::ButtonHoverWatcher(QObject * parent) :
    QObject(parent)
{}

bool ButtonHoverWatcher::eventFilter(QObject * watched, QEvent * event)
{
    QPushButton * button = qobject_cast<QPushButton*>(watched);
    if (!button) {
        return false;
    }

    if (event->type() == QEvent::Enter) {
        // The push button is hovered by mouse
        button->setIcon(QIcon(":/images/start_hov.png"));
        return true;
    }

    if (event->type() == QEvent::Leave){
        // The push button is not hovered by mouse
        button->setIcon(QIcon(":/images/start.png"));
        return true;
    }

    return false;
}

然后在您的代码中设置用户界面,您可以执行以下操作:

Then somewhere in your code setting up the UI you do something like this:

ButtonHoverWatcher * watcher = new ButtonHoverWatcher(this);
ui->pushButton->installEventFilter(watcher);

还有宾果游戏 - 您可以在悬停和取消悬停时更改按钮的图标!

And bingo - you get the button's icon changing on hover and unhover!

这篇关于在悬停并按下时更改 QPushButton 图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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