0

QSqlTableModel updates the data when directly used but while subclassing setData does return true but updates nothing:

 enum ItemRoles {
    CONTENTROLE = Qt::UserRole + 1,
    TYPEROLE = Qt::UserRole + 2,
    VIEWSROLE = Qt::UserRole + 3,
    WEIGHTROLE
};
QHash<int, QByteArray> ItemModel::roleNames() const  {
   QHash<int, QByteArray> roles;
   roles[CONTENTROLE] = "content";
   roles[TYPEROLE] = "type";
   roles[VIEWSROLE] = "views";
   roles[WEIGHTROLE] = "weight";
   return roles;
}
QVariant ItemModel::data(const QModelIndex & index, int role) const {
    QModelIndex modelIndex = this->index(index.row(), role - Qt::UserRole);
    return QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
bool ItemModel::setData(const QModelIndex &index, const QVariant &value, int role) {
    QModelIndex modelIndex = this->index(index.row(), role - Qt::UserRole);
    qDebug() << QSqlTableModel::setData(modelIndex,value, Qt::EditRole); // true
    qDebug() << lastError();
    emit dataChanged(modelIndex,modelIndex);
    return true;
}
//
QModelIndex index = itemModel->index(0, 0);

qDebug() <<  itemModel->data(index, itemModel->CONTENTROLE);  // SOMETHING
itemModel->setData(index, "VALUE",  itemModel->CONTENTROLE);  
qDebug() <<  itemModel->data(index, itemModel->CONTENTROLE); // SOMETHING [should be VALUE]

Note: Most examples on the web are related to PyQt and there are very few references of c++ code in this regard.

dev-Bilal
  • 1
  • 1
  • Doc for [QSqlQueryModel](https://doc.qt.io/qt-5/qsqlquerymodel.html): "The QSqlQueryModel class provides a read-only data model for SQL result sets" - so you call the wrong base function for data(). Also you use EditRole in one and DislayRole in the other function. – chehrlic Dec 02 '21 at 17:52
  • I have made changes but now "data" function returns QVariant(Invalid) after setting data with same index. – dev-Bilal Dec 02 '21 at 19:35
  • .. after changing QSqlQueryModel to QSqlTableModel in "data" function. "setData" makes every value in the record invalid. – dev-Bilal Dec 02 '21 at 19:44
  • @chehrlic [Compilable Test Project] (https://drive.google.com/uc?export=download&id=1CkGsyyh0pE4ctX3Tt1zQYJEpsrMlz39A) – dev-Bilal Dec 04 '21 at 06:09

0 Answers0