Important: Please read the Qt Code of Conduct -

QSqlTableModel::setData() works but it does not do any change to the database

  • My purpose :
    I have a table in my database with column 'gender'.
    And I set the type int for column 'gender', so it can only store integer like 0, 1 in the database.
    But I don't want to display gender with 0 or 1 in my application, or modify the gender with 0 or 1.

    My solution:
    I override the functions QSqlTableModel::setData() and QSqlTableModel::data(),
    in my class class MyTableModel : public QSqlTableModel.

       QVariant data(const QModelIndex &idx,
                      int role = Qt::DisplayRole) const {
            if (idx.column() == 2) {
                QVariant var = QSqlTableModel::data(idx, role);
                qDebug() << "var : " << var.toString();
                if (var.toInt() == 0) {
                    return QVariant("female");
                else {
                    return QVariant("male");
            return QSqlTableModel::data(idx, role);
        bool setData(
                const QModelIndex &index,
                const QVariant &value,
                int role = Qt::EditRole){
           if (index.column() == 2) {
               int newValue = value.toString() == "female" ?
                           0 : 1;
               return QSqlTableModel::setData(index, newValue, role);
           // column() != 2
           else {
                return QSqlTableModel::setData(index, value, role);

    This code is wrong, but I have try my best.
    I am to new to Qt, I just can't make it right.
    I don't know how to override these functions or maybe there is another solution?

    Can someone help me?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    No need to alter the model. You should create a custom QStyledItemDelegate that will handle that part.

Log in to reply