ManuelSchneid3r February 2016

How to outsource qml listview delegate

My delegate grew pretty big. I want to put it in a dedicated file. What do I have to do to make this work? I need clearifications especially on how to import and instantiate the delegate. For future readers a complete howto would be fine.

Answers


ddriver February 2016

You can have a property property Component delegateComponent : Qt.createComponent("file.qml") and use that as the delegate. Or directly delegate: Qt.createComponent("file.qml").

You can use a Loader for the delegate, and set its source property to the desired file. This extra level of abstraction allows different items in the list to instantiate different qml files, practically achieving different delegates.

Normally, you don't need to import anything, unless your component is registered as a part of an external module. QML files part of your projects will just work, no imports are needed.

You can click on the root object of your delegate component (not on the component but its single allowed child), go to "refactoring" and click "move component into separate file". This will result in a Component { TheNewQMLFile { } } where the TheNewQMLFile will replace the content of the object tree you promoted to a new source. It can also work in this form, without the need to use the first two techniques.

Because of QML's dynamic scoping, you can use the model roles from external QML files as well, they will be resolved as long as the object is instantiated in the correct context, i.e. as a delegate of a view with a model, providing those roles.

3 possible ways to do it:

delegate: Qt.createComponent("DelegateType.qml")

delegate: Component { DelegateType { } }

delegate: Component { Loader { source: "DelegateType.qml"} } // here source can come from a model role as well

Actually, it seems that explicitly wrapping in a Component is not even necessarily, it happens implicitly as well. So the last two will also work like this:

delegate: DelegateType { }

delegate: Loader { source: "DelegateType.qml"} 

Post Status

Asked in February 2016
Viewed 3,973 times
Voted 10
Answered 1 times

Search




Leave an answer