Python 3.x 插槽右键单击菜单操作不起作用
我已经编写了下面的代码,我最终成功地向其中添加了menu,但connecitn menu到函数中似乎不起作用:Python 3.x 插槽右键单击菜单操作不起作用,python-3.x,pyqt5,Python 3.x,Pyqt5,我已经编写了下面的代码,我最终成功地向其中添加了menu,但connecitn menu到函数中似乎不起作用: import os from PyQt5 import uic from PyQt5 import QtWidgets from PyQt5 import QtCore FILE_LOCATION = os.path.dirname(os.path.realpath(__file__)) class MainDialogWindow(QtWidgets.QDialog):
import os
from PyQt5 import uic
from PyQt5 import QtWidgets
from PyQt5 import QtCore
FILE_LOCATION = os.path.dirname(os.path.realpath(__file__))
class MainDialogWindow(QtWidgets.QDialog):
def __init__(self):
super(MainDialogWindow,self).__init__()
ui_file = os.path.join(FILE_LOCATION, "example.ui")
self._ui = uic.loadUi(ui_file, self)
self.registerCallbacks()
self.initUI()
def initUI(self):
"""Initialize the UI.
"""
self.textBrowser.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
def registerCallbacks(self):
self.textBrowser.customContextMenuRequested.connect(self.context_menu)
# self.connect(self.textBrowser, QtCore.Signal('customContextMenuRequested(const QPoint &)'), self.context_menu)
def context_menu(self, pos):
menu = QtWidgets.QMenu(self)
action = menu.addAction("clear")
menu.exec_(self.mapToGlobal(pos))
action.trigered.connect(self.clear)
def clear(self):
"""Slot to claer text.
"""
print("clear")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainDialogWindow()
window.show()
window.setGeometry(500, 300, 300, 300)
sys.exit(app.exec_())
请帮助p,,我想从右键单击菜单调用clear函数我似乎不理解该菜单的工作原理。exec_uu()方法,该方法会阻止连续任务的执行,直到用户从QMenu中选择QAction。例如,在您的情况下,直到您按下“clear”并发出触发信号(注意:您有一个输入错误),但此时没有连接,因此不会调用clear方法。解决方案是在调用QMenu exec_3;()之前建立连接:
def上下文菜单(self,pos):
menu=qtwidts.QMenu(self)
动作=菜单。添加动作(“清除”)
动作。触发。连接(自清除)
menu.exec_(self.mapToGlobal(pos))
我似乎不明白menu.exec_()方法是如何工作的,该方法会阻止连续任务的执行,直到用户从QMenu中选择一个QAction。例如,在您的情况下,直到您按下“clear”并发出触发信号(注意:您有一个输入错误),但此时没有连接,因此不会调用clear方法。解决方案是在调用QMenu exec_3;()之前建立连接:
def上下文菜单(self,pos):
menu=qtwidts.QMenu(self)
动作=菜单。添加动作(“清除”)
动作。触发。连接(自清除)
menu.exec(self.mapToGlobal(pos))
def context_menu(self, pos):
menu = QtWidgets.QMenu(self)
action = menu.addAction("clear")
action.triggered.connect(self.clear)
menu.exec_(self.mapToGlobal(pos))