Getting selected rows in QListWidget

bobflob picture bobflob · Nov 25, 2015 · Viewed 8.4k times · Source

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>

Answer

justengel picture justengel · Nov 25, 2015

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.