访问命令行参数

时间:2017-02-20 15:08:14

标签: qt qml command-line-arguments qt-quick

我有一个Qt应用,QML窗口和一个自定义类,已在qmlRegisterType()注册,这基本上是我的main

int main(int argc, char *argv[])
{
   QGuiApplication app(argc, argv);
   qmlRegisterType<MyType>(...);
   QQmlApplicationEngine engine;
   engine.load(QUrl(QStringLiteral("qrc:/MyType.qml")));
}

我有一个重要的命令行选项,它改变了MyType的构造函数,这就是我想通过QML访问命令行参数的原因,我研究了一下,到目前为止我看到了两种方法:

  1. 神秘Qt.Application.arguments,其规格在Qt文件中出现,直到Qt 5发布。 Link. 我可以在我的qml文件中访问Application.arguments,但接下来该怎么办? QML引擎说它是未定义的类型,我无法像列表那样访问它,i。即Application.arguments[0]发出错误TypeError: Cannot read property '0' of undefined
  2. 获取QCommandLineParser的命令行参数,并以某种方式将其传递给我在qmlRegisterType()注册的自定义类。据我了解,MyType的构造函数是由QML引擎本身调用的,我怎样才能将参数传递给它呢?

2 个答案:

答案 0 :(得分:2)

您是否可以使用[1]中的代码添加argv[](可能首先将其设为QList?)?

QQuickView view;
view.rootContext()->setContextProperty("currentDateTime", QDateTime::currentDateTime());
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();

但是,还有另一种方法:你可以在你的MyType函数中实例化main,然后使用上面的方法将 it 传递给QML码。当然,您必须让元对象系统知道MyType,但您已经通过调用qmlRegisterType已经完成了(IIRC)。

绝对可以看一下http://doc.qt.io/qt-5/qtqml-cppintegration-contextproperties.html#setting-a-simple-context-property,它可以为您提供两种方法的详细信息。您尝试在C ++和QML之间共享信息,这必须使用Qt API完成。

[1] http://doc.qt.io/qt-5/qtqml-cppintegration-contextproperties.html#setting-a-simple-context-property

答案 1 :(得分:1)

如果您需要访问MyType构造函数内的参数,那么您需要在那里检索它们:

const QStringList args = QCoreApplication::arguments();

通过QML访问为时已晚,因为您无法通过构造函数参数。