【发布时间】:2021-10-28 09:29:47
【问题描述】:
我正在使用鼠标右键在基于 QTreeView 的 GUI 中显示上下文相关菜单。上下文菜单在 Windows 和 Ubuntu 上正常工作。在 Mac OS X 上,上下文菜单可以正确显示,但是当用户从上下文菜单中选择一个选项时,相应的操作只会在大约每 10 次菜单被调用并做出选择时执行一次。
环境是 Python V3.9.6 和 PyQt V5.12.3 在所有机器上,使用 conda 安装。 Ubuntu机器是20.04,Windows 10是Ubuntu主机下的虚拟机(VBox),Mac OS X机器是运行Catalina的MacInCloud服务器。
我在下面添加了一个 MRE,它提供了一个基本的树形视图。右键单击条目将显示上下文菜单,选择上下文菜单条目应在控制台中打印一条消息。这在 Ubuntu 和 Windows 上可以正常工作,但在 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_())
我已尝试恢复到 Python 3 和 PyQt 的早期版本,但问题仍然存在,我无法在此处或其他地方找到相关问题。
【问题讨论】:
-
您是否尝试过使用最新版本的 PyQt5 并且不使用 conda?
-
@eyllanesc - 好建议,我现在在 OSX 机器上试试。
-
@eyllanesc - 如果不使用 conda,我无法安装 Python3。我的现收现付服务器上没有 root 访问权限。通过 conda (3.9.5) 安装 Python3 和通过 pip (5.15.4) 安装 PyQt5 产生与上述相同的结果。只有部分检查,因为 conda 仍然用于安装 Python ...
标签: python macos pyqt contextmenu intermittent