11

I have a QTableView and I need to the get value (string) from the first cell of the selected row (any cell on the row could be selected). But I need this value only if exactly one row was selected.

I thought - I need to get index of the selected row and then get the value of the first сell on that line, but I couldn't find a way to do it.

fduff
  • 3,671
  • 2
  • 30
  • 39
Stals
  • 1,543
  • 4
  • 27
  • 52

2 Answers2

15
myTableView->selectionModel()->currentIndex().row()

Will give you the index of the currently selected row. From there you should have enough information to look up the row/column pair in your model.

Also, QItemSelectionModel::selectedRows() will let you know how many rows are selected.

Chris
  • 17,119
  • 5
  • 57
  • 60
  • 2
    I am able to get the row index, but how to get the value at the first column for example ? – McLan Dec 07 '15 at 12:42
  • 4
    An old question by @Suda.nese but for anyone else who needs to get the value: `QModelIndex index=myTableView->selectionModel()->currentIndex();` to get the index, then `QVariant value=index.sibling(index.row(),index.column()).data();` will get the value of the clicked cell. – JBES Apr 29 '18 at 17:19
  • Extremely helpful, can confirm that this works on PyQt5 as well – dtasev Oct 18 '18 at 13:59
10

Python Code will look like :

    self.tableView.clicked.connect(self.on_Click)

When User Click on Table Cell the on_Click() method is invoked

    def on_Click(self):
        # #selected cell value.
        index=(self.tableView.selectionModel().currentIndex())
        # print(index)
        value=index.sibling(index.row(),index.column()).data()
        print(value)

Explanation.

"value" contains the cell value of the selected cell.

       index.row() # gives current selected row.
       index.column() # gives current selected column.
       index.sibling(index.row(),index.column()).data() # will return cell data
Akshar Sarvaiya
  • 230
  • 2
  • 8
  • 2
    Your answer pointed me in the right direction and helped me solve an issue i was having for months getting tool tips to work from my qtableview qsqltablemodel index. the only mod i had to do was to use cause i had tried this `index.sibling(index.row(),index.column()).data()` with the column set to 5 but it did not work `index.sibling(index.row(),index.column(5)).data()` So i ended up using this which worked to get the value from the same index row but column5 of the selection. `index.siblingAtColumn(5).data()` – Mike R Oct 11 '20 at 02:55
  • Works like a charm..! – T.SURESH ARUNACHALAM Jul 02 '21 at 06:32
  • index.siblingAtColumn(5).data() worked for me on PyQt6 also! – zeroalpha Mar 31 '22 at 05:08