PySide2 index of setData
-
Hi,
I used QAbstractTableModel to make a table in python and when i try to trigger setData function, it requires PySide2.QtCore.QModelIndex. So how can i set PySide2.QtCore.QModelIndex from qml file.
python:class TableItems(QAbstractTableModel): def __init__(self): QAbstractTableModel.__init__(self) self.rows = 3 self.cols = 4 self.item = np.arange(12).reshape(self.rows, self.cols) def rowCount(self, parent): return self.rows def columnCount(self, parent): return self.cols def data(self, index, role): if((index.row() < 3) and index.column() < 4): return str(self.item[index.row(), index.column()])
qml:
TableView{ anchors.fill: parent id: viewer columnSpacing: 12 rowSpacing: 5 model: modelItem delegate: TextField{ id: readWrite text: display onAccepted: { modelItem.setData(readWrite.text) } }
-
@Abdulrahman
I'm sorry I don't know anything about QML so cannot answer your question.But may I suggest you might want to improve you
def data()
a bit? You should test therole
parameter before returning your data value. Qt infrastructure calls it with a variety of values ofrole
behind the scenes, you are returning your result unconditionally to what might be a request for a colour or an alignment for data at that index, in which case your return result may be misinterpreted. Unless this never happens from QML. I would change yours to, say:def data(self, index, role): if not index.isValid(): return None if role == Qt.DisplayRole or role == Qt.EditRole: return self.item[index.row(), index.column()] return None
Also, you are inheriting from just
QAbstractTableModel
. That means yourmodelItem.setData(readWrite.text)
will do nothing. You must implementsetData()
(in a similar fashion todata()
) before your model can be updated:def setData(self, index, value, role): if not index.isValid(): return False if role == Qt.EditRole: self.item[index.row(), index.column()] = value return True return False
-
@Abdulrahman
Not my area, perhaps this question should be posted to the QML sub-forum, if you don't get an answer here in a while? (except to say: if you have the row, column & model,model->index(row, column)
delivers theQModelIndex
, if that helps from QML.)