Qt World Summit: Submit your Presentation

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.

    class TableItems(QAbstractTableModel):
         def __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()])


            anchors.fill: parent
            id: viewer
            columnSpacing: 12
            rowSpacing: 5
            model: modelItem
            delegate: TextField{
                 id: readWrite
                text: display
                onAccepted: {

  • @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 the role parameter before returning your data value. Qt infrastructure calls it with a variety of values of role 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 your modelItem.setData(readWrite.text) will do nothing. You must implement setData() (in a similar fashion to data()) 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

  • @JonB
    Sorry for late reply. but i had implemented SetData(), when modelItem.setData(readWrite.text) is invoked, it requires the first parameter to be PySide2.QtCore.QModelIndex. So my question is how to send this index from qml.

  • @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 the QModelIndex, if that helps from QML.)