Thursday 9 January 2014

Pass Qt imports folder path as one argument

I used to set imports folder path using environment variable, after look inside the code of qmlscene, I can pass the imports folder as an argument to my app, below is my full code:
#include <QtQml>
#include <QtQuick/QQuickView>
#include <QtCore/QString>
#include <algorithm>
#ifdef QT_WIDGETS_LIB
#include <QtWidgets/QApplication>
#else
#include <QtGui/QGuiApplication>
#endif

#ifdef QT_WIDGETS_LIB
#define Application QApplication
#else
#define Application QGuiApplication
#endif
QCoreApplication* createApplication(int & argc, char * argv[]) {
for (int i = 1; i < argc; ++i) {
if (!qstrcmp(argv[i], "-no-gui")) {
return new QCoreApplication(argc, argv);
}
}
return new QApplication(argc, argv);
}
int main(int argc, char *argv[])
{
if ((argc != 3) || qstrcmp(argv[1], "-I")) {
qWarning("Error: You must pass the location of plugins as one argument, e.g. -I ..\imports");
return -1;
}
QDir folder(argv[2]);
QString imports_dir_path;
if (!folder.exists()) {
QFileInfo info(argv[0]); QDir dir(info.absoluteDir().absolutePath() + QDir::separator() + argv[2]);
imports_dir_path = dir.absolutePath(); if (!dir.exists()) { QString err = "Error: The passed imports path is not a real folder, -I " + folder.absolutePath();
qWarning(err.toStdString().c_str());
return -1;
}
} else {
imports_dir_path = folder.absolutePath();
}

QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
if (qobject_cast<QApplication*>(app.data())) {
QQmlApplicationEngine engine;
engine.addImportPath(imports_dir_path); engine.load(QUrl("qrc:/qmls/main.qml"));
QObject * topLevel = engine.rootObjects().value(0);
QQuickWindow * window = qobject_cast<QQuickWindow*>(topLevel);
if (!window) {
qWarning("Error: Your root item has to be a Window.");
return -1;
}
window->showMaximized();
return app->exec();
} else {
}
}
The key is to use QQmlApplicationEngine::addImportPath method. 
For supporting the relative path, I test the passed path first, if it does not exit, I concatenate the current process folder and relative path. 


No comments:

Followers

Contributors