如何在QML中分离中继器的设计和逻辑

问题描述 投票:2回答:1

在使用QML时,Qt Creator建议把设计和逻辑分成2个QML文件,比如一个File.qml和FileForm.ui.qml,前者用于逻辑,后者用于设计。它只能在visual designer中显示一个文件,如果它不包含复杂的代码,比如函数调用或{}代码块(我使用的是Ubuntu 18.04自带的Qt creator 4.5.2)。

现在的问题是:当我使用Repeater和它的委托时,我如何将复杂的代码从ui.qml中移出?

举个例子。

我的 FileForm.ui.qml 看起来像这样。

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)
        }
    }
}

我把它实例化在 File.qml 像这样。

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

现在,Qt Creator不想打开。FileForm.ui.qml 文件,因为文本格式复杂,我必须把它移到File.qml中。我如何正确地做到这一点?无论我尝试了什么,我都会从Repeater中丢失modelData对象。我尝试了各种变体。

File {
    tt.text = someFunction(modelData)
    Component.onCompleted: {
        rr.model = ... // some model from C++ code, does not matter.
    }    
}
qt qml qt-creator
1个回答
0
投票

我觉得这种分离非常有用,而且一直在使用。在这种情况下,你可以这样做,把Repeater的子代分离出来。

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.File.qml: RepeaterText.qml: RepeaterText.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.
    }    
}
© www.soinside.com 2019 - 2024. All rights reserved.