Vector Vector - 11 months ago 105
Python Question

PyQt: Can a QPushButton be assigned a QAction?

Using Python 3.2x and PyQT 4.8x:

I initialized an action and assigned to a menu item:

self.__actionOpen = QtGui.QAction(self.__mw)
QtCore.QObject.connect(self.__actionOpen, QtCore.SIGNAL("triggered()"), self.__accessFile)

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:


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 Source

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.