Created
July 12, 2020 05:18
-
-
Save chilarai/3d7b50d84e867bc0e7e77f8c345790e3 to your computer and use it in GitHub Desktop.
Main.cpp for Qt - QSqlQueryModel - TableView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QGuiApplication> | |
#include <QQmlApplicationEngine> | |
#include <QQmlContext> | |
#include <QDebug> | |
#include "mysqlmodel.h" | |
int main(int argc, char *argv[]) | |
{ | |
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); | |
QGuiApplication app(argc, argv); | |
QQmlApplicationEngine engine; | |
// Mysql connection | |
// Change the credentials accrodingly | |
if(QSqlDatabase::isDriverAvailable("QMYSQL")){ | |
QSqlDatabase dbMysql = QSqlDatabase::addDatabase("QMYSQL"); | |
dbMysql.setHostName("SERVER"); | |
dbMysql.setPort(3306); | |
dbMysql.setDatabaseName("DATABASE"); | |
dbMysql.setUserName("DB_USER"); | |
dbMysql.setPassword("DB_PASSWORD"); | |
if(!dbMysql.open()){ | |
qDebug() << "Connection to mysql failed"; | |
} | |
} | |
// Initiate mysql instance | |
// And run a default query | |
MysqlModel mysqlModel; | |
mysqlModel.callSql("SELECT * FROM users"); | |
// Set the model for QML | |
engine.rootContext()->setContextProperty("MysqlModel", &mysqlModel); | |
const QUrl url(QStringLiteral("qrc:/main.qml")); | |
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, | |
&app, [url](QObject *obj, const QUrl &objUrl) { | |
if (!obj && url == objUrl) | |
QCoreApplication::exit(-1); | |
}, Qt::QueuedConnection); | |
engine.load(url); | |
return app.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment