Nominate our 2022 Qt Champions!

Do not show data in table mysql In Tableview

  • hi guys ,
    I want to give a series of data in the table (MYSQL) in QML View ،
    To do this I created a class sqlquerymodel ، I use the following code to display
    When I open the program, there is no data in the table, what's the problem?

    #include <QSqlQueryModel>
    class SqlQueryModel : public QSqlQueryModel
        explicit SqlQueryModel(QObject *parent = 0);
        void setQuery(const QString &query, const QSqlDatabase &db = QSqlDatabase());
        void setQuery(const QSqlQuery &query);
        QVariant data(const QModelIndex &index, int role) const;
        QHash<int, QByteArray> roleNames() const {	return m_roleNames;	}
        void generateRoleNames();
        QHash<int, QByteArray> m_roleNames;
    #include "SqlQueryModel.h"
    #include <QSqlRecord>
    #include <QSqlField>
    SqlQueryModel::SqlQueryModel(QObject *parent) :
    void SqlQueryModel::setQuery(const QString &query, const QSqlDatabase &db)
        QSqlQueryModel::setQuery(query, db);
    void SqlQueryModel::setQuery(const QSqlQuery & query)
    void SqlQueryModel::generateRoleNames()
        for( int i = 0; i < record().count(); i ++) {
            m_roleNames.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
    QVariant SqlQueryModel::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;
        SqlQueryModel *sqlquerymodel = new SqlQueryModel();
        sqlquerymodel->setQuery("SELECT * FROM tbl_user");
        engine.rootContext()->setContextProperty("SqlQueryModel", sqlquerymodel);
        TableView {
            id: tableview
            anchors.fill: parent
            anchors.margins: 10
            model: SqlQueryModel
            TableViewColumn { role: "Id" ; title: "Id"; visible: true }
            TableViewColumn { role: "UserName" ; title: "UserName" }

  • Not somebody help me? :(

  • Lifetime Qt Champion


    Please practice some patience, allow 24 hours to run before bumping your own thread. This forum is community driven and not all people live in the same timezone as you.

    That said, did you check that your database connection is properly opened before running your queries ?

  • Moderators

    @MrErfan Are you sure the role's assigned in QML match with those returned from the model ? They are case-sensitive.

Log in to reply