将Qt imports目录路径作为参数传递

我过去使用环境变量指定imports目录路径,在看过qmlscene的代码后,我能够将imports路径作为参数传递给我的程序。下面是我的完整代码:

#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 {
   }
}

核心是使用QQmlApplicationEngine::addImportPath方法。

为了支持相对路径,我首先测试传递进来的路径,如果目录不存在,则将当前进程的目录路径加上相对路径。


你可能感兴趣的:(qt)