我有一个treeWidget,在其上调用customContextMenu。 但是我无法获得调用它的widgetItem。
我尝试阅读文档,但一无所获
小工具:
self.treeWidget = QtWidgets.QTreeWidget(self.centralwidget)
self.treeWidget.headerItem().setText(0, "Database Explorer")
self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.treeWidget.customContextMenuRequested.connect(self.openMenu)
def openMenu(self,position):
menu = QtWidgets.QMenu()
deleteAction = menu.addAction("Delete")
showAction = menu.addAction("Show")
action = menu.exec_(self.treeWidget.mapToGlobal(position))
if action == deleteAction:
self.my_function(treeWidgetItemObject)
我想获取在my_function()中调用contextMenu的treeWidgetItem对象
答案 0 :(得分:1)
如果要获取与按下的项目关联的QModelIndex或QTreeWidgetItem返回的indexAt()
,则必须使用itemAt()
def openMenu(self,position):
menu = QtWidgets.QMenu()
deleteAction = menu.addAction("Delete")
showAction = menu.addAction("Show")
pos = self.treeWidget.viewport().mapToGlobal(position)
action = menu.exec_(pos)
if action == deleteAction:
ix = self.treeWidget.indexAt(position)
if ix.isValid():
print(ix.data())
it = self.treeWidget.itemFromIndex(ix)
texts = [it.text(c) for c in range(it.columnCount())]
print(texts)