【问题标题】:How to set the QToolButton's icons using style sheet?如何使用样式表设置 QToolButton 的图标?
【发布时间】:2025-12-31 11:30:06
【问题描述】:

我想使用样式表设置 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;
}

但它也没有工作。按下按钮或悬停不会更改图标。

【问题讨论】:

  • 您设置的是图像而不是图标。试试 qproperty-icon: url()
  • @KamilKlimek 我试过了,但没用。它将设置正常图像,但不会按下并悬停。我认为是因为这个错误:bugreports.qt.nokia.com/browse/…
  • 那么您必须将其设置为图像或背景!但是!您必须使用 CSS 调整大小。
  • @KamilKlimek 如果我将其设置为背景,则文本居中。将其设置为图像不起作用(图像未显示)。
  • 你能不能用“background-image”代替“image”。

标签: c++ qt4 stylesheet


【解决方案1】:

那天晚些时候,我设法以某种方式解决了问题,但忘记发布解决方案:

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

仅仅设置背景是不够的。它还需要固定大小。

【讨论】:

    最近更新 更多