Important: Please read the Qt Code of Conduct -

QSqlTableModel in QML

  • Most of the logics of my app is in Qt/C++, but I'm using QML for the UI.
    I need to read a QSqlTableModel and create a ListView on the QML side which loads all its content. So far the only solution I found is creating an intermediate table subclasing QStandardItemModel where I need to define one additional role per column in my table where I will store my data to expose to QML and make it available in my UI.
    Is there any possibility to read columns from a QSqlTableModel directly? or the QML side only understand roles?
    I think this is a serious issue. The amount of overhead for an operation like this is no sence.
    A simple line in Qt/C++ like:


    Turns to be a ton of work in QML.

  • I have been working out on a simple solution for this limitation and I'm sharing a fearly small and simple code that do the job nicely.

    I'm sure it will be useful for others using QAbstractItemModel subclasses:

    class ProxySqlTableModel : public QSqlTableModel
    explicit ProxySqlTableModel(QObject *pObject = 0);
    QVariant data (const QModelIndex & Index, int iRole = Qt::DisplayRole) const;
    void setProxyModel(const QString& sTable);

    ProxySqlTableModel::ProxySqlTableModel(QObject *pObject) :

    QVariant ProxySqlTableModel::data (const QModelIndex & Index, int iRole) const
    if (iRole>=Qt::UserRole)
    return QSqlTableModel::data(index(Index.row(),iRole-Qt::UserRole));

    return QSqlTableModel::data(Index,iRole);

    void ProxySqlTableModel::setProxyModel(const QString& sTable)
    QHash<int, QByteArray> hashRoles;

    QSqlTableModel Table;
    QSqlRecord Record=Table.record();

    for (int i=0; i<Record.count(); i++)

  • I have the same issue, not happy with the design of Model/View with QML. It seems that only very basic use cases are possible without tons of workarounds.
    Model/View was a pain using plain Qt, it is even worse now with QML.
    Thanks for your input, I will try this.

Log in to reply