【问题标题】:PyQt4 Local Directory view with option to select foldersPyQt4 本地目录视图,带有选择文件夹的选项
【发布时间】:2013-03-12 05:29:28
【问题描述】:

我知道如何使用 QDirModel(或 QFileSystemModel)制作一个简单的 QTreeView() 来显示系统中的文件/文件夹,但我想在每个文件/文件夹旁边添加一个复选框,以便用户可以选择一些文件夹/文件在他的系统上。显然,我还需要知道他选择了哪些。有什么提示吗?

基本上是这样的......

以下是创建目录视图但没有复选框的示例代码。

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_())

【问题讨论】:

    标签: python qt pyqt pyqt4


    【解决方案1】:

    您可以继承 QDirModel,并重新实现 data(index,role) 方法,您应该在其中检查 role 是否为 QtCore.Qt.CheckStateRole。如果是,您应该返回QtCore.Qt.CheckedQtCore.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。见thisthis
    • 所以在 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 是否在字典中或 foo/ bar 是或者如果 foo/bar/text.dat ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多