为什么我会收到"QDeclarativeComponent:Component is not ready"错误?

Why do I get a "QDeclarativeComponent:Component is not ready" error?

本文关键字:is not ready 错误 Component QDeclarativeComponent 为什么      更新时间:2023-10-16

我做了一些事情,但只停留在一个特定的例子中。代码类似

MyItem.qml

 import QtQuick 1.0
 Item {
     function myQmlFunction(msg) {
         console.log("Got message:", msg)
         return "some return value"
     }
 }

main.cpp

 QDeclarativeEngine engine;
 QDeclarativeComponent component(&engine, "MyItem.qml");
 QObject *object = component.create();
 QVariant returnedValue;
 QVariant msg = "Hello from C++";
 QMetaObject::invokeMethod(object, "myQmlFunction",
         Q_RETURN_ARG(QVariant, returnedValue),
         Q_ARG(QVariant, msg));
 qDebug() << "QML function returned:" << returnedValue.toString();
 delete object;

这是一个简单的例子,但当我在qt(5.0)中运行此代码时,它会显示如下内容QDeclarativeComponent:组件尚未就绪。

我知道我错过了什么。在谷歌上,我发现这个方法应该声明为Q_INVOKABLE,但我不明白为什么?

在QML中创建组件时,第一步是解析QML文件。这就是当您调用时发生的情况:

QDeclarativeComponent component(&engine, "MyItem.qml");

然后,在调用QDeclarativeComponent::create之前,您必须等待组件状态传递给Ready。您可以通过处理状态更改信号来跟踪状态更改。

一旦组件准备就绪,就创建组件实例。

相关文章: