Important: Please read the Qt Code of Conduct -

SetData() in QSqlTableModel with role other than Qt::EditRole does not work

  • Hi,

    I have been trying to change the background colour of rows matching certain criteria on a QTableView that uses a QSqlTableModel as the model. For this, I modify the Qt::BackgroundRole attribute of the relevant items, using the following sort of code (ObsEditTableModel inherits from QSqlTableModel), and basically has just this one method:

    void ObsEditTableModel::setObsGood(const QModelIndex & item, bool goodObs)
    int i = item.row();
    for (int j = 0; j < columnCount(); j++) {
    QModelIndex cell = index(i, j);
    if (goodObs) {
    bool r = setData(cell, QVariant(QBrush(Qt::gray)), Qt::BackgroundRole);
    qDebug() << goodObs << r << i << j;
    } else {
    bool r = setData(cell, QVariant(), Qt::BackgroundRole);
    qDebug() << goodObs << r << i << j;
    QModelIndex tl = index(i, 0);
    QModelIndex br = index(i, columnCount()-1);
    emit dataChanged(tl, br);

    The problem is that setData() always returns false, and nothing changes in the view. After a few hours of Googling, I have found the following recent post with appears to describe, as far as I can tell, my exact problem:

    Any solutions or hints as to how to solve this would be extremely appreciated.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    The thing is that modifying any other data role in a sql model doesn't make sense: the idea of the QSqlTableModel and QSqlQueryModel is to interact with a database which doesn't care about the background color.

    For this kind of modification you should have a look at "QIdentityProxyModel":

    Hope it helps

  • Hi

    Thank you for your reply. I suppose your argument makes sense--however, I wish it would be explicitly documented (any idea where Qt's Bugzilla is these days? maybe? So I can file a documentation bug).

    I will take a look at QIdentityProxyModel. Many thanks again!

  • P.S.: I had to AdBlock * to be able to post, otherwise it would just hang forever.

  • Moderators

    yep that's the correct place for bugreports ;)

  • [quote author="raven-worx" date="1376481343"]yep that's the correct place for bugreports ;)[/quote]

    Ta much! :)

Log in to reply