python - 将 qtreeview 项目设置为可通过上下文菜单编辑并自动将其设置回禁用状态?

标签 python pyqt pyqt5

我正在尝试创建一个 qtreeview,其中的项目可以通过右键单击它们并从上下文菜单中选择编辑来编辑。现在我只是将项目从 TreeView 中取出并将其设置为可编辑,然后调用 item.edit()。

但我无法弄清楚它的另一面。我必须弄清楚如何在编辑字段关闭后将该项目设置回不可编辑状态。

理想情况下,我会捕获编辑框关闭后立即触发的信号,但我似乎找不到。

有什么想法吗?

编辑:我使用的是 QSortFilterProxyModel,后面有 QStandardItemModel,里面有 QStandardItems。真正的问题是这个。

qstandarditem 的编辑框关闭后是否会触发信号?

最佳答案

如果您想检测编辑器何时关闭,则必须使用委托(delegate)的 closeEditor()信号。

考虑到如果您的型号是 QStandardItemModel然后您可以启用 Qt::ItemIsEditable使用setEditable()方法QStandardItem .

from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.treeview = QtWidgets.QTreeView()
        self.treeview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeview.customContextMenuRequested.connect(
            self.on_customContextMenuRequested
        )
        self.treeview.itemDelegate().closeEditor.connect(self._on_closeEditor)
        self.setCentralWidget(self.treeview)

        self.model = QtGui.QStandardItemModel(self)
        self.treeview.setModel(self.model)

        for i in range(4):
            it = QtGui.QStandardItem(f"{i}")
            it.setEditable(False)
            self.model.appendRow(it)
            for j in range(5):
                child_it = QtGui.QStandardItem(f"{i}-{j}")
                child_it.setEditable(False)
                it.appendRow(child_it)

        self.treeview.expandAll()

    @QtCore.pyqtSlot("QWidget*")
    def _on_closeEditor(self, editor):
        p = editor.pos()
        index = self.treeview.indexAt(p)
        if not index.isValid():
            return
        it = self.model.itemFromIndex(index)
        it.setEditable(False)

    @QtCore.pyqtSlot(QtCore.QPoint)
    def on_customContextMenuRequested(self, pos):
        index = self.treeview.indexAt(pos)
        if not index.isValid():
            return
        menu = QtWidgets.QMenu()
        edit_action = menu.addAction("&Edit")
        action = menu.exec_(self.treeview.viewport().mapToGlobal(pos))
        if action == edit_action:
            it = self.model.itemFromIndex(index)
            it.setEditable(True)
            self.treeview.edit(index)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MainWindow()
    w.show()

    sys.exit(app.exec_())

关于python - 将 qtreeview 项目设置为可通过上下文菜单编辑并自动将其设置回禁用状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018135/

相关文章:

python - 慢慢改变 BigQuery 的查找缓存 - Dataflow Python Streaming SDK

python - 如何将 slider 连接到 PyQt4 中的函数?

python - PyQT 图形用户界面测试

python - 在 Python 中使用 PyQt4 向 QTableWidget 添加数据

python - 使用字典转换 tensorflow 数组中的元素

Python 3 中忽略的 Python 单元测试预期失败

python - 有效地从二维似然矩阵(numpy 数组)中提取局部最大值(坐标)

python - 在虚拟环境中使用 PyQt5 时出现致命 Python 错误

python - 如何在这段代码上应用 PyQt QThread

python - PyQt5 在 Qtextedit 上发出点击信号