How to set a Qt button's icons using stylesheet?

99封情书 提交于 2019-12-13 06:29:11

问题


I would like to set a button's icons using stylesheets, like this :

#include <QToolButton>
#include <QApplication>

QString FormStyleSheetString( const QString & name )
{
  const QString thisItemStyle( "QToolButton:enabled { image: url(" + name + "_normal.png); }  "
                             "QToolButton:pressed { image: url(" + name + "_pressed.png); }  "
                             "QToolButton:disabled { image: url(" + name + "_disabled.png); }  "
                           );

  return thisItemStyle;
}

int main(int argc, char * argv[])
{
    QApplication qapp(argc,argv);

    QToolButton button;
    button.setStyleSheet( FormStyleSheetString( "button" ) );
    button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    button.setIconSize(QSize(200,200));
    button.show();

    return qapp.exec();
}

I compiled it like this :

g++ -O3 -std=c++0x -Wall -Wextra -pedantic test.cpp -lQtCore -lQtGui -I/usr/include/Qt/ -I/usr/include/QtCore/ -I/usr/include/QtGui/

Unfortunately, the above doesn't work (the icon is not shown).

If I use setIcon, then the icon is shown properly.

So, what am I doing wrong? How to set the button's icon using style sheet?

The images I used are :


回答1:


There was similar unanswered question before, right here. It seems that you should try setting border-image property instead of icon one.

To fix it, change FormStyleSheetString function to this :

QString FormStyleSheetString( const QString & name )
{
  const QString thisItemStyle( "QToolButton:enabled { border-image: url(" + name + "_normal.png); }  "
                               "QToolButton:pressed { border-image: url(" + name + "_pressed.png); }  "
                               "QToolButton:disabled { border-image: url(" + name + "_disabled.png); }  "
                           );

  return thisItemStyle;
}


来源:https://stackoverflow.com/questions/8382421/how-to-set-a-qt-buttons-icons-using-stylesheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!