2016-10-29 7 views
1

ホバー上のQpushButtonのアイコンを変更しようとしていますが、QtDesignerをスタイルシートと共に使用しています。 私はこれを試しましたホバー上のQPushButtonアイコンを変更して押した

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

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

しかし、それは動作しません。

I tried setting it from QtDesigner Menu でも機能しませんでした。

答えて

2

残念ながら、まだ修正されていないbug of Qtです。

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; 
} 

しかし、最終結果は、実際には非常に満足のいくものではない...になります。実際には代わりにbackground-imageプロパティを変更しながら、基本的には空のqproperty-iconを使用して、それのために必要なスペースを確保でき、そのバグへのコメント内workaround suggestionあります。あなたはこのような何かを行うUIをどこかにあなたのコード内で次に

#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; 
} 

設定:あなたは、実行時にボタンのアイコンを変更するには、C++を使用する場合は、より良い結果を得ることができ、ここでイベントフィルタを使用した簡単な例です

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

ビンゴ - あなたは、ホバリングとアンハーバーでボタンのアイコンが変化します!

+0

QIconオブジェクトは、モードに応じて、最大で4枚の画像を含めることができます。これらの画像を作成した後、Qtに残りの画像を簡単に設定する方が簡単でしょうか? – RobbieE

+0

私はこのアプローチを働かせることができず、Qt Designerからアイコンイメージを設定しようとしているトピックスターターもいませんでした。このアプローチの実例を別の回答で提示してください。 – Dmitry

0

私は、UI _...時間ファイルから、デザイナーでそれを集約した:

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); 
関連する問題