我想使用样式表设置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;
}
但它也没有用。按下按钮或悬停,不会更改图标。
答案 0 :(得分:8)
那天晚些时候,我设法以某种方式解决了问题,但忘了发布解决方案:
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;
}
仅仅设置背景是不够的。它还需要修复尺寸。