Search code examples
pythonpyqtpyqt4contextmenuqtreeview

Custom context menu in QTreeView


I currently have this dialog widget:

class TaskTypeTreeEditor(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._view = QTreeView()
        self._view.setItemDelegate(TaskTypeNameDelegate())
        self._view.setContextMenuPolicy(Qt.CustomContextMenu)
        self._view.customContextMenuRequested.connect(self._open_menu)

        self._refresh()

        layout = QVBoxLayout()
        layout.addWidget(self._view)

        self.setLayout(layout)
        self.setWindowTitle(_('Admin.editTaskType'))

    def _open_menu(self, position):
        indexes = self._view.selectedIndexes()
        if len(indexes) == 0:
            return

        menu = QMenu()
        ids = [index.internalPointer().type_id for index in indexes]

        if len(indexes) == 1:
            NewTypeAction(ids[0], self._refresh, menu)

        DeleteTypeAction(ids, self._refresh, menu)

        menu.exec_(self._view.viewport().mapToGlobal(position))

    def _refresh(self):
        model = TaskTypeTreeModel()
        self._view.setModel(model)
        self._view.expandAll()

This was based on another design from the Python wiki. Assuming NewTypeAction and DeleteTypeAction are subclasses of QAction and their constructors appropriately call QAction.__init__ with the parent of menu, why when I right click in my view doesn't a menu appear?


Solution

  • Got it figured out. I forgot to call menu.addAction for both of my new actions.