34

I'm trying to make a conditional statement based on whether a checkbox is checked or not. I've tried something like the following, but it always returns as true.

self.folderactive = QtGui.QCheckBox(self.folders)
self.folderactive.setGeometry(QtCore.QRect(50, 390, 71, 21))
self.folderactive.setObjectName(_fromUtf8("folderactive"))
if self.folderactive.isChecked:
    folders.createDir('Desktop')
    print "pass"
elif not self.folderactive.isChecked:
    folders.deleteDir('Desktop')
    print "nopass"

Is there a way to get a bool value of whether a checkbox is checked or not?

Damon
  • 3,004
  • 7
  • 24
  • 28
Joshua Strot
  • 2,343
  • 4
  • 26
  • 33

2 Answers2

57

self.folderactive.isChecked isn't a boolean, it's a method - which, in a boolean context, will always evaluate to True. If you want the state of the checkbox, just invoke the method:

if self.folderactive.isChecked():
    ...
else:
    ...
mata
  • 67,110
  • 10
  • 163
  • 162
  • 2
    to avoid the if-then-else construct and keep track of the state myself, programatically, is there anything that emits a signal when a checkBox is checked (another when unchecked), like ``` self.checkBox.toggled.connect(self.calculate)``` ? – Echeban Dec 22 '19 at 22:34
  • @Echeban Did you find out if there is such a thing, I was looking for it – pippo1980 Apr 07 '22 at 16:48
  • here --> -https://stackoverflow.com/questions/59437747/checkbox-to-a-variables-pyqt5 – pippo1980 Apr 07 '22 at 17:11
4
x = self.folderactive.isChecked()

x will be True or False—a Boolean value.

(It's the brackets at the end that make the difference.)

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Terry
  • 41
  • 1