Getting selected rows in QListWidget
Asked Answered
E

2

6

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>
Eskill answered 25/11, 2015 at 14:32 Comment(2)
By "indices" do you mean row ? Index and row numbers are not the same thing in Qt. If you mean row, I suggest editing your question (including title).Keratosis
I guess i needed row yeah, i will change itEskill
C
5

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.

Caniff answered 25/11, 2015 at 15:4 Comment(0)
S
7

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.

Stint answered 25/11, 2015 at 14:49 Comment(1)
Thank you, this is what i neededEskill
C
5

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.

Caniff answered 25/11, 2015 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.