pyqt create a qmenu on a button click

Solutions on MaxInterview for pyqt create a qmenu on a button click by the best coders in the world

showing results for - "pyqt create a qmenu on a button click"
Yann
12 May 2016
1import sys
2from PyQt4 import QtGui, QtCore
3class MainForm(QtGui.QMainWindow):
4    def __init__(self, parent=None):
5        super(MainForm, self).__init__(parent)
6
7        # create button
8        self.button = QtGui.QPushButton("test button",self)       
9        self.button.resize(100, 30)
10
11        # set button context menu policy
12        self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
13        self.connect(self.button, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu)
14        self.popMenu = QtGui.QMenu(self)
15
16    def on_context_menu(self, point):
17        self.popMenu.clear()
18
19        #some test list for test
20        testItems = ['itemA', 'itemB', 'itemC']
21        for item in testItems:
22        action = self.popMenu.addAction('Selected %s' % item)
23        action.triggered[()].connect(
24            lambda item=item: self.printItem(item))
25        self.popMenu.exec_(self.button.mapToGlobal(point))
26
27    @QtCore.pyqtSlot(str)
28    def printItem(self, item):
29        print item
30
31def main():
32    app = QtGui.QApplication(sys.argv)
33    form = MainForm()
34    form.show()
35    app.exec_()
36
37if __name__ == '__main__':
38    main()