Tirsi
Tirsi

Reputation: 53

Automatically selecting element from QListView

I have a QListView widget that contains a set of elements. I am trying to automatically select the last element, each time this QListView is updated (and to display it in the GUI).

What I want to do is something like this:

list_view_1  = QtWidgets.QListView()
element_list = QStandardItemModel(list_view_1)

element_list.appendRow(QStandardItem(element))
list_view_1.setModel(element_list)

list_view_1.setCurrentIndex(len(element_list))

The last command doesn't seem to work. I tried to look around for any previous posts but I couldn't find something that works for me.

Upvotes: 1

Views: 117

Answers (1)

Heike
Heike

Reputation: 24420

To get the index of the last element in the model you can use something like

index = element_list.index(element_list.rowCount()-1, 0)
list_view_1.setCurrentIndex(index)

But since you just created and added the item you could also do something like

item = QStandardItem(element)
element_list.appendRow(item)
list_view_1.setModel(element_list)

index = element_list.indexFromItem(item)
list_view_1.setCurrentIndex(index)

Upvotes: 1

Related Questions