我正在尝试创建一个 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/