Important: Please read the Qt Code of Conduct -

QSqlRelationalTableModel::setRecord returns TRUE but isn't working

  • bool NullableModel::setNullData(const QModelIndex& idx)
        qDebug() << "from:" << this->record(idx.row()).field(idx.column()).value();
        QSqlRecord record = this->record(idx.row());
        QSqlField field = record.field(idx.column());
        record.replace(idx.column(), field);
        qDebug() << "through:" << record.field(idx.column()).value();
        bool b = this->setRecord(idx.row(), record);
        qDebug() << "to:" << this->record(idx.row()).field(idx.column()).value();
        qDebug() << "return:" << b;
        return b;

    When I run it and the value is already NULL, it seems fine:

    • from: QVariant(QString, "")
    • through: QVariant(QString, "")
    • to: QVariant(QString, "")
    • return: true

    If I want to really clear something, QSqlRelationalTableModel::setRecord also returns TRUE but the value isn't changing:

    • from: QVariant(int, 1)
    • through: QVariant(QString, "")
    • to: QVariant(int, 1)
    • return: true

    The real problem it that when I'm trying to set NULL value to the model, and the related field is foreign key of left-joined table, QSqlRelationalTableModel::setData returns FALSE:

    bool NullableModel::setNullData(const QModelIndex& idx)
        //const QVariant value = QVariant(QString(""));
        //const QVariant value = QVariant(record().field(col).type());
        const QVariant value = QVariant(0);
        return QSqlRelationalTableModel::setData(idx, value, Qt::EditRole);

    It returns FALSE even if I'm sure is already NULL and I'm trying to set it to the same value:

    bool NullableModel::setNullData(const QModelIndex& idx)
        return QSqlRelationalTableModel::setData(idx,, Qt::EditRole);

    I tried everything and didn't find any solution in the Internet so it's probably some limitation of this function... so I figured I'll try to go around and set the record manually... but it's still not working and that's my question: why QSqlRelationalTableModel::setRecord returns TRUE while the record is then unchanged and how to set the data to NULL?

    This is how I create the model:

    model = new NullableModel(ui->tableView, QSqlDatabase::database());
    role_idx = model->fieldIndex("role_id");
    model->setRelation(role_idx, QSqlRelation("Roles", "id", "role_name"));
    if (!model->select()) {

Log in to reply