Home > Blockchain >  How to disable and re-enable QPushButton
How to disable and re-enable QPushButton

Time:09-23

I made MainWindow and Dialog with Qt-designer.The MainWindow and Dialog have one QPushButton. Clicking a button in the MainWindow disables the button and opens a Dialog Window. When you click the Dialog button, the Dialog window closes and the MainWindow's button is activated again.

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5 import uic

form_mainwindow = uic.loadUiType("dialog_mainWindow.ui")[0]
form_dialog = uic.loadUiType("Dialog__.ui")[0]

class dialog(QDialog, form_dialog) :
    def __init__(self):
        super(dialog, self).__init__()
        self.setupUi(self)
        self.closeBtn.clicked.connect(self.close)
        self.closeBtn.clicked.connect(self.closeFN)

    def closeFN(self):
        main = mainwindow()
        main.pushButton.setEnabled(True)

class mainwindow(QtWidgets.QMainWindow, form_mainwindow) :
    def __init__(self):
        super(mainwindow, self).__init__()
        self.setupUi(self)

        self.pushButton.clicked.connect(self.dia)

    def dia(self,checked):
        d = dialog()
        self.pushButton.setEnabled(False)
        d.show()
        d.exec_()

if __name__ == "__main__" :
    app = QtWidgets.QApplication(sys.argv)
    Window = mainwindow()
    Window.show()
    sys.exit(app.exec_())

This is my code. However, my code is that when the Dialog window is closed, the button in the MainWindow is not activated again. Why??

CodePudding user response:

You are calling mainwindow() in your dialogs closeFN method, which creates a new mainwindow widget. So the button that you are setting to be enabled is not the same one that you used to create the dialog in the first place. You are setting a button on a new window that isn't visible yet because you never call .show() or similar method that makes top level windows visible.

A solution to this is to have your mainwindow connect to the dialogs closebtn.clicked signal which could then trigger it's own method that set's the pushbutton to be enabled.

For example:

...

class dialog(QDialog) :
    def __init__(self):
        super(dialog, self).__init__()
        ...
        # self.closeFN is no longer necessary
        self.closeBtn.clicked.connect(self.close)

class mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mainwindow, self).__init__()
        ...
        self.pushButton.clicked.connect(self.dia)

    def dia(self):
        d = dialog()
        self.pushButton.setEnabled(False)
        # connect to closeBtn signal to enable the pushButton
        d.closeBtn.clicked.connect(lambda: self.pushButton.setEnabled(True))  
        d.exec_()
...
  • Related