我正在尝试创建一个树状视图,以允许用户更改所有选定项的复选框状态。因此,如果用户单击树视图中的项目并更改其检查状态,则所有其他选定项目应与被单击项目的当前检查状态相匹配。
我不太确定自己做的正确。我注意到我特意单击的项目似乎总是与我在qtreeview中将其他所有内容设置为相反。在这种情况下,我选择了 Chester ,它会暂时检查为真,然后翻转以取消选中。
第二,我只能使更改状态仅在用户单击实际复选框时才更改。当我做出选择时,我注意到它会发生变化。
from PySide import QtGui, QtCore
from PySide import QtSvg, QtXml
import sys
class Person:
def __init__(self, name="", children=None):
self.name = name
self.children = children if children else []
class TreeView(QtGui.QTreeView):
def __init__(self, **args):
super(TreeView, self).__init__(**args)
self.setHeaderHidden(True)
self.setUniformRowHeights(True)
self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
index = self.indexAt(event.pos())
if index.isValid():
# get selected items
items = []
selection = self.selectionModel().selectedRows()
for index in selection:
model = index.model()
items.append(model.itemFromIndex(index))
# returns what the value is before it changes...
value = index.data(role=QtCore.Qt.CheckStateRole) == QtCore.Qt.Checked
state = QtCore.Qt.Unchecked if value else QtCore.Qt.Checked
for x in items:
if x.isCheckable():
x.setData(state, role=QtCore.Qt.CheckStateRole)
super(self.__class__, self).mousePressEvent(event)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(300, 400)
self.treeview = TreeView()
self.treeview.setModel(QtGui.QStandardItemModel())
self.setCentralWidget(self.treeview)
self.populate()
def populate(self):
parent = Person("Kevin", [
Person("Tom", [Person("Sally"), Person("Susan")]),
Person("Snappy", [Person("John"), Person("Kimmy"),
Person("Joe")]),
Person("Chester", [Person("Danny"), Person("Colleen")])
]
)
self.create_nodes(parent, self.treeview.model())
self.treeview.expandAll()
def create_nodes(self, node, parent):
tnode = QtGui.QStandardItem()
tnode.setCheckable(True)
tnode.setData(QtCore.Qt.Unchecked, role=QtCore.Qt.CheckStateRole)
tnode.setData(node.name , role=QtCore.Qt.DisplayRole)
tnode.setData(node, role=QtCore.Qt.UserRole) # store object on item
parent.appendRow(tnode)
for x in node.children:
self.create_nodes(x, tnode)
def main():
app = QtGui.QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()