对于我的应用程序,我在Qt Designer中创建了一个GUI并将其转换为python(2.6)代码。
在QPushButton
(使用设计器创建)的某些内容中,我想添加一个右键单击上下文菜单。菜单选项取决于应用程序状态。
如何实现这样的上下文菜单?
答案 0 :(得分:17)
检查以下示例是否适合您。关键是将set context menu policy用于您的小部件到CustomContextMenu并连接到小部件的customContextMenuRequested信号:
import sys
from PyQt4 import QtGui, QtCore
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
# create button
self.button = QtGui.QPushButton("test button", self)
self.button.resize(100, 30)
# set button context menu policy
self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.button.customContextMenuRequested.connect(self.on_context_menu)
# create context menu
self.popMenu = QtGui.QMenu(self)
self.popMenu.addAction(QtGui.QAction('test0', self))
self.popMenu.addAction(QtGui.QAction('test1', self))
self.popMenu.addSeparator()
self.popMenu.addAction(QtGui.QAction('test2', self))
def on_context_menu(self, point):
# show context menu
self.popMenu.exec_(self.button.mapToGlobal(point))
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()