【问题标题】:How to set ItemFlag in QTreeView or QListView?如何在 QTreeView 或 QListView 中设置 ItemFlag?
【发布时间】:2021-02-01 11:35:22
【问题描述】:

更新1: 基于 QFileSystemModel() 的 QTreeView。

如何在指定的树项上“setFlags”?

在子类 QFileSystemModel() 中?

class MyTreeModel(QFileSystemModel):
    def __init__(self, parent=None):
        super(MyTreeModel, self).__init__(parent)
        # fake code:
        if current_index.parent() == treeView.rootIndex():
            # it is a second level folder.
            # set this tree item not selectable.
            current_index.setFlags(^ Qt.ItemIsSelectable)

【问题讨论】:

  • 什么项目和基于什么?该标志可以在运行时出于任何原因更改吗?模型是静态的还是布局发生变化?标志总是由模型提供(意味着flags()必须重新实现);如果您希望能够以编程方式为特定索引设置标志,则应保留每个索引及其自定义标志(如果有)的内部引用。也就是说,请先提供minimal, reproducible example,这个问题太宽泛了。

标签: python pyqt5 pyside2


【解决方案1】:

我从这里得到灵感: TreeView in Python+QT

与setData()类似,不能将setData()设置为QFileSystemModel,但可以修改data()在从模型中读取数据时添加代码。

你不能直接setFlags()到QFileSystemModel,但是你可以修改flags()来改变返回的数据。

class MyTreeModel(QtWidgets.QFileSystemModel):
    #...
    def flags(self, index):
        flags = super(MyTreeModel, self).flags(index)
        # Determine directory level.
        if self.index_level(index) == 2:
            flags = flags ^ QtCore.Qt.ItemIsSelectable
        return flags

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2015-11-20
    相关资源
    最近更新 更多