Osman-pasha
Osman-pasha

Reputation: 632

How to separate design and logic of Repeater in QML

When using QML, Qt Creator advises to separate design and logic into 2 QML files, e.g. a File.qml and FileForm.ui.qml, the former for logic, the latter for design. It can only show a file in visual designer if it does not contain complex code, like function calls or {} code blocks (I'm using Qt creator 4.5.2 that comes with Ubuntu 18.04).

Now for the question: how do I move complex code out of ui.qml when I use Repeater and its delegates?

Example:

My FileForm.ui.qml looks like this:

import "displayutils.js" as Utils

RowLayout {
    property alias rr: rr
    property alias tt: tt
    Repeater {
        id: rr
        Text {
            id: tt
            text: "text: "+ Utils.fmtTemp(modelData.temp)+" / "+Utils.fmtPressure(modelData.pressure)
        }
    }
}

I instantiate it in File.qml like this:

File {
    Component.onCompleted: {
        rr.model = ... // some model from C++ code, does not matter.
    }    
}

Now, Qt Creator does not want to open FileForm.ui.qml file because of complex formatting of text and I have to move it to File.qml. How do I do this correctly? Whatever I tried, I loose modelData object from Repeater. I tried various variants of this:

File {
    tt.text = someFunction(modelData)
    Component.onCompleted: {
        rr.model = ... // some model from C++ code, does not matter.
    }    
}

Upvotes: 2

Views: 706

Answers (1)

David K. Hess
David K. Hess

Reputation: 17246

I find this separation very helpful and use it all of the time. You can do it in this case by separating out the Repeater's children like this:

RepeaterTextForm.ui.qml:

Text {}

RepeaterText.qml:

import "displayutils.js" as Utils 

RepeaterTextForm {
    text: (
        "text: " + 
        Utils.fmtTemp(modelData.temp) + 
        " / " + 
        Utils.fmtPressure(modelData.pressure)
    )
}

FileForm.ui.qml:

RowLayout {
    property alias rr: rr
    Repeater {
        id: rr
        RepeaterText {}
    }
}

File.qml:

File {
    Component.onCompleted: {
        rr.model = ... // some model from C++ code, does not matter.
    }    
}

Upvotes: 0

Related Questions