QListWidget 选中项按行排序
我有一个 QListWidget,开启了扩展选择功能 self.sensors.setSelectionMode(QAbstractItemView.ExtendedSelection)
。要获取所有被选中项的文本,可以使用以下方法:
for item in self.sensors.selectedItems():
target.write(" "+item.text()+",")
不过,输出的结果是按照选择的顺序排列的。有没有什么简单的方法可以按照行号来排序这些项呢?我可以通过 QListWidget.row(self.sensors, item)
来获取某个项的行号。
1 个回答
3
# create a dict containing index and corresponding item
tempDict = {}
for item in self.sensors.selectedItems():
tempDict[self.sensors.row(item)] = item
# sort the index and store as a list (`sorted()` does this for you)
tempIndexes = sorted(tempDict)
# define a list to contain the resultant items i.e sorted items
resultItems = []
for index in tempIndexes:
resultItems.append(tempDict[index])
for it in resultItems:
print(it.text())
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。