Search code examples
pythonqtpysidepyside6qt6

Disabling custom button inside QDialogButtonBox


I have a QDialogButtonBox that contains the two custom buttons Start and Cancel. According to this answer, the best way to add these buttons is as follows:

button_box = QDialogButtonBox()
button_box.addButton("Launch", QDialogButtonBox.ButtonRole.AcceptRole)
button_box.addButton("Cancel", QDialogButtonBox.ButtonRole.RejectRole)

One of the two buttons must now be deactivated. I tried to adopt the code from here:

button_box.button(QDialogButtonBox.ButtonRole.AcceptRole).setDisabled(True)

but this seems only to work with the default qt buttons like Ok etc. I came up with the following working solution, but I wanted to ask if there is a more direct way I missed.

for btn in button_box.buttons():
    if btn.text() == "Launch":
        btn.setDisabled(True)

Solution

  • You should be able to retrieve the button from the addButton function, and save it to a variable according to the docs.

    #create button box w/ custom buttons
    button_box = QDialogButtonBox()
    launch_button = button_box.addButton("Launch", QDialogButtonBox.ButtonRole.AcceptRole)
    cancel_button = button_box.addButton("Cancel", QDialogButtonBox.ButtonRole.RejectRole)
    
    # disable the launch button
    launch_button.setDisabled(True)