[Python] Redraw a QPushButton after .setDown is called?

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the following example:

    import sys
    import time
    from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QVBoxLayout
    from PyQt5.QtCore import QTimer

    app = QApplication(sys.argv)
    window = QWidget()
    window.setWindowTitle("Minimal PyQt5 Example")

    button = QPushButton("Click Me")
    button.setCheckable(True)

    def unpress_button():
    button.setDown(False)
    print("{}: unpress_button: {}".format(time.time(), button.isDown()))

    def show_message_box():
    msg_box = QMessageBox()
    msg_box.setText("Button clicked")
    msg_box.setStandardButtons(QMessageBox.Ok)
    ok_button = msg_box.button(QMessageBox.Ok)
    ok_button.setText("OK")
    msg_box.exec_()
    unpress_button()
    QTimer.singleShot(1000, unpress_button)

    button.clicked.connect(show_message_box)

    layout = QVBoxLayout()
    layout.addWidget(button)
    window.setLayout(layout)

    window.show()
    sys.exit(app.exec_())


    At start of the application, we get the button in its unchecked/unpressed state:

    [​IMG]

    When the button is clicked, since it is .setCheckable, it is rendered in its checked/pressed state, as expected - and a "Button clicked" sub dialog appears:

    [​IMG]

    What I want now, is that after the OK button is pressed on the sub dialog and the sub dialog disappears, the original button should be automatically restored to its unpressed/unchecked state. I was hoping to do that via the unpress_button function, which runs button.setDown(False) - and in fact the printouts show that the "down" property is indeed set to False:

    1750425124.4820263: unpress_button: False
    1750425125.5181835: unpress_button: False


    ... however, after all this, the button remains drawn/rendered in its "pressed"/"checked" state:

    [​IMG]

    Note that I have even used QTimer.singleShot so I could escape the context of the show_message_box handler, but that does not help either.

    So, how can I force the button to be drawn in its "unpressed"/"unchecked" state, as it should be as per what its .isDown() method indicates?

    Continue reading...

Compartilhe esta Página