0

I have done few things but stuck in one particular example. The code is like

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;

A Simple one but when i run this code in my qt(5.0) it shows something like QDeclarativeComponent:Component is not ready.

I know I'm missing something. On google i found that the method should be declared as Q_INVOKABLE but i don't get it why?

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
anbu selvan
  • 725
  • 3
  • 13
  • 41

1 Answers1

0

When you create a component in QML, the first step is to parse the QML file. This is what happen when you are invoking :

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

Then, prior any call on QDeclarativeComponent::create, you have to wait that the component status pass to Ready. You can track status changes by handling statusChanged signal.

Create your component instance once component becomes ready.

epsilon
  • 2,849
  • 16
  • 23