悬停并按下时更改QPushButton图标

Zey*_*aia 4 qt qt-designer qstylesheet

我试图在悬停并按下时更改QpushButton的图标,将QtDesigner与样式表一起使用。我试过了

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

QPushButton:hover
{
       qproperty-icon:url(:/images/start_hov.png);
}
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。

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

Dmi*_*try 7

不幸的是,这是Qt错误,目前尚未修复。在该错误的注释中有一个变通建议,基本上可以使用empty qproperty-icon并为其保留必要的空间,而实际上是更改background-image属性:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

ButtonHoverWatcher * watcher = new ButtonHoverWatcher(this);
ui->pushButton->installEventFilter(watcher);
Run Code Online (Sandbox Code Playgroud)

宾果游戏-您会在悬停和悬停时更改按钮的图标!