我想使用样式表来设置QToolButton的图标,如下所示:
#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.setText("some thing..." );
button.show();
return qapp.exec();
}我是这样编译的:
g++ -O3 -std=c++0x -Wall -Wextra -pedantic test.cpp -lQtCore -lQtGui -I/usr/include/Qt/ -I/usr/include/QtCore/ -I/usr/include/QtGui/不幸的是,上面的方法不起作用(图标没有显示)。
如果我使用setIcon,那么图标就会正确显示。
那么,我做错了什么呢?如何使用样式表设置按钮的图标?
我使用的图片是:



PS请注意,我问了类似的问题here,但一旦设置了文本,答案就不起作用了(图标都被挤压了,文本不在图标下面)。
编辑1:我也尝试了这个函数(正如Kamil Klimek建议的那样):
QString FormStyleSheetString( const QString & name )
{
const QString thisItemStyle( "QToolButton { qproperty-icon: url(" + name + "_normal.png); }; "
"QToolButton:pressed { qproperty-icon: url(" + name + "_pressed.png); }; "
"QToolButton:hover { qproperty-icon: url(" + name + "_disabled.png); }; "
);
return thisItemStyle;
}但它也不起作用。按下按钮或悬停不会改变图标。
发布于 2012-02-24 15:39:28
那天晚些时候,我设法解决了这个问题,但忘记了发布解决方案:
QString FormStyleSheetString( const QString & name )
{
const QString thisItemStyle(
"QToolButton {\n"
" border: none;\n"
" background: url(" + name + "_normal.png) top center no-repeat;\n"
" padding-top: 200px;\n"
" width: 200px;\n"
" font: bold 14px;\n"
" color: red;\n"
"}\n"
"QToolButton:hover {\n"
" background: url("+name+"_hover.png) top center no-repeat;\n"
" color: blue;\n"
"}\n"
"QToolButton:pressed {\n"
" background: url("+name+"_pressed.png) top center no-repeat;\n"
" color: gray;\n}" );
return thisItemStyle;
}仅仅设置背景是不够的。它还需要固定的大小。
https://stackoverflow.com/questions/8385309
复制相似问题