I am developing a plugin for the GIS software, QGIS. I created a QTableWidget
and wish to extract values from it:
Problem is, I use a lot of for
loops and if
else
statements which, up until the last few lines, seems to work fine. I can't seem to follow the logic now as the line print constraint_name
only prints off the last value "Example_2". I could take it out of its corresponding else
statement and then it will print all values correctly but I need to set it inside a condition:
qTable = self.dockwidget.tableWidget # QTableWidget
example_group = root.findGroup('Main group') # Group containing sub groups
all_items = []
gis_map = QgsMapLayerRegistry.instance().mapLayersByName( "Map" )[0] # Layer map in QGIS
idx = gis_map.fieldNameIndex("Rank") # Get "Rank" attribute field from gis_map
for row in range(qTable.rowCount()):
for col in [0]: # For first column "Constraint name"
constraint_item = qTable.item(row, col)
constraint_name = str(constraint_item.text())
for col in [1]: # For second column "Rank"
item = qTable.item(row, col)
item_string = str(item.text())
all_items.append(item_string)
for group in example_group.children(): # Search for specific group
if group.name() == "Sub group":
if len(set(all_items)) == 1: # If all items are the same
# If "Rank" field exists in layer map
if idx == -1:
print 'success'
else:
print 'fail'
else:
if idx == -1:
print constraint_name
else:
print 'fail'
Is there a way to tidy this up and still get the correct results?
for col in [0]:
?? Something seems fishy therefor
loops are useless.for col in [0]
andfor col in [1]
can be refactored to nothing, since they each execute exactly once with a known value.if
statements can be reversed, since you printfail
ifidx == -1
regardless of the value oflen(set(all_items))
QTableWidget
? Because I can print off the values from that by addingprint constraint_name
in the same loop.for col in [0]: # For first column "Constraint name"
The comment there hints that you should define a variable namedconstraint_column
or something and then use it in thefor
statement.