I am currently using PyQt5 to develop a GUI for my application. I have not used PyQt for very long and I am currently still learning more about it. I have discovered a way to dynamically create a QCheckBox for every element in a specified list and add it to my QGridLayout. I am currently attempting to connect a function to each of the generated QCheckBoxes. My code is as follows:
import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout,
QPushButton, QApplication, QCheckBox, QButtonGroup, QAbstractButton)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def checkboxState(self,b):
if b.isChecked() == True:
print(b.text()+ " is selected")
else:
print(b.text()+ " is deselcted")
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
appList = ['Demo1','Demo2','Demo3']
for app in appList:
checkbox = QCheckBox(app)
checkbox.stateChanged.connect(lambda:self.checkboxState(checkbox))
grid.addWidget(checkbox)
self.move(300, 150)
self.setWindowTitle('Calculator')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
My code runs without throwing any errors, but I get an odd result. When I check any checkbox, other than 'Demo3', in the GUI window the console output reads the following:
Demo3 is now deselected
When I select Demo3 in the window the console output alternates between the following:
Demo3 is now selected and Demo3 is now deselected
So, I have the checkbox working correctly for only the last button that is added to the window. If you all can provide me with any pointers, I would be more than grateful.