Search code examples
pythonpyqtpyqt4

python how can i display a checkbox as checked in


I have a GUI with many check boxes (in python). users should click many check boxes to run the application. I want to create a button that automatically select and "clicks" some predefined check boxes.

I know how to create the button, and also have the application "know" the check box is checked.

however, when looking at the GUI, the check boxes are left empty, so the user doesn't know which check box is checked. see below the check box definition:

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        QtCore.QObject.connect(self.legacyrunsens, 
        QtCore.SIGNAL(_fromUtf8("stateChanged(int)")), legacychecksens)

so, I call legacychecksens(2) , but on the GUI the checkbox is not marked.


Solution

  • The solution consists of connecting the clicked signal to the setChecked(True) method of the QCheckBox through functools.partial(), in the following part I show the example with PySide4

    from PyQt4 import QtCore, QtGui
    from functools import partial
    
    
    class Widget(QtGui.QWidget):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            lay = QtGui.QVBoxLayout(self)
    
            button = QtGui.QPushButton("Default")
            lay.addWidget(button)
    
            options = ["A", "B", "C", "D", "E", "F"]
            default = ["A", "B", "C"] 
    
            for option in options:
                checkbox = QtGui.QCheckBox(option)
                lay.addWidget(checkbox)
                if option in default:
                    button.clicked.connect(partial(checkbox.setChecked, True))
    
    
    if __name__ == '__main__':
        import sys
    
        app = QtGui.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())