kyrpav
kyrpav

Reputation: 778

Get data from QTableView

I am trying to read data from a QTableView in PyQT. I have read several posts but I can not succeed.

I am using this function and inside it, I have commented different ways that all failed:

    def test(self):

    mymodel=self.resultTableView.model()  
    rows=mymodel.rowCount(self)
    columns=mymodel.columnCount(self)
    print rows
    print columns

#1st way
#         index = self.resultTableView.indexAt(QPoint(1,1))
#         x=self.resultTableView.model().data(index,QAbstractItemModel)

#2nd way
#         myindex=self.resultTableView.model().index(1, 1, QModelIndex())
#         x=self.resultTableView.model().data(myindex,self)

#3rd way
    x=self.resultTableView.model().data(self.resultTableView.model().index(0,2)).toString()
    index = self.resultTableView.currentIndex() ;
    x = index.sibling(index.row(),0)
    print type(x)
    print (x)

The first and the second have printed type= None and None for the items and 3rd printed type

class 'PyQt4.QtCore.QModelIndex'

PyQt4.QtCore.QModelIndex object at 0x000000001060E4C0

if I try to use .toString() function at the initialisation of x, I get a crash and if I try str(), I get:

type 'str'

PyQt4.QtCore.QModelIndex object at 0x000000001060E4C0

Is there any standard way? Also I get crashes when I try to use

model=self.resultTableView.model()

Upvotes: 0

Views: 3467

Answers (2)

QuentinJS
QuentinJS

Reputation: 322

There is a simple method. You need to make your own data method. (python doesn't make overloading easy, so I will skip that)

Make data2 the workhorse method, and then have the data() method call data2() in my case I am using a Panda dataframe.

    def data(self, index, role):
        return self.data2(index.column(), index.row(), role)

    def data2(self, column, row, role):
        value = self._data.iloc[row, column]

and then just call it like so

value = self.tbl.model().data2(0, current.row(), Qt.ItemDataRole.DisplayRole)

Upvotes: 0

Joseph Yu
Joseph Yu

Reputation: 21

I'm using PyQt5.5.1 with Python 3.4, and I've been confused by the similar questions for some time, because most of the answers I got from stackoverflow or somewhere actually either did not solve the issue or are based on the older version of PyQt.

Here're what I did:

  1. connect either activated, pressed or clicked signal to the slot where the data in the selected row is to be handled: example: self.ui.tableView.pressed.connect(self.__rowselect) The signal will pass the instance of QModelIndex to the slot function.
  2. proceed the selected data (QModelIndex) in the slot. example: def __rowselect(self, index): print(index.row(),index.sibling(index.row(),1).data()) You can use index.sibling(index.row(),index.column()).data() or index.data() to get the data of the selected CELL.

Hope that helps!

Upvotes: 2

Related Questions