Do not show data in table mysql In Tableview
Unsolved
QML and Qt Quick
-
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?//h #include <QSqlQueryModel> class SqlQueryModel : public QSqlQueryModel { Q_OBJECT public: 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; } private: void generateRoleNames(); QHash<int, QByteArray> m_roleNames; };
//cpp #include "SqlQueryModel.h" #include <QSqlRecord> #include <QSqlField> SqlQueryModel::SqlQueryModel(QObject *parent) : QSqlQueryModel(parent) { } void SqlQueryModel::setQuery(const QString &query, const QSqlDatabase &db) { QSqlQueryModel::setQuery(query, db); generateRoleNames(); } void SqlQueryModel::setQuery(const QSqlQuery & query) { QSqlQueryModel::setQuery(query); generateRoleNames(); } void SqlQueryModel::generateRoleNames() { m_roleNames.clear(); 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; }
//main.cpp SqlQueryModel *sqlquerymodel = new SqlQueryModel(); sqlquerymodel->setQuery("SELECT * FROM tbl_user"); engine.rootContext()->setContextProperty("SqlQueryModel", sqlquerymodel);
//main.qml TableView { id: tableview anchors.fill: parent anchors.margins: 10 model: SqlQueryModel TableViewColumn { role: "Id" ; title: "Id"; visible: true } TableViewColumn { role: "UserName" ; title: "UserName" } }
-
Hi,
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 ?