How to access to a qml object from javascript
-
Hi.
Newbie with Qt, I just started using it.
I have a very simple softThe question is how to access "text" of my dynamically created CustomButton object.
It works using
@
property string text
@and
@
button.text = "toto"
@But is it the right way to do it ?
Can I avoid the property and use something like@
button.button.text = "toto"
@to acces directly to the text of my button ?
Thanks
Forum.qml
@import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.0import "Forum.js" as Logic
ApplicationWindow {
width: 640
height: 480Component.onCompleted: { Logic.init(this) }
}@
forum.js
@
function init(parent) {
var button = Qt.createQmlObject('import QtQuick 2.2; CustomButton {width:100; height:100}', parent, "dynamicSnippet1");button.text = "toto"
}
@CustomButton.qml
@
import QtQuick 2.0
import QtQuick.Controls 1.1Item {
property string textButton { id:button width: 100 height: 62 x : 100 y : 100 } onTextChanged: { button.text = text }
}
@ -
You have just defined the text inside the item. From outside it is just tex from Item. If you want to the text of button, you need make the top text as alias for the button text
e.g
Item {
property alias text : button.text}
Now from outside you refer using button.text
Hope this helps.
-
Hi,
Your first way is correct
@
button.text = "toto"
@you can avoid the onTextChanged handler if you solely want to assign the text,
@
function init(parent) {
var button = Qt.createQmlObject('import QtQuick 2.2; CustomButton {width:100; height:100}', parent, "dynamicSnippet1");button.mytext = "toto"
}
Item {
property string mytextButton { id:button width: 100 height: 62 x : 100 y : 100 text: mytext }
}
@Notice above that mytext is binded to text property of Button.
bq. Can I avoid the property and use something like
button.button.text = "toto"
to acces directly to the text of my button ?You can't access it using id.id, but another non recommended way to do this to get the exact child using children as,
@
button.children[0].text = "Sometext"
@Since we can guess the exact child number by merely seeing the QML file we are able to do the above; but it is not recommended.