Matteo NNZ
Matteo NNZ

Reputation: 12665

Python & PyQt4: setMenu method not working on a pushButton object

I'm pretty new to PyQt and I'm working on a PyQt4 GUI which has a push button defined as follows:

self.buttonFormule11=QtGui.QPushButton(self.centralwidget)
self.buttonFormule11.setGeometry(QtCore.QRect(268, 696, 19, 23))
self.buttonFormule11.setObjectName(_fromUtf8("buttonFormule11"))
self.buttonFormule11.setFlat(True) 

I would like to set a menu on it, so I've tried to follow the same logic of the other buttons within the same interface (that I didn't program):

self.listeWhenDefault = ["Option1", "Option2", "Option3"] 
self.MenuWhenIndicateur = QtGui.QMenu(self.centralwidget)
for option in self.listeWhenDefault:
    checkBox = QtGui.QRadioButton(option,self.MenuWhenIndicateur)
    checkableAction = QtGui.QWidgetAction(self.MenuWhenIndicateur)
    checkableAction.setDefaultWidget(checkBox)
    self.MenuWhenIndicateur.addAction(checkableAction)
    QtCore.QObject.connect(checkBox, QtCore.SIGNAL("toggled(bool)"), self.majWhenFormule) #here it should just modify the text shown into a line edit close to the push button, not relevant

self.buttonFormule11.setMenu(self.MenuWhenIndicateur) 

However, this procedure doesn't work cause when I click on the pushButton no menu is shown. Can anyone tell me if I'm forgetting something/being wrong anywhere?

Upvotes: 1

Views: 630

Answers (1)

ekhumoro
ekhumoro

Reputation: 120628

There doesn't seem to be anything wrong with the code you posted (I tested it, and it works for me). So the problems must lie elsewhere in your code.

However, I think the example code uses a somewhat odd approach, and so I have re-written it to use QActionGroup instead.

Here is a simple demo:

from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        menu = QtGui.QMenu(self.button)
        group = QtGui.QActionGroup(self.button)
        group.setExclusive(True)
        for index in range(1, 4):
            action = group.addAction('Option%d' % index)
            action.setCheckable(True)
            if index == 1:
                action.setChecked(True)
            menu.addAction(action)
        self.button.setMenu(menu)
        group.triggered.connect(self.handleOptionTriggered)

    def handleOptionTriggered(self, action):
        print(action.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 200, 100)
    window.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions