QButtonGroups可以有复选框。但您不能将它们添加到QButtonGroup中,因为它们不继承QAbstractButton。
对于一些UI来说,能够有几个具有排他性复选框的QGroupBoxes将是非常好的。也就是说,您选中其中一个,而另一个QGroupBoxes将自动取消选中。
在理想情况下,我可以这样做:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QGroupBox, QWidget, QApplication,
QAbstractButton, QButtonGroup)
class SuperGroup(QGroupBox, QAbstractButton):
def __init__(self, title, parent=None):
super(SuperGroup, self).__init__(title, parent)
self.setCheckable(True)
self.setChecked(False)
class Example(QWidget):
def __init__(self):
super().__init__()
sg1 = SuperGroup(title = 'Super Group 1', parent = self)
sg1.resize(200,200)
sg1.move(20,20)
sg2 = SuperGroup(title = 'Super Group 2', parent = self)
sg2.resize(200,200)
sg2.move(300,20)
self.bgrp = QButtonGroup()
self.bgrp.addButton(sg1)
self.bgrp.addButton(sg2)
self.setGeometry(300, 300, 650, 500)
self.setWindowTitle('SuperGroups!')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())只要您尝试将SuperGroup添加到按钮组中,此代码就会失败。PyQt5显式不支持多重继承。但也有一些examples out in the wild, like from this blog。
在这个简单的示例中,可以很容易地以编程方式管理clicks。但是当你添加更多的组框时,它会变得更加混乱。或者,如果您想要一个具有按钮、复选框和组框的QButtonGroup呢?呃。
发布于 2020-04-25 03:21:15
没有必要创建一个继承自QGroupBox和QAbstractButton的类(另外,这在pyqt或Qt/C++中是不可能的)。解决方案是创建一个QObject,它在检查任何QGroupBox时处理其他QGroupBox的状态,我为Qt/C++的old answer实现了这一点,所以这个答案只是一个翻译:
import sys
from PyQt5.QtCore import pyqtSlot, QObject, Qt
from PyQt5.QtWidgets import QGroupBox, QWidget, QApplication, QButtonGroup
class GroupBoxManager(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self._groups = []
@property
def groups(self):
return self._groups
def add_group(self, group):
if isinstance(group, QGroupBox):
group.toggled.connect(self.on_toggled)
self.groups.append(group)
@pyqtSlot(bool)
def on_toggled(self, state):
group = self.sender()
if state:
for g in self.groups:
if g != group and g.isChecked():
g.blockSignals(True)
g.setChecked(False)
g.blockSignals(False)
else:
group.blockSignals(True)
group.setChecked(False)
group.blockSignals(False)
class Example(QWidget):
def __init__(self):
super().__init__()
sg1 = QGroupBox(
title="Super Group 1", parent=self, checkable=True, checked=False
)
sg1.resize(200, 200)
sg1.move(20, 20)
sg2 = QGroupBox(
title="Super Group 2", parent=self, checkable=True, checked=False
)
sg2.resize(200, 200)
sg2.move(300, 20)
self.bgrp = GroupBoxManager()
self.bgrp.add_group(sg1)
self.bgrp.add_group(sg2)
self.setGeometry(300, 300, 650, 500)
self.setWindowTitle("SuperGroups!")
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())https://stackoverflow.com/questions/61415536
复制相似问题