Issue with my Check Box in PyQt and Python

2019-08-07 12:10发布

问题:

I have a checkbox named "selectAllCheckBox". When this in checked state, all the checkboxes(created dynamically) inside the listview should change to checked state and when "selectAllCheckBox" checkbox is in Unchecked state, all the dynamically created checkboxes should change to unchecked state.

self.dlg.selectAllCheckBox.stateChanged.connect(self.selectAll)
def selectAll(self):
    """Select All layers loaded inside the listView"""

    model = self.dlg.DatacheckerListView1.model()
    for index in range(model.rowCount()):
        item = model.item(index)
        if item.isCheckable() and item.checkState() == QtCore.Qt.Unchecked:
            item.setCheckState(QtCore.Qt.Checked)

What the above code does it makes the dynamic checkboxes inside the listview to Checked state even when "SelectAllCheckBox" is in Unchecked state. Please help me how to solve this using python. Is there anything could be done in signal like when the checkbox is "checked" or "unchecked" to connect to a slot instead of stateChanged?

回答1:

The stateChanged signal sends the checked state, so the slot could be re-written as:

def selectAll(self, state=QtCore.Qt.Checked):
    """Select All layers loaded inside the listView"""

    model = self.dlg.selectAllCheckBox.model()
    for index in range(model.rowCount()):
        item = model.item(index)
        if item.isCheckable():
            item.setCheckState(state)

(NB: if all the rows in the list-view have checkboxes, the isCheckable line could be omitted)