PyQt: Can a QPushButton be assigned a QAction?

Vector picture Vector · May 23, 2013 · Viewed 7.3k times · Source

Using Python 3.2x and PyQT 4.8x:

I initialized an action and assigned to a menu item:

self.__actionOpen = QtGui.QAction(self.__mw)
self.__actionOpen.setObjectName("actionOpen")
self.__actionOpen.setText("OpenFile")
QtCore.QObject.connect(self.__actionOpen, QtCore.SIGNAL("triggered()"), self.__accessFile)
self.__menuFile.addAction(self.__actionOpen)

Works fine - menu item is there with caption "OpenFile" and the action signal/slot is invoked.

I tried it with a QPushButton - same QAction object:

self.__buttonFile.addAction(self.__actionOpen)

Nothing: No caption on the button, nothing happens when it's clicked.

Do actions not work with QButton (the addAction call did not complain...)? Or is there something wrong with my code? Perhaps the "triggered()" signal is not appropriate for an action that interacts with QPushButton?

Answer

alexisdm picture alexisdm · May 23, 2013

You can't assign a QAction to a QPushButton the way you want. QPushButton doesn't redefine addAction so the behavior comes from QWidget.addAction which adds the action to the context menu of the button.

You can however assign the action to a QToolButton with setDefaultAction which will change the button caption and trigger the action when clicked.

Or you could do it manually anyway by subclassing QPushButton and adding a setDefaultAction method that would change everything in the button according to the action (caption, tooltip...) and connects the relevant button's signals to the action's slots.