import sys
from PyQt5 import QtCore
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QTreeView, QMenu, QAction, QApplication
class TreeView(QTreeView):
def __init__(self):
super().__init__()
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.menu = self.create_menu()
self.customContextMenuRequested.connect(self.open_menu)
def create_menu(self) -> QMenu:
menu = QMenu() # Передавать self пробовал, не помогает.
menu.addAction(QAction("Action 1"))
menu.addAction(QAction("Action 2"))
return menu
def open_menu(self, position) -> QMenu:
print(position)
print("Open menu")
action = self.menu.exec(self.viewport().mapToGlobal(position))
print(action)
# Так тоже пробовал
# self.menu.popup(self.viewport().mapToGlobal(position))
if __name__ == "__main__":
app = QApplication(sys.argv)
model = QStandardItemModel()
for i in range(2):
item = QStandardItem("Item {}".format(i))
for j in range(2):
item.appendRow(QStandardItem("Sub item {}".format(j)))
model.appendRow(item)
window = TreeView()
window.setModel(model)
window.show()
sys.exit(app.exec_())
PyQt5.QtCore.QPoint(62, 23)
Open menu
def addAction(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
"""
addAction(self, QAction)
addAction(self, str) -> QAction
addAction(self, QIcon, str) -> QAction
addAction(self, str, PYQT_SLOT, shortcut: Union[QKeySequence, QKeySequence.StandardKey, str, int] = 0) -> QAction
addAction(self, QIcon, str, PYQT_SLOT, shortcut: Union[QKeySequence, QKeySequence.StandardKey, str, int] = 0) -> QAction
"""
return QAction