右键单击QPushButton上的contextMenu

右键单击QPushButton上的contextMenu

本文介绍了右键单击QPushButton上的contextMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我已经在Qt Designer中创建了一个GUI,并将其转换为python(2.6)代码。

For my app I have created a GUI in Qt Designer and converted it into python(2.6) code.

在某些 QPushButton上(由设计者创建)我想添加一个右键单击上下文菜单。菜单选项取决于应用程序的状态。

On some of the QPushButton (created with the designer) I want to add a right click context menu. The menu options depend on the application status.

如何实现此类上下文菜单?

How to implement such a context menu ?

推荐答案

检查以下示例是否适合您。关键是要,以便小部件能够CustomContextMenu并连接到小部件的信号:

Check if an example below would work for you. The key thing is to set context menu policy for your widget to CustomContextMenu and connect to the widget's customContextMenuRequested signal:

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()

这篇关于右键单击QPushButton上的contextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:45