如果复选框已修改,我试图覆盖QTreeView
来处理对父母和子女的调整。但是,我无法发出信号,也不确定是否是因为我试图继承QtGui
而不是QtWidgets
的子类。
以下是将触发错误的代码:
class QStandardItem(QtGui.QStandardItem):
someSignal = QtCore.Signal()
def __init__(self, *args, **kwargs):
QtGui.QStandardItem.__init__(self, *args, **kwargs)
self.someSignal.emit()
>>> QStandardItem()
# AttributeError: 'PySide2.QtCore.Signal' object has no attribute 'emit' #
这是我当前的代码,仅供参考:
class QStandardItem(QtGui.QStandardItem):
checkStateChanged = QtCore.Signal(object)
def __init__(self, *args, **kwargs):
QtGui.QStandardItem.__init__(self, *args, **kwargs)
def setData(self, data, role):
if role == QtCore.Qt.CheckStateRole:
self.checkStateChanged.emit(self)
QtGui.QStandardItem.setData(self, data, role)
class QTreeView(QtWidgets.QTreeView):
def __init__(self, *args, **kwargs):
QtWidgets.QTreeView.__init__(self, *args, **kwargs)
#I need to know when to trigger this as it edits other nodes
def checkStateChanged(self, model_index):
selected_item = self.model().itemFromIndex(model_index)
check_state = selected_item.checkState()
#Handle child nodes
for i in range(selected_item.rowCount()):
child_item = selected_item.child(i)
if child_item.isCheckable():
child_item.setCheckState(check_state)
#Handle parent nodes
parent_item = selected_item.parent()
check_states = {QtCore.Qt.Checked: 0,
QtCore.Qt.PartiallyChecked: 1,
QtCore.Qt.Unchecked: 2}
counts = [0, 0, 0]
if parent_item is not None:
for i in range(parent_item.rowCount()):
child_item = parent_item.child(i)
if child_item.isCheckable():
counts[check_states[child_item.checkState()]] += 1
if counts[0] and not counts[1] and not counts[2]:
parent_item.setCheckState(QtCore.Qt.Checked)
elif not counts[0] and not counts[1] and counts[2]:
parent_item.setCheckState(QtCore.Qt.Unchecked)
else:
parent_item.setCheckState(QtCore.Qt.PartiallyChecked)
答案 0 :(得分:1)
正如您已经指出的那样,仅继承自QObject
的类可以发出信号,QStandardItem
不是QObject
,因此会产生此问题。适当的选项是使用QStandardItemModel,为此,我们覆盖setData()
方法并建立逻辑以验证状态是否已更改,然后使用QStandardItem
方法发出itemFromIndex()
,该方法返回给定QStandardItem
的{{1}}。
示例:
QModelIndex
答案 1 :(得分:0)
不是100%肯定,但是对于Python来说,要定义自己的信号,您必须使用:
QtCore.pyqtSignal()
此外,您可能还需要继承QtCore.QObject
才能使用信号
编辑:刚刚看到您在使用pyside,因此取消了第一个解决方案,但是继承QObject是您的解决方案