QML component assignation
-
Is it possible to assign 1 component to another of the same type in this way?
MyQml.qml
@
Item{
property int var1
property string var 2
property int var3
}
@and in another file:
main.qml
@
MyQml{
id: myQml1
var1: 2
var2:'hello'
var3: 4
}MyQml{
id:myQml2
}
onSomeSignal:{
myQml2 = myQml1
}@
-
Not like this, no. There are a couple of ways to get similar behaviour, depending on precisely what it is you wish to do:
-
set visibility.
@
onSomeSignal: { myQml2.visible = true; myQml1.visible = false }
@ -
use properties.
@
property MyQml activePage: MyQml { id: myQml1; ... }
onSomeSignal: { activePage.destroy(); activePage = myQml2; }
@ -
use a Loader element to load specific instances on demand.
@
Loader {
// I forget the properties, look at the docs.
source: "MyQml.qml"
}
@
Also, note that in your example, both myQml1 and myQml2 are not actually components; they're actually object instances. The declaration of myQml1 also specifies an implicit type declaration, but I guess you can ignore that for the purposes of your use case.
Cheers,
Chris. -
-
Hi,
What I want to do is: To assign two instances of the same type using only its id's. Like:
@ onSomeSignal:{
myQml2 = myQml1
}@Thanks
-
What do you mean? I'm really not sure what you're trying to do now.
Imagine that I have two apples: a red one, and a green one.
Let's rephrase your question in terms of these apples:
"What I want to do is: onSomeSignal: { redApple = greenApple }"What are you hoping to happen?
Are you expecting all of the properties of the redApple to be changed to the values of those in the greenApple? Or what?
Or, are you expecting the id "redApple" to now point to the object with the id "greenApple"? If so, that will never work: an id uniquely identifies an instance. As I mentioned in my previous reply, if this is the behaviour you want, then you should use a property assignment instead of an id assignment.
Cheers,
Chris. -
Yes, This is what I'm expecting, all of the properties of the redApple to be changed to the values of those in the greenApple
-
As both myQml1, myQml2 are just readonly references to qml objects this will not work.
If you really would want to change ALL the properties of object you could achieve this via
@
onSomeSignal:{
copyProperties(myQml1, myQml2);
}function copyProperties(source, target) { var properties = Object.keys(source); for (var i = 0, l = properties.length; i < l; ++i) { var prop = properties[i]; var type = typeof target[prop]; if (type === "function" /* || add your own checks here */) { return; } target[prop] = source[prop]; }
}
@This does not check for properties that might not exist on the target or properties that you might not want to change (like objectName or parent) or readonly properties that you might have on those objects, so please adapt to your usecase ;)
Or in the best case - do it some other way, as proposed before.
-
thanks mutaphysis I'll try your approach