QPushButton上的右键菜单

14

我为我的应用程序在Qt Designer中创建了GUI并将其转换为Python(2.6)代码。

在一些使用设计工具创建的 QPushButton 上,我想添加右键上下文菜单。菜单选项取决于应用程序状态。

如何实现这样的上下文菜单?

1个回答

32

请检查下面的示例是否适用于您。关键是为您的小部件设置上下文菜单策略并连接到小部件的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()

嗨Serge,谢谢你的回复。看起来解决了我的问题。敬礼,Arthur。 - ArtDijk
1
如果这解决了你的问题,请将你的问题标记为已解答。谢谢! - serge_gubenko
TypeError: 参数1的类型意外为'NoneType',位于self.popMenu.addAction(QtGui.QAction('test0', self))。 - greendino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接