Sable
Sable

Reputation: 11

PyQt5 - Index a QListView that uses a QStringListModel list

Objective is to detect the item index whenever the user clicks an item on the list.

Example:

A
B
C
D
E

If the user clicks on C, then I would like to retrieve that index number from the list().

Tried to directly print out the item variable but I get this output on the command prompt:

[<PyQt5.QtCore.QModelIndex object at 0x0416CA70>]

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5       import QtWidgets, QtGui, QtCore
from PyQt5.QtGui import QBrush, QColor 

class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        lay = QtWidgets.QVBoxLayout(self)

        self.listView = QtWidgets.QListView()
        self.label    = QtWidgets.QLabel("Please Select item in the QListView")
        lay.addWidget(self.listView)
        lay.addWidget(self.label)

        model = QStringListModel()
        textList = list()
        textList = ["Itemname1", "Itemname2", "Itemname3", "Itemname4", "Itemname5", "Itemname6", "Itemname7", "Itemname8"]
        model.setStringList(textList)
        self.listView.setModel(model)        

        self.listView.clicked[QtCore.QModelIndex].connect(self.on_clicked)

    def on_clicked(self, index):
        item = self.listView.selectedIndexes()
        print(item)

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Output is [<PyQt5.QtCore.QModelIndex object at 0x0416CA70>] but I want the integer number.

Upvotes: 1

Views: 775

Answers (1)

egy
egy

Reputation: 143

From the documentation:

This convenience function returns a list of all selected and non-hidden item indexes in the view. The list contains no duplicates, and is not sorted.

A list of QModelIndex is returned. The following would get the first index:

print(item[0].row())

Also, for a single selection, you could use QListView.currentSelection() instead

Upvotes: 2

Related Questions