pythonqtpyqtpyqt5qwidgetaction

Hiding QWidgetAction just grey it out


I'm trying to build a menu with some QWidgetAction. Some of them can be hidden (using setVisible()), depending on the current state of the program. When I hide a QWidgetAction, it isn't really hidden but seems to only be disabled, and other actions are drawn over it.

Here's a little test script that shows the issue :

from PyQt5 import QtGui, QtWidgets
import sys

widgetActions = []

def buttonClicked():
    widgetActions[0].setVisible(not widgetActions[0].isVisible())

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QMainWindow()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('QWidgetAction bug')

    menuBar = QtWidgets.QMenuBar(w)
    menu = menuBar.addMenu('Test')

    for i in range(10):
        widget = QtWidgets.QLabel('XXXXXXXXXXX' if not i else '------------')
        widgetAction = QtWidgets.QWidgetAction(menuBar)
        widgetAction.setDefaultWidget(widget)
        menu.addAction(widgetAction)
        widgetActions.append(widgetAction)

    button = QtWidgets.QPushButton(QtGui.QIcon(), 'Hide/show first action', w)
    button.move(20, 50)
    button.resize(200, 40)
    button.clicked.connect(buttonClicked)
    w.show()
    sys.exit(app.exec())

See below the result and how the first QWidgetAction stays visible under another action. Am I doing something wrong or am I just hitting a Qt bug ? For information, I'm using Qt-5.9.4 on Linux.

Action visible First action hidden


Solution

  • If you want to hide the QWidgetAction you must hide the associated widget:

    def buttonClicked():
        widgetActions[0].setVisible(not widgetActions[0].isVisible())
        widgetActions[0].defaultWidget().setVisible(widgetActions[0].isVisible())