Right click contextMenu on QPushButton

18,793

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()
Share:
18,793

Related videos on Youtube

ArtDijk
Author by

ArtDijk

Updated on December 19, 2020

Comments

  • ArtDijk
    ArtDijk about 2 years

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

    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 ?

  • ArtDijk
    ArtDijk almost 12 years
    Hi Serge, Thanks for your reply. It seems to soleve my issue. rgds Arthur.
  • serge_gubenko almost 12 years
    if it solves your issue, pls, mark your question as answered, regards
  • greendino
    greendino over 2 years
    TypeError: argument 1 has unexpected type 'NoneType' on self.popMenu.addAction(QtGui.QAction('test0', self))

Related