问题
I have a Qlistwidget
in which I can select multiple items. I can get a list with all the selected items in the listwidget but can not find a way to get a list of the corresponding rows. To get a list of the selected items in the listwidget I used the following code:
print [str(x.text()) for x in self.listWidget.selectedItems()]
To retrieve the rows I am looking for something like:
a = self.listWidget.selectedIndexes()
print a
But this does not work. I have also tried some code which resulted in outputs like this, which is not very useful:
<PyQt4.QtGui.QListWidgetItem object at 0x0000000013048B88>
<PyQt4.QtCore.QModelIndex object at 0x0000000014FBA7B8>
回答1:
The weird output is because you are getting objects of type QModelIndex
or QListWidgetItem
. The QModelIndex
object has a method to get its row, so you can use:
[x.row() for x in self.listWidget.selectedIndexes()]
To get a list of all selected indices.
回答2:
selectedIndexes and QModelIndex should be all you need.
liwidg = QtGui.QListWidget()
liwidg.show()
liwidg.setSelectionMode( QtGui.QAbstractItemView.SelectionMode.ExtendedSelection)
liwidg.addItems(["a", "b", "c", "d"])
liwidg.selectedIndexes()
When selected 'a', 'b', and 'c' liwidg.selectedIndexes() Gives:
[<PySide.QtCore.QModelIndex(0,0,0xb266478,QListModel(0xb0e6400) ) at 0x0C86EB20>,
<PySide.QtCore.QModelIndex(1,0,0xb266518,QListModel(0xb0e6400) ) at 0x0C861D78>,
<PySide.QtCore.QModelIndex(2,0,0xb2843c8,QListModel(0xb0e6400) ) at 0x0C869AF8>]
You can use the QModelIndex to get whatever information you need.
sel0 = liwidg.selectedIndexes()[0]
# <PySide.QtCore.QModelIndex(0,0,0xb266478,QListModel(0xb0e6400) ) at 0x0C85B530>
print(sel0.data())
print(sel0.row())
print(sel0.column())
Prints:
'a'
0
0
This works for me.
来源:https://stackoverflow.com/questions/33919150/getting-selected-rows-in-qlistwidget