1

I am working with a QTableView and trying to retrieve values from the selected row(s). At other times I will be working with mulitiple rows using:

self.tableView5.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

The code below works, but only when the first row is selected. However, it shows:

identity[row].append(str(self.table_model5.data(index)))
IndexError: list index out of range

when another row is clicked.

names = []
emails = []
identity = []
data = sorted(set(index.row() for index in self.tableView5.selectionModel().selectedRows()))
for row in data:
    identity.append([])
    for column in range(0,2):
        index = self.table_model5.index(row, column)
        identity[row].append(str(self.table_model5.data(index)))
for item in identity:
    names.append(item[0])
    emails.append(item[1])
for name, recipient in zip(names, emails):
    print(name, recipient)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
And3r50n 1
  • 337
  • 1
  • 5
  • 21
  • possible duplicate of https://stackoverflow.com/questions/22577327/how-to-retrieve-the-selected-row-of-a-qtableview – eyllanesc Mar 04 '18 at 17:30

2 Answers2

3

The problem here is caused by the convoluted method you are using to populate the lists of values. I would suggest the following simplification:

names = []
emails = []
identity = []
for index in sorted(self.tableView5.selectionModel().selectedRows()):
    row = index.row()
    name = self.table_model5.data(self.table_model5.index(row, 0))
    email = self.table_model5.data(self.table_model5.index(row, 1))
    identity.append((name, email))            
    names.append(name)
    emails.append(email)

Note that there is no need to use set, because selectedRows only returns one index per selected row.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
0

It's identity[row] that throws this exceptions. Imagine you selected from the table rows 2 and 3. Then in the first iteration of your for row in data: loop the value of row will be 2 while your identity list will be one element long at that time.

Debug and fix your logic.

Andrei Boyanov
  • 2,309
  • 15
  • 18