how to retrieve the selected row of a QTableView?

怎甘沉沦 提交于 2019-12-04 03:24:16

It depends what you mean by "the selected row". By default, a QTableView has its selection mode set to ExtendedSelection, and its selection behavior set to SelectItems. This means that several individual table cells in different rows and columns can be selected at the same time. So which one should count as "the" selected row?

The selection model of the table-view has a selectedRows method which will return a list of indexes for the rows where all the colums are selected (i.e. as it is when you click on the header section for a row):

    indexes = table.selectionModel().selectedRows()
    for index in sorted(indexes):
        print('Row %d is selected' % index.row())

However, if you want to get all the rows where at least one cell is selected, you can use the selectedIndexes method:

    rows = sorted(set(index.row() for index in
                      self.table.selectedIndexes()))
    for row in rows:
        print('Row %d is selected' % row)

One of the way's you can use to retrieve the selected rows is:

tableView = QtGui.QTableView()
tableModel = PaletteTableModel()   
tableView.setModel(tableModel)

x = tableView.selectedIndexes ()

"tableView.selectedIndexes ()" returns a list-of-QModelIndex's

In my case I use this action into a function that is called in doubleClicked event something like this: I add this line code into the init function

self.tableSusAmigos.doubleClicked.connect(self.doubleClicked_table)

After that I declared doubleClicked_table like this:

def doubleClicked_table(self):
    index = self.tableSusAmigos.selectedIndexes()[0]
    id_us = int(self.tableSusAmigos.model().data(index).toString())
    print ("index : " + str(id_us)) 

In this case I show an id (integer) that it's in the first column (that's the reason the number 0 in selectedIndexes()[0])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!