我正在为GIS软件QGIS开发一个插件。我创建了一个QTableWidget并希望从中提取值:

问题是,我使用了很多for循环和if else语句,直到最后几行为止,这些语句看起来都很好。我现在似乎无法遵循逻辑,因为行print constraint_name只输出最后一个值"Example_2“。我可以从它对应的else语句中取出它,然后它将正确地打印所有值,但是我需要在一个条件中设置它:
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' 有没有办法把这件事整理一下,然后得到正确的结果呢?
发布于 2016-05-26 13:57:20
我衷心感谢那些指导我找到一个更有效的解决方案的评论员,下面是工作代码(我相信它还可以进一步完善):
qTable = self.dockwidget.tableWidget
example_group = root.findGroup('Main group')
all_items = []
gis_map = QgsMapLayerRegistry.instance().mapLayersByName( "Map" )[0]
idx = gis_map.fieldNameIndex("Rank")
for row in range(qTable.rowCount()):
constraint_item = qTable.item(row, 0)
constraint_name = str(constraint_item.text())
item = qTable.item(row, 1)
item_string = str(item.text())
all_items.append(item_string)
for group in example_group.children():
if group.name() == "Sub group":
if idx == -1:
if len(set(all_items)) == 1:
print 'success'
else:
print 'fail'
else:
print constraint_name https://stackoverflow.com/questions/37462274
复制相似问题