Reputation: 32451
Ok, I know how to call C++ method from QML, but in this case it is not working.
This is how my code looks like (its not actual code since it is very big):
Container //this is my main qml element, where is everything contained and started
{
ElemA
{
id: elemA
...
}
ElemB
{
id: elemB
...
}
}
ElemA
{
MyClass
{
id: myClass
...
}
//myClass.method() //runs fine
//Now I call: elemB.myClass = myClass
//after that, if I call method() it doens't work (below is code)
}
ElemB
{
property MyClass myClass
//myClass.method() //doesn't run at all, neither shows any errors or warnings
}
ElemA and ElemB are basically states, from which I switch. It goes like this: everything starts in state ElemA, then I can switch into ElemB, but when I switch, method() is not working (as I said above, no errors or warnings).
I am pretty sure that something goes wrong (or maybe is not allowed, but somehow it passes) when I put "elemB.myClass = myClass", in other words, that I cannot pass C++ object as property to some other element (withing QML).
So my question is how I am supposed to solve this?
EDIT: My code is game actually. I have many Elem's, each Elem represents one state (for example, ElemMenu is game menu, when I press some button like "Options", it switches me to ElemOptions state where I can do some other things).
MyClass is C++ implementation for networking. Now problem is that I need to have one instance of c++ object between 2 states (networking):
Now once I accept enough client connections, I want to start game and switch to state ElemB but I need to have same object so I can manipulate with connected clients.
I have tried to inject myClass using this method: viewer.rootContext()->setContextProperty("myClass", new MyClass()); but then I am unable to use "myClass" with Connections element in QML (says that myClass property is undefined, but I can do method invocation like myClass.something().
What I am thinking right now to reimplement MyClass, and make it static. Then I could make in ElemA and ElemB instances of MyClass, but I would rather not if possible.
QtMobility is not option for me right now.
I am using QT 1.8.1 with QtCreator 2.5
Upvotes: 0
Views: 901
Reputation: 4178
Why not setting an alias on your property on elemB :
ElemB
{
property alias myClassInElemB: myClass
MyClass
{
id: myClass
...
}
}
In your code, you can do this : elemB.myClassInElemB = myClass
.
However, I think there is a problem of conception in your code. Why do you use just like ElemA
and ElemB
objects instead of the states
property of your Container
? Why do you call elemB.myClass = myClass
in ElemA.qml (source code of ElemA
) ? Solving this problem may enable you to write more simple things and avoid this problem with myClass
. Can you tell us more about your code ?
Upvotes: 1