问题
I am developing a project by seperating ui.qml files and .qml files . So, I am writing the functionality codes(javascript codes) into .qml file and I am writing design codes in ui.qml file . However I have a problem with using Component.onComplete functionality in .qml file.
for example :
MapDisplayForm.ui.qml
Item{
id:item1
property alias map1
Map{
id: map1
Component.OnCompleted : {
//this is the function that i should write in Map.qml
}
}
}
MapDisplay.qml
MapDisplayForm{
//it does not accept map1.oncompleted here
}
回答1:
You can solve this problem using the QML Connections item. As an example in my form1.qml I have
SlideToAction {
id: sosSlider
height: 80
Component.onCompleted: {
if (window.getHomeLocation()) {
normalBMargin = 0
} else {
normalBMargin = -80
}
}
}
To put this into the form1Form.ui.qml and form1.qml format: form1Form.ui.qml:
property alias sosSlider:sosSlider
SlideToAction {
id: sosSlider
height: 80
}
The property alias sosSlider:sosSlider
is like saying this property is public
and won't work otherwise.
form1.qml:
Connections {
target: sosSlider
Component.onCompleted {
// Your code here
}
}
This solved the problem for me.
I like the idea of splitting up the UI and functionality. It reminds of the MVC style that Ionic/Angular and also Django views use. It makes it really easy to play around with the UI without worrying about dependencies or other qml restrictions.
Hope this helps!
回答2:
UI files are meant to be used ONLY with the designer (which does not work pretty well with imperative JS). The solutions can be:
- Remove the .ui or use common .qml files
- Use an property to handle the onCompleted event and use that property in your qml file to do what you want like the next example.
MapDisplayForm.ui.qml
Item {
id:item1
property bool propertyOnCompleted: false
Map {
id: map1
Component.onCompleted: propertyOnCompleted = true
}
MapDisplay.qml
MapDisplayForm {
onPropertyOnCompletedChanged: {
console.log("Map1 Completed")
}
}
回答3:
You can do something like the following:
Item {
id:item1
signal mapCompleted() // <-- custom signal
property alias mapDisplay
Map {
id: map1
Component.OnCompleted : {
item1.mapCompleted(); // <-- emit custom signal
}
}
}
and so:
MapForm {
onMapCompleted: { // <-- handle custom signal
}
}
来源:https://stackoverflow.com/questions/56650756/how-can-i-transfer-component-oncompleted-method-from-ui-qml-to-qml