Skip to content

Instantly share code, notes, and snippets.

@chilarai
Created July 12, 2020 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilarai/3d7b50d84e867bc0e7e77f8c345790e3 to your computer and use it in GitHub Desktop.
Save chilarai/3d7b50d84e867bc0e7e77f8c345790e3 to your computer and use it in GitHub Desktop.
Main.cpp for Qt - QSqlQueryModel - TableView
#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