2016-10-29 48 views

回答

2

不幸的是,它是一個bug of Qt,它仍然沒有修復。還有的意見是錯誤內workaround suggestion,基本上你可以使用空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; 
} 

但最終的結果看起來...真的不是很理想。如果你使用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; 
} 

然後地方在你的代碼設置你做這樣的事情的UI:

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

和賓果 - 你得到的按鈕的圖標改變懸停和不停!

+0

QIcon對象可以含有至多根據模式4倍的圖像。在創建時設置這些圖像並讓Qt完成剩下的工作並不容易嗎? – RobbieE

+0

我無法獲得這種方法的工作,也沒有試圖從Qt Designer設置圖標圖像的topicstarter。你能否通過另一個答案提供一個這種方法的工作示例? – Dmitry

0

我maked它在設計器中,從UI _... .h文件:

QIcon icon; 
icon.addFile(QStringLiteral(":/unpressed.png"), QSize(), QIcon::Normal, QIcon::Off); 
icon.addFile(QStringLiteral(":/pressed.png"), QSize(), QIcon::Normal, QIcon::On); 
pushButton->setIcon(icon);