Qt复选框/工具按钮,带有自定义/不同的检查/未选中图标

时间:2011-05-11 10:06:23

标签: c++ qt

我需要一个像控件这样的复选框,其中已选中状态和未选中状态使用自定义图形。我查看了QToolButton和QCheckBox的所有文档,以及QIcon,但找不到任何符合我想要的组合。

我只想在未检查状态下使用一个图标(实际上是pixmap),在检查状态下使用另一个图标。

这感觉应该很容易,但解决方案(缺少自定义控件)让我望而却步。


我也尝试过使用样式表,QToolButton:checked使用background-image种作品,但我无法正确使用布局 - 它没有像图标那样定位/调整大小

4 个答案:

答案 0 :(得分:19)

使用::指标子项。下面的代码对我来说非常好......

 QCheckBox::indicator {
     width: 18px;
     height: 18px;
 }

  QCheckBox::indicator:checked
  {
    image: url(.../Checkbox_checked_normal.png);
  }
  QCheckBox::indicator:unchecked
  {
    image: url(.../Checkbox_unchecked_normal.png);
  }

  QCheckBox::indicator:checked:hover
  {
    image: url(.../Checkbox_checked_hovered.png);
  }
  QCheckBox::indicator:unchecked:hover
  {
    image: url(.../Checkbox_unchecked_hovered.png);
  }
  QCheckBox::indicator:checked:pressed
  {
    image: url(.../Checkbox_checked_pressed.png);
  }
  QCheckBox::indicator:unchecked:pressed
  {
    image: url(.../Checkbox_unchecked_pressed.png);
  }
  QCheckBox::indicator:checked:disabled
  {
    image: url(.../Checkbox_checked_disabled.png);
  }
  QCheckBox::indicator:unchecked:disabled
  {
    image: url(.../Checkbox_unchecked_disabled.png);
  }

答案 1 :(得分:3)

必须将其输入为StyleSheet。通过设计编辑器右键单击复选框并选择“更改样式表...”来执行此操作。

答案 2 :(得分:0)

感谢您的帮助! 为了在Maya中使用,我使用了:

from PySide2 import QtWidgets
import os
ICON = os.path.join(os.path.dirname(__file__), '_icons//').replace("\\", "//")

ui.setStyleSheet("""
QGroupBox::indicator {width: 14px; height: 14px;}
QGroupBox::indicator:checked {image: url(""" + ICON + """arrow_down.png);}
QGroupBox::indicator:Unchecked {image: url(""" + ICON + """arrow_right.png);}
QGroupBox::indicator:checked:hover {image: url(""" + ICON + """arrow_down_hover.png);}
QGroupBox::indicator:Unchecked:hover {image: url(""" + ICON + """arrow_right_hover.png);}
""")

用反斜杠替换反斜杠非常重要,因为如果这种方式的路径不统一,图像将不会显示。

答案 3 :(得分:0)

您还可以包括图标并将其用作资源:

QCheckBox::indicator:checked {image: url(:/circle-green.png);}
QCheckBox::indicator:unchecked {image: url(:/circle-red.png);}