访问命令行参数
Access command line arguments
我有一个 Qt 应用程序,QML window 和一个自定义 class,已在 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 访问命令行参数的原因,我研究了一下,到目前为止我看到了两种方法:
- Mystical
Qt.Application.arguments
,其规范在 Qt 5 发布之前一直存在于 Qt 文档中。 Link.
我可以在我的 qml 文件中访问 Application.arguments
,但接下来要做什么呢? QML 引擎说它是未定义的类型,我不能像列表一样访问它,我。 e. Application.arguments[0]
报错 TypeError: Cannot read property '0' of undefined
.
- 使用
QCommandLineParser
获取命令行参数,并以某种方式将其传递给我的自定义 class,注册于 qmlRegisterType()
。据我了解,MyType
的构造函数是由QML引擎本身调用的,那么我该如何将参数传递给它呢?
您是否可以使用 [1] 中的代码添加 argv[]
(也许先将其设为 QList
?)?
QQuickView view;
view.rootContext()->setContextProperty("currentDateTime", QDateTime::currentDateTime());
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
但是,还有另一种方法:您可以在 main
函数中实例化 MyType
,然后使用 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
如果您需要访问 MyType
的构造函数中的参数,那么您需要在那里检索它们:
const QStringList args = QCoreApplication::arguments();
通过 QML 访问为时已晚,因为您无法传递构造函数参数。
我有一个 Qt 应用程序,QML window 和一个自定义 class,已在 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 访问命令行参数的原因,我研究了一下,到目前为止我看到了两种方法:
- Mystical
Qt.Application.arguments
,其规范在 Qt 5 发布之前一直存在于 Qt 文档中。 Link. 我可以在我的 qml 文件中访问Application.arguments
,但接下来要做什么呢? QML 引擎说它是未定义的类型,我不能像列表一样访问它,我。 e.Application.arguments[0]
报错TypeError: Cannot read property '0' of undefined
. - 使用
QCommandLineParser
获取命令行参数,并以某种方式将其传递给我的自定义 class,注册于qmlRegisterType()
。据我了解,MyType
的构造函数是由QML引擎本身调用的,那么我该如何将参数传递给它呢?
您是否可以使用 [1] 中的代码添加 argv[]
(也许先将其设为 QList
?)?
QQuickView view;
view.rootContext()->setContextProperty("currentDateTime", QDateTime::currentDateTime());
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
但是,还有另一种方法:您可以在 main
函数中实例化 MyType
,然后使用 it 传递给 QML以上代码。当然,您必须让 MyType
为元对象系统所知,但您已经通过调用 qmlRegisterType
.
一定要看看 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
如果您需要访问 MyType
的构造函数中的参数,那么您需要在那里检索它们:
const QStringList args = QCoreApplication::arguments();
通过 QML 访问为时已晚,因为您无法传递构造函数参数。