Add context menu to QListWidget

How can I add a context menu (right click) to a QListWidget object?

A simple example

#!/usr/bin/env python3

import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, 
                             QListWidget, QMenu)
from PyQt6.QtGui import QIcon, QCursor, QAction
from PyQt6.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setWindowTitle('QListWidget')
        self.setWindowIcon(QIcon.fromTheme('python'))
        self.setGeometry(100, 100, 200, 60)

        self.list_widget = QListWidget(self)
        self.list_widget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.list_widget.addItems(['Python', 'PyQt6', 'PySide6'])
        
        self.list_widget.customContextMenuRequested.connect(self.on_context_menu)
        
        self.action_1 = QAction("Option 1", self, triggered=self.on_option_1)
        self.action_2 = QAction("Option 2", self, triggered=self.on_option_2)
        self.action_3 = QAction("Option 3", self, triggered=self.on_option_3)
        
        self.setCentralWidget(self.list_widget)
        self.show()
        
    def on_option_1(self):
        print("Option 1")

    def on_option_2(self):
        print("Option 2")

    def on_option_3(self):
        print("Option 3")
        
    def on_context_menu(self):
        menu = QMenu(self)
        menu.addAction(self.action_1)
        menu.addAction(self.action_2)
        menu.addAction(self.action_3)
        menu.exec(QCursor.pos())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())
    

You need to define a timer which calls a function (displays a context menu) for the application (init) and then start the timer when focus occurs for the QListWidget.

Why a timer for a context menu?

The moment you right-click in the QListWidget, the QListWidget has focus.

The example I found online and use in my app (touch screen) it doesn’t use a right-click, it uses the focus event to initiate the context menu within a designated period of time.

In a non touch environment you wouldn’t need a timer …