我正在使用以下示例https://wiki.qt.io/How_to_Use_a_QSqlQueryModel_in_QML。它使用QSqlQueryModel并选择列名列表。但就我而言,我不知道输出中的表列名称,因为我正在使用  *query "Select * from users"。如何在 Qml的TableView中打印数据。
我的代码如下:
QtTest2.cpp
QtTest2::QtTest2(QObject *parent) :
    QSqlQueryModel(parent)
{
}
void QtTest2::setQuery(const QString &query, const QSqlDatabase &db)
{
    QSqlQueryModel::setQuery(query, db);
    generateRoleNames();
}
void QtTest2::setQuery(const QSqlQuery & query)
{
    QSqlQueryModel::setQuery(query);
    generateRoleNames();
}
void QtTest2::generateRoleNames()
{
    m_roleNames.clear();
    for( int i = 0; i < record().count(); i ++) {
        m_roleNames.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
    }
}
QVariant QtTest2::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;
}
void QtTest2::callSql()
{
    this->setQuery("SELECT * FROM users");
}
qml文件
import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3
Page {
id : somepageid
Component.onCompleted: {
    QtTest2.callsql();
}
TableView {
    id: tableView
    model: QtTest2
    // This is for header
    Row {
        id: columnsHeader
        y: tableView.contentY
        z: 2
        Repeater {
            model: tableView.columns > 0 ? tableView.columns : 1
            Label {
                width: tableView.columnWidthProvider(modelData)
                height: 35
                text: QtTest2.headerData(modelData, Qt.Horizontal)
                color: '#aaaaaa'
                font.pixelSize: 15
                padding: 10
                verticalAlignment: Text.AlignVCenter
                background: Rectangle { color: "#333333" }
            }
        }
    }
    // Here I cannot print the values dynamically. 
    // Currently this is printing the email (e.g.), in all columns in a row
    // But yes, each row prints different email
    // I want the rest of the column data dynamically printed
      
    delegate:Rectangle {
                        Text {
                            text: email
                            anchors.fill: parent
                            anchors.margins: 10
                            color: 'black'
                            font.pixelSize: 15
                            verticalAlignment: Text.AlignVCenter
                        }
                    }
    }
   
编辑
我已经调用了engine.rootContext()->setContextProperty("QtTest2", &qttest2);main.cpp