我修改了 QGroupBox 复选框的行为以隐藏/显示组的子项,有效地充当扩展器。它工作得很好,但唯一的问题是默认的复选框图标看起来像是用于启用/禁用该组,而不是扩展它。我想用扩展器样式的图标替换它。
我发现这篇文章几乎回答了我的问题(最终我可能不得不使用该解决方案):Change PySide QGroupBox checkbox image。问题是,那里提供的答案建议使用自定义复选框图像,而我想使用内置的特定于操作系统的扩展器,例如 QTreeView 中的扩展器,在我的电脑上看起来像这样:
这可能吗?扩展器是否被视为程式化的复选框或完全是其他东西?我对 Qt 相当陌生,所以我不太熟悉如何处理样式。这是我能够查询的东西吗?如果是的话,它是否与 QCheckBox 样式兼容?除了启用/禁用扩展器之外,我在 QTreeView 文档页面上找不到太多关于扩展器的信息,而且我目前正在尝试挖掘 QTreeView.cpp 源代码以弄清楚它们是如何工作的。
更新
离开 eyllanesc 的答案,我越来越接近解决方案,但我遇到了一些覆盖 QProxyStyle 方法的问题。我正在尝试做类似以下的事情:
class GroupBoxExpanderStyle(QtWidgets.QProxyStyle):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._replaceCheckboxWithExpander = False
def drawComplexControl(self, control, option, painter, widget):
try:
if control == QtWidgets.QStyle.CC_GroupBox and widget.isCheckable():
self._replaceCheckboxWithExpander = True
super().drawComplexControl(control, option, painter, widget)
finally:
self._replaceCheckboxWithExpander = False
def drawPrimitive(self, element, option, painter, widget):
if element == QtWidgets.QStyle.PE_IndicatorCheckBox and self._replaceCheckboxWithExpander:
indicatorBranchOption = ... # Set up options for drawing PE_IndicatorBranch
super().drawPrimitive(QtWidgets.QStyle.PE_IndicatorBranch, indicatorBranchOption, painter, widget)
else:
super().drawPrimitive(element, option, painter, widget)
此代码中似乎已经完成了类似的操作。我遇到的问题是,我的重写
drawPrimitive()
函数根本没有被 QGroupBox 小部件调用......但它被应用了相同代理样式的其他小部件调用!查看qcommonstyle.cpp的
drawComplexControl()
函数,CC_GroupBox
案例正在调用
proxy()->drawPrimitive(PE_IndicatorCheckBox, &box, p, widget);
绘制复选框,所以我不明白为什么我的重写函数没有运行。
我不太确定如何调试它,因为我无法进入 C++ 代码来查看实际调用的内容。谁能提供任何建议来帮助我弄清楚为什么我的被覆盖的
drawPrimitive()
没有被调用?
更新2:
我已经解决了为什么我的重写的
drawPrimitive()
没有被调用的谜团 - 这是因为我的应用程序使用根级样式表,这导致 QStyleSheetStyle
被用作小部件的活动样式。 QStyleSheetStyle
直接调用 drawPrimitive()
自己的 CC_GroupBox
方法,而不是调用 proxy()->drawPrimitive()
- 这对我来说似乎是一个错误,事实上 这个 Qt bug 表明样式表与 QProxyStyle
不能很好地混合
。我将尝试不再使用样式表。
eyllanesc 的技术适用于 Fusion 风格,所以我接受了他的答案,但它与其他风格不兼容。
一种可能的解决方案是实现 QProxyStyle:
from PySide2 import QtCore, QtGui, QtWidgets
class GroupBoxProxyStyle(QtWidgets.QProxyStyle):
def subControlRect(self, control, option, subControl, widget):
ret = super(GroupBoxProxyStyle, self).subControlRect(
control, option, subControl, widget
)
if (
control == QtWidgets.QStyle.CC_GroupBox
and subControl == QtWidgets.QStyle.SC_GroupBoxLabel
and widget.isCheckable()
):
r = self.subControlRect(
QtWidgets.QStyle.CC_GroupBox,
option,
QtWidgets.QStyle.SC_GroupBoxCheckBox,
widget,
)
ret.adjust(r.width(), 0, 0, 0)
return ret
def drawComplexControl(self, control, option, painter, widget):
is_group_box = False
if control == QtWidgets.QStyle.CC_GroupBox and widget.isCheckable():
option.subControls &= ~QtWidgets.QStyle.SC_GroupBoxCheckBox
is_group_box = True
super(GroupBoxProxyStyle, self).drawComplexControl(
control, option, painter, widget
)
if is_group_box and widget.isCheckable():
opt = QtWidgets.QStyleOptionViewItem()
opt.rect = self.proxy().subControlRect(
QtWidgets.QStyle.CC_GroupBox,
option,
QtWidgets.QStyle.SC_GroupBoxCheckBox,
widget,
)
opt.state = QtWidgets.QStyle.State_Children
opt.state |= (
QtWidgets.QStyle.State_Open
if widget.isChecked()
else QtWidgets.QStyle.State_None
)
self.drawPrimitive(
QtWidgets.QStyle.PE_IndicatorBranch, opt, painter, widget
)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
style = GroupBoxProxyStyle(app.style())
app.setStyle(style)
w = QtWidgets.QGroupBox(title="Exclusive Radio Buttons")
w.setCheckable(True)
vbox = QtWidgets.QVBoxLayout()
for text in ("Radio button 1", "Radio button 2", "Radio button 3"):
radiobutton = QtWidgets.QRadioButton(text)
vbox.addWidget(radiobutton)
vbox.addStretch(1)
w.setLayout(vbox)
w.resize(320, 240)
w.show()
sys.exit(app.exec_())
更新:
OP提供的code到Python的转换如下:
from PySide2 import QtCore, QtGui, QtWidgets
class GroupBoxProxyStyle(QtWidgets.QProxyStyle):
def drawPrimitive(self, element, option, painter, widget):
if element == QtWidgets.QStyle.PE_IndicatorCheckBox and isinstance(
widget, QtWidgets.QGroupBox
):
super().drawPrimitive(
QtWidgets.QStyle.PE_IndicatorArrowDown
if widget.isChecked()
else QtWidgets.QStyle.PE_IndicatorArrowRight,
option,
painter,
widget,
)
else:
super().drawPrimitive(element, option, painter, widget)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
style = GroupBoxProxyStyle(app.style())
app.setStyle(style)
w = QtWidgets.QGroupBox(title="Exclusive Radio Buttons")
w.setCheckable(True)
vbox = QtWidgets.QVBoxLayout()
for text in ("Radio button 1", "Radio button 2", "Radio button 3"):
radiobutton = QtWidgets.QRadioButton(text)
vbox.addWidget(radiobutton)
vbox.addStretch(1)
w.setLayout(vbox)
w.resize(320, 240)
w.show()
sys.exit(app.exec_())
这可以仅使用样式表来完成:
setStyleSheet('''
QGroupBox::indicator::unchecked {
image: url(:/unchecked-icon.png);
}
QGroupBox::indicator::checked {
image: url(:/checked-icon.png);
}''')
这是一个完整的例子:
from typing import Tuple, Dict
from PySide6.QtCore import QTemporaryFile
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QGroupBox, QVBoxLayout, QHBoxLayout, QLabel, QSizePolicy, QScrollArea, QWidget, QSpacerItem
class CollapsableGroupBox(QGroupBox):
def __init__(self, expanded: bool, title: str, parent=None):
super().__init__(parent)
# Keep a reference to the temporary files to prevent them from being garbage collected
self.icon_keep_alive: Dict[Tuple[QIcon.ThemeIcon, int], QTemporaryFile | None] = {}
# Set up the group box
self.setTitle(title)
self.setCheckable(True)
self.setChecked(expanded)
self.on_toggle(expanded)
self.toggled.connect(self.on_toggle)
# Add some content
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.scroll_area = QScrollArea()
self.layout.addWidget(self.scroll_area)
self.scroll_area_widget = QWidget()
self.scroll_area.setWidget(self.scroll_area_widget)
self.scroll_area_layout = QVBoxLayout()
self.scroll_area_widget.setLayout(self.scroll_area_layout)
self.scroll_area.setWidgetResizable(True)
for icon in QIcon.ThemeIcon:
layout = QHBoxLayout()
icon_label = QLabel(icon.name)
icon_label.setPixmap(QIcon.fromTheme(icon).pixmap(32))
icon_label.setMinimumWidth(32)
layout.addWidget(icon_label)
layout.addWidget(QLabel(icon.name))
layout.addSpacerItem(QSpacerItem(0, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum))
self.scroll_area_layout.addLayout(layout)
# Set up the stylesheet
self.setStyleSheet(f'''
QGroupBox {{
border: 1px solid gray;
border-radius: 3px;
margin-top: 0.5em;
}}
QGroupBox::title {{
subcontrol-origin: margin;
subcontrol-position: top left;
padding-left: 4px;
padding-right: 8px;
left: 2px;
}}
QGroupBox:flat {{
border: none;
}}
QGroupBox::indicator::unchecked {{
image: url({self.get_icon(QIcon.ThemeIcon.GoNext, 32)});
}}
QGroupBox::indicator::checked {{
image: url({self.get_icon(QIcon.ThemeIcon.GoDown, 32)});
}}
''')
def on_toggle(self, checked: bool):
self.setMaximumHeight(16777215 if checked else 20)
self.setFlat(not checked)
def get_icon(self, icon: QIcon.ThemeIcon, size: int) -> str:
"""Create a temporary file with the icon and return the file path"""
temp_file: QTemporaryFile | None = None
if icon in self.icon_keep_alive:
temp_file = self.icon_keep_alive[(icon, size)]
else:
q_icon = QIcon.fromTheme(icon)
if not q_icon.isNull():
temp_file = QTemporaryFile()
if not temp_file.open():
temp_file = None
else:
q_icon.pixmap(size).save(temp_file.fileName(), 'PNG')
self.icon_keep_alive[(icon, size)] = temp_file
return temp_file.fileName()