How to assign SQL query output model from Qt to QML's TableView?

别等时光非礼了梦想. 提交于 2019-12-04 16:32:34

You have to subclass QSqlQueryModel and reimplement roleNames and data methods

MySqlModel.h

class MySqlModel: public QSqlQueryModel
{
    Q_OBJECT
public:
    MySqlModel(QObject *parent = 0) : QSqlQueryModel(parent) {}

    enum Roles {
        BinId = Qt::UserRole + 1,
        PartitionId,
        UnitId,
        ItemCount
    };
    QHash<int, QByteArray> roleNames() const {
        QHash<int, QByteArray> roles;
        roles[BinId] = "binIdRole";
        roles[PartitionId] = "partitionIdRole";
        roles[UnitId] = "unitIdRole";
        roles[ItemCount] = "itemCountRole";
        return roles;
    }
    QVariant data(const QModelIndex &index, int role) const {
        if (!index.isValid())
            return QVariant();

        QString fieldName;
        switch (role) {
            case BinId: fieldName = QStringLiteral("t1.BinId"); break;
            case PartitionId: fieldName = QStringLiteral("t1.PartitionId"); break;
            case UnitId: fieldName = QStringLiteral("t2.UnitId"); break;
            case ItemCount: fieldName = QStringLiteral("t2.ItemCount"); break;
        }
        if (!this->record().isGenerated(fieldName))
            return QVariant();
        else {
            QModelIndex item = indexInQuery(index);
            if ( !this->query().seek(item.row()) )
                return QVariant();
            return this->query().value(fieldName);
        }
        return QVariant();
    }
};

main.qml

Window  {
    visible: true
    width: 640
    height: 480
    TableView {
        anchors.fill: parent
        model: SQQL
        TableViewColumn{ role: "binIdRole" ; title: "BinId" ; visible: true}
        TableViewColumn{ role: "partitionIdRole" ; title: "PartitionId" }
        TableViewColumn{ role: "unitIdRole" ; title: "UnitId" }
        TableViewColumn{ role: "itemCountRole" ; title: "ItemCount" }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!