Shaurya Garg
Shaurya Garg

Reputation: 105

PyQt5: Check the existance of dynamically created Checkboxes and Refer them

Basic Layout of the Code

Here, every time the user clicks on the PushButton 'Press me', a new CheckBox will be generated.

from PyQt5 import QtWidgets, QtGui, QtCore

count = 1

class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.vlayout = QtWidgets.QVBoxLayout()
        self.pushButton1 = QtWidgets.QPushButton("Press me", self)
        self.pushButton1.clicked.connect(self.addCheckbox(count))
        self.pushButton2 = QtWidgets.QPushButton("OK", self)
        self.vlayout.addWidget(self.pushButton1)
        self.vlayout.addWidget(self.pushButton2)

        self.setLayout(self.vlayout)

    def addCheckbox(self,count):
        global count
        self.vlayout.addWidget(str(count),QtWidgets.QCheckBox())
        count = count +1 

application = QtWidgets.QApplication(sys.argv)
window = Window()
window.setWindowTitle('Hello')
window.resize(250, 180)
window.show()
sys.exit(application.exec_())  

What I wish to do?

Now you will have unique check boxes, each with a different number, I want to add further functionality.

Every time the user chooses specific checkboxes, I want to know which checkbox did the user click after he clicks the PushButton OK. Eg: I click on checkbox 1 -> OK -> print 1 on the screen

How can I do this?

PS: We need to consider the possibility that the user never clicks Press me, so no ckeckboxes will be generated and straightaway clicks on OK

Upvotes: 2

Views: 968

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

Just use a list to store the QCheckBox, and verify by iterating.

from PyQt5 import QtWidgets, QtGui, QtCore


class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.vlayout = QtWidgets.QVBoxLayout(self)
        self.pushButton1 = QtWidgets.QPushButton("Press me")
        self.pushButton1.clicked.connect(self.addCheckbox)
        self.pushButton2 = QtWidgets.QPushButton("OK")
        self.pushButton2.clicked.connect(self.onClicked)

        self.vlayout.addWidget(self.pushButton1)
        self.vlayout.addWidget(self.pushButton2)

        self.checkboxes = []

    def addCheckbox(self):
        checkbox = QtWidgets.QCheckBox()
        self.checkboxes.append(checkbox)
        self.vlayout.addWidget(checkbox)

    def onClicked(self):
        for i, checkbox in enumerate(self.checkboxes):
            if checkbox.isChecked():
                print("print {} on the screen".format(i))

if __name__ == '__main__':
    import sys

    application = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setWindowTitle('Hello')
    window.resize(250, 180)
    window.show()
    sys.exit(application.exec_())  

Upvotes: 4

Related Questions