Frage

I wrote QSQLTableModel inheritor for working with qml and it's work well. I need use it with QTableView too, data shows, but I cannot modify it - when I edit everything is ok, but all changes drop when I get out from field (I know about editStrategy, but the problem occurs earlier). I suppose that something wrong with virtual function, but I cant undestant what. If i create QSqlTableModel with the same parameters, everything is ok. Somebody have any idea how can i fix this? My code:

h:

class ListModel : public QSqlTableModel
{

    Q_OBJECT
    Q_PROPERTY( int count READ rowCount() NOTIFY countChanged())

signals:
    void countChanged();

public:
    Q_INVOKABLE QVariant data(const QModelIndex &index, int role) const;
    ListModel(QObject *parent, QSqlDatabase _db):QSqlTableModel(parent,_db){this->setEditStrategy(QSqlTableModel::OnManualSubmit);}
    void applyRoles();
#ifdef HAVE_QT5

virtual QHash<int, QByteArray> roleNames() const{return roles;}

#endif

private:
    int count;
    QHash<int, QByteArray> roles;
};

cpp:

//based on http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML

void ListModel::applyRoles()
{
    roles.clear();
    qDebug()<<"\n"<<this->tableName();
    for (int i = 0; i < this->columnCount(); i++) {
            QString role=this->headerData(i, Qt::Horizontal).toString();
            roles[Qt::UserRole + i + 1] = QVariant(role).toByteArray();
            qDebug()<<this->headerData(i, Qt::Horizontal);
    }
#ifndef HAVE_QT5
    setRoleNames(roles);
#endif
}

QVariant ListModel::data(const QModelIndex &index, int role) const{

    QVariant value;
    if(role < Qt::UserRole)
    {
        value = QSqlQueryModel::data(index, role);
    }
    else {
        int columnIdx = role - Qt::UserRole - 1;
        QModelIndex modelIndex = this->index(index.row(), columnIdx);
        value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
    }
    return value;
}

UPD I understood that the problem is in data method's quantifier const, if I remove it everything is ok with QTableView, but I cant get data from model with gml's listviews. I see only one solution - replace interition from QSqlTableModel with aggregation it, but maybe someone knows better solution?

War es hilfreich?

Lösung

Summary: Solved with strange hack - inherited from QSqlRelationalTableModel instead QSqlTableModel, I think the reason is that QSqlRelationalTableModel has rewritten non virtual method data

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top