Please nominate your Qt Champions for 2021!

Unable to edit QSqlTableModel from QML

  • I subclassed a class SqliteModel from QSqlTableModel. I want the model to be editable so reading the documentation I found that I need to reimplement the setData function. I implemented the function as below:

    bool SqliteModel::setData(const QModelIndex &index, const QVariant &value, int role)
        if (index.isValid()) {
            bool ret = QSqlTableModel::setData(index, value, Qt::EditRole);
            qDebug() << ret << lastError(); // debug output
            if(ret) dataChanged(index, index);
            return ret;
        return false;

    However this always return false and the debug output is: false QSqlError("20", "Unable to fetch row", "datatype mismatch"). I am using the model inside QML (the items are correctly displayed and when I clicke the setData function is correctly called):

            anchors.fill: parent
            model: sqlmodel
            delegate: Label{
                text: model.linecolor
                    anchors.fill: parent
                        model.linecolor = "hello"

  • Moderators

    What is printed if you call:

    qDebug() << index.row() << value << role;

    Also, have you defined any role names? roleNames()

  • I get this:
    false QSqlError("20", "Unable to fetch row", "datatype mismatch").
    The rolenames are defined and correctly displayed.

  • Moderators

    @daljit97 said in Unable to edit QSqlTableModel from QML:

    , Qt::EditRole);

    Then you should probably pass the role and not editRole, otherwise model won't know which column to update.