I am trying to check multiple checkboxes with a for loop in the run(self) function because it needs to be somewhat self suficient and be able to analyse hundreds of checkboxes but it only runs once and modifies only the last value in my list no matter which is pressed
def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.first_start = False
# Fetch the currently loaded layers
#layers = QgsProject.instance().layerTreeRoot().children()
# Clear the contents of the comboBox from previous runs
#self.dlg2.comboBox.clear()
# Populate the comboBox with names of all the loaded layers
#self.dlg2.comboBox.addItems([layer.name() for layer in layers])
# show the dialog
self.dlg.show()
# Run the dialog event loop
self.dlg.resetButton.clicked.connect(self.reset)
self.dlg.coucheButton.clicked.connect(self.choix_couches)
self.dlg.controleButton.clicked.connect(self.choix_controles)
self.dlg3.cancel.clicked.connect(self.cancel)
self.dlg3.buttonBox.clicked.connect(self.reset_check_states)
self.dlg3.uncheck_all.clicked.connect(self.uncheck_all)
self.dlg3.check_all.clicked.connect(self.check_all)
for i in range(len(self.control_list)):
self.control_list[i][0].clicked.connect(lambda: self.update_check_status(self.control_list[i]))
# See if OK was pressed
result = self.dlg.exec_()
if result:
if (self.dlg3.rebroussement.isChecked()):
print(rebroussement(self))
The other functions that loop work fine and work every time they are called, but just the one that needs to analyse events only runs once because run is only called once.
Examples of functions that get called in run and work fine:
def uncheck_all(self):
for items in self.control_list:
if (items[0].isChecked()):
items[0].setChecked(False)
items[1] += 1
def check_all(self):
for items in self.control_list:
if (items[0].isChecked() == False):
items[0].setChecked(True)
items[1] += 1
I tried resetting "i" but it just does the same for the first value instead of the last.
Is there any other way to check if you clicked a potentially infinite number of checkboxes?
1 Answer 1
There are several ways to handle this, but I would recommend using a QSignalMapper
object in this circumstance.
self.click_signals = QSignalMapper()
self.click_signals.mappedInt.connect(self.update_check_status)
for i, ctl in enumerate(self.control_list):
self.click_signals.setMapping(ctl[0], i)
ctl[0].clicked.connect(self.click_signals.map)
len(self.control_list)
isi
will only ever have the last value assigned to it when the lambda is called. But it’s hard to suggest an alternative without knowing howcontrol_list
is populated or whatupdate_check_status
is doing.