Reputation: 778
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
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
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:
Hope that helps!
Upvotes: 2