I'm using right mouse clicks to display a context-sensitive menu within a QTreeView-based GUI. The context menu works correctly on Windows and Ubuntu. On Mac OS X, the context menu displays correctly but when the user selects an option from the context menu the corresponding operation is only performed about once every 10 times the menu is invoked and a selection made.
The environment is Python V3.9.6 and PyQt V5.12.3 on all machines, installed using conda. The Ubuntu machine is 20.04, Windows 10 is a virtual machine (VBox) under the Ubuntu host and the Mac OS X machine is a MacInCloud server running Catalina.
I've included an MRE below that puts up a basic tree view. Right clicking on an entry will display the context menu and selecting a context menu entry should print a message in the console. This works correctly on Ubuntu and Windows but only intermittently on Mac OS X.
import sys
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5 import QtCore
class main_ui(QtWidgets.QWidget):
def __init__(self):
super(main_ui, self).__init__()
# set the window title and size
self.setWindowTitle("Context menu trigger")
self.resize(500, 300)
# set the model
self.model = QtGui.QStandardItemModel()
self.model.setHorizontalHeaderLabels(["Variable"])
# set the view and link it to the model
self.view = QtWidgets.QTreeView()
self.view.setModel(self.model)
self.view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.view.customContextMenuRequested.connect(self.context_menu)
self.view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectItems)
# define the context menu
self.context_menu = QtWidgets.QMenu()
self.context_menu.plot_time_series = QtWidgets.QAction(self)
self.context_menu.plot_time_series.setText("Plot time series")
self.context_menu.plot_time_series.triggered.connect(self.plot_time_series)
self.context_menu.addAction(self.context_menu.plot_time_series)
# create the model
self.create_model()
# set the layout
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.view)
def context_menu(self, position):
print("Displaying context menu")
self.context_menu.exec_(self.view.viewport().mapToGlobal(position))
def create_model(self):
keys = ["Variable1", "Variable2", "Variable3"]
for key in keys:
self.model.appendRow([QtGui.QStandardItem(key)])
def plot_time_series(self):
print("In plot_time_series")
if (__name__ == '__main__'):
app = QtWidgets.QApplication(["Test"])
ui = main_ui()
ui.show()
sys.exit(app.exec_())
I have tried reverting to earlier versions of Python 3 and PyQt but the problem persists and I've been unable to find a related question here or elsewhere.