Python PyQt4本地目录视图,具有选择文件夹的选项
我知道如何使用QDirModel(或QFileSystemModel)制作一个简单的QTreeView(),以显示系统中的文件/文件夹,但我想在每个文件/文件夹旁边添加一个复选框,以便用户可以选择系统中的一些文件夹/文件。显然,我还需要知道他选择了哪些。有什么提示吗 基本上是这样的 下面是生成目录视图的示例代码,但没有复选框Python PyQt4本地目录视图,具有选择文件夹的选项,python,qt,pyqt,pyqt4,Python,Qt,Pyqt,Pyqt4,我知道如何使用QDirModel(或QFileSystemModel)制作一个简单的QTreeView(),以显示系统中的文件/文件夹,但我想在每个文件/文件夹旁边添加一个复选框,以便用户可以选择系统中的一些文件夹/文件。显然,我还需要知道他选择了哪些。有什么提示吗 基本上是这样的 下面是生成目录视图的示例代码,但没有复选框 from PyQt4 import QtGui if __name__ == '__main__': import sys app = QtGui.
from PyQt4 import QtGui
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
model = QtGui.QDirModel()
tree = QtGui.QTreeView()
tree.setModel(model)
tree.setAnimated(False)
tree.setIndentation(20)
tree.setSortingEnabled(True)
tree.setWindowTitle("Dir View")
tree.resize(640, 480)
tree.show()
sys.exit(app.exec_())
您可以将QDirModel子类化,并重新实现
数据(索引,角色)
方法,如果角色
是QtCore.Qt.CheckStateRole
,则应在该方法中进行检查。如果是,则应返回QtCore.Qt.Checked
或QtCore.Qt.Unchecked
。此外,您还需要重新实现setData
方法来处理用户检查/取消检查,以及flags
来返回QtCore.Qt.ItemIsUserCheckable标志,该标志启用用户检查/取消检查。即:
class CheckableDirModel(QtGui.QDirModel):
def __init__(self, parent=None):
QtGui.QDirModel.__init__(self, None)
self.checks = {}
def data(self, index, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.CheckStateRole:
return QtGui.QDirModel.data(self, index, role)
else:
if index.column() == 0:
return self.checkState(index)
def flags(self, index):
return QtGui.QDirModel.flags(self, index) | QtCore.Qt.ItemIsUserCheckable
def checkState(self, index):
if index in self.checks:
return self.checks[index]
else:
return QtCore.Qt.Unchecked
def setData(self, index, value, role):
if (role == QtCore.Qt.CheckStateRole and index.column() == 0):
self.checks[index] = value
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index)
return True
return QtGui.QDirModel.setData(self, index, value, role)
然后使用该类而不是QDirModel
:
model = CheckableDirModel()
tree = QtGui.QTreeView()
tree.setModel(model)
这很好,但是你知道如何修改它吗?当你点击C:然后所有子类别都被点击,当你点击一个子类别C:变成一个点(半选中)?@Kiarash你应该相应地改变
setData
中index
的子索引和父索引。要获取子索引,请使用QModelIndex.child
。要获取父索引,请使用QModelIndex.parent
。要获得给定索引的多个子项,应使用QDirModel.rowCount
。在setData中,我简单地添加了以下内容:for I in range(self.rowCount(index)):self.setData(index.child(I,0),value,role),但是如果单击C:,速度会非常慢。有什么办法解决这个问题吗?@Kiarash速度很慢,因为它必须遍历整个层次结构并将其添加到列表中。另一种方法是存储未检查的索引,而是检查项的路径。然后在checkState
中,您可以检查文件路径是否在self.checks
中,或者给定文件路径的前缀是否在self.checks
中。您是说当您选中一个框时,路径进入一个字典,当我们检查foo/bar/text.dat时,我们首先检查foo是否在字典中,或者foor/bar是否在字典中,或者foo/bar/text.dat。。。