Check the state of QPushButton in PyQt4?

13.7k views Asked by At

I want to write a if with a condition as the state of QPushButton. I would like to execute if if the button is enabled. So, how can i check the state of the Button.

Code:

self.pushButton = QtGui.QPushButton()
self.pushbutton.setEnabled(False)

self.pushbutton.setEnabled(False) ##some where in the another class I have enabled it this line will not be executed all the time,so I want the check state.

if self.pushbutton.checkstate() == Enabled:  ##??? How to write this condition?
    some code I want to execute
1

There are 1 answers

0
Oliver On BEST ANSWER

Use QPushButton.isEnabled. The following code toggles a button between enabled and disabled and uses an "if" test to do something depending on the state. It is for PyQt5 but you should only have to adjust the imports to make it work with PyQt4 (if you are using Python 2.x, you will also have to adjust the print statements):

from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QPushButton

def check_button():
    if push.isEnabled():
        print('enabled')
        push.setEnabled(False)
    else:
        print('not enabled')
        push.setEnabled(True)

    QTimer.singleShot(1000, check_button)

app = QApplication([])
push = QPushButton()
push.show()
QTimer.singleShot(0, check_button)
app.exec()