I am new to QML and would like to understand how object creation works when splitting code over different files (as it feels like a good code practice).

I know I can call property of an item within the same file:

// MyItem.qml
Item {
  id: myItem
  property string name: "Myself"

  onClicked: {
    console.log(myItem.name)
  }
}

but how do I create an instance of the same item in a different file?

// Main.qml
Button {
  onClicked: {
    console.log(myItem.name)
  }
}

Throws a ReferenceError: name is not defined error which I suppose means: "can not call property name of an undefined object".

Is this common practice in QML (don't see a lot of examples doing this) or does everyone simply put everything in the same file?

share|improve this question
up vote 2 down vote accepted

You do something like:

// Main.qml
MyItem {
    id: thisIsMyItem
}
Button {
    onClicked: console.log(thisIsMyItem.name)
}

The idea is that you can use the components you declared in the same document referenced by their id. You call these files "documents" in QML.

Another thing is that you don't need to use the myItem id in MyItem.qml, you can simply reference the name property with its name. Of course, using the id is necessary when you have multiple components in the same document with the 'name' property.

// MyItem.qml
Item {
    id: myItem
    property string name: "Myself"
    Item {
        id: secondItem
        property string name: "Second Item"
        Component.onCompleted: console.log("This item's name is " + name + ", and parent item's name is " + myItem.name) 
    }
}

One remark: that onClicked in your MyItem.qml would give a syntax error, as Item has no clicked() signal.

Hope this helps.

share|improve this answer
    
Now I get it, thanks! I defined a new type and need to create an instance like you explain. This is an eye opener! – Cimm Mar 16 '15 at 20:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.