C
QML 最佳实践
应用程序的 QML 代码可能会对闪存和随机访问内存的占用产生显著影响。通过编写简洁的 QML 代码(避免重复),您可以减少生成的 C++ 代码量及其在闪存中的占用空间。以下各节介绍了其他可用于减少内存占用并提升性能的技术。
创建可重用组件
与其在多个位置重复相同的代码模式,不如考虑将该模式封装到一个单独的 QML 文件中。
例如,下面的代码包含一组标签,每个标签都包含一些文本和一张图片:
Column { spacing: 15 anchors.centerIn: parent Rectangle { width: 250 height: 120 color: "#e7e3e7" Row { anchors.centerIn: parent spacing: 10 Text { anchors.verticalCenter: parent.verticalCenter text: "Entry 1" color: "#22322f" font.pixelSize: 22 } Image { anchors.verticalCenter: parent.verticalCenter source: "img1.png" } } } Rectangle { width: 250 height: 120 color: "#e7e3e7" Row { anchors.centerIn: parent spacing: 10 Text { anchors.verticalCenter: parent.verticalCenter text: "Entry 2" color: "#22322f" font.pixelSize: 22 } Image { anchors.verticalCenter: parent.verticalCenter source: "img2.png" } } } }
您可以通过创建Label.qml 文件来简化此代码,其中包含如下所示的可配置属性或属性别名:
import QtQuick 2.15 Rectangle { property alias imageSource: imageItem.source property alias text: textItem.text width: 250 height: 120 color: "#e7e3e7" Row { anchors.centerIn: parent spacing: 10 Text { id: textItem anchors.verticalCenter: parent.verticalCenter color: "#22322f" font.pixelSize: 22 } Image { id: imageItem anchors.verticalCenter: parent.verticalCenter } } }
您可以在原始的 QML 代码中重用此 QML 组件,从而避免代码重复:
Column { spacing: 15 anchors.centerIn: parent Label { text: "Entry 1" imageSource: "img1.png" } Label { text: "Entry 2" imageSource: "img2.png" } }
限制属性更改
如果一个 QML 文件包含大量状态,且有许多属性会通过 `PropertyChanges` 受这些状态影响,则会生成庞大且复杂的 C++ 代码。生成的代码大小为 `N x M`,其中 N 表示状态数量,M 表示在这些状态中由 `PropertyChanges ` 更新的唯一属性数量。
以下是一个仅包含两个状态和两个属性的示例,但请设想,在同一个 QML 组件中,为了在多种视图之间进行切换,可能需要处理更多类似的状态:
Item { state: "0" states: [ State { name: "0" PropertyChanges { target: viewA; visible: true } }, State { name: "1" PropertyChanges { target: viewB; visible: true } } ] ViewA { id: viewA visible: false } ViewB { id: viewB visible: false } }
您可以通过根据状态直接设置视图的 visible 属性来优化这一点:
Item { id: root state: "0" states: [ State { name: "0" }, State { name: "1" } ] ViewA { id: viewA visible: root.state == "0" } ViewB { id: viewB visible: root.state == "1" } }
避免出现空容器项
`Item` 类型可用于将其他项分组,从而能够以组合方式设置它们的可见性和位置。请限制容器项的使用,因为它们会增加内存占用。例如,以下代码片段中的外层 `Item` 项是多余的:
相反,您可以直接使用其中的 Image 项:
Image { anchors.fill: parent source: "img.png" }
动态加载组件
您的应用程序可能包含许多项目且结构复杂的QML组件,这些组件会在不同时间显示。您可以通过使用Loader 类型动态加载此类组件,从而减少内存占用。
在加载新项目之前,请显式卸载现有的隐藏项目,以避免内存使用量激增。根据应用程序的 UI 设计和内存限制,请确保在任何给定时刻仅加载一定数量的项目。以下示例演示了如何确保在任何给定时刻,SwipeView 中仅有一页被加载到内存中:
SwipeView { id: theSwipe width: parent.width * 0.5 height: parent.height * 0.5 anchors.centerIn: parent clip: true function updateLoaderStates() { console.log("updating loader states ...") if (theSwipe.currentIndex === 0) { loader1.source = "" loader0.source = "FirstPage.qml" } else if (theSwipe.currentIndex === 1) { loader0.source = "" loader1.source = "SecondPage.qml" } } Component.onCompleted: updateLoaderStates() onCurrentIndexChanged: updateLoaderStates() Loader { id: loader0 onItemChanged: { if (item) { console.log("loader0 loaded") } else { console.log("loader0 free") } } } Loader { id: loader1 onItemChanged: { if (item) { console.log("loader1 loaded") } else { console.log("loader1 free") } } } }
一般而言,请勿依赖绑定项的评估顺序。在以下示例中,您无法控制项目的加载和卸载顺序。这可能会导致应用程序的两页都暂时占用内存:
SwipeView { id: mySwipe width: parent.width * 0.5 height: parent.height * 0.5 anchors.centerIn: parent clip: true onCurrentIndexChanged: { console.log("index changed ...") } Loader { source: "FirstPage.qml" active: mySwipe.currentIndex === 0 onItemChanged: { if (item) { console.log("loader0 loaded") } else { console.log("loader0 free") } } } Loader { source: "SecondPage.qml" active: mySwipe.currentIndex === 1 onItemChanged: { if (item) { console.log("loader1 loaded") } else { console.log("loader1 free") } } } }
减少可视化组件的数量
每个视觉项在运行时通常都会带来一定的处理和渲染开销。如果可能,请减少构建用户界面所需的视觉项数量。以下是一些实现方法的示例。
减少重叠的图像
如果两个图像在用户界面中总是重叠,最好将它们合并为一张图像。过多的重叠图像会降低性能并消耗更多内存。例如,以下代码片段中的inner.png 比outer.png 这张图像更小:
与其分别使用,不如将inner.png 和outer.png 合并为一张图片:
Image { source: "combined.png" }
如果静态文本与图像重叠,建议将该文本直接添加到图像中,而不是使用单独的“文本”或“StaticText ”元素。
减少“文本”元素的数量
如果可以将多个“文本”控件合并为一个,请避免将它们排成一排。例如,以下代码片段展示了两个排成一排的“文本”控件:
您可以将它们合并为一个文本项:
Text { text: "Temperature: " + root.temperature }
减少绑定数量
减少绑定数量可节省ROM空间
使用隐式尺寸
在可能的情况下,您可以通过使用隐式尺寸来减少绑定数量
对图像使用隐式维度
请以正确的尺寸创建图片,这样您就不必在每次使用图片时都指定宽度和高度属性。
Image { width: 64 height: 64 fillMode: Image.pad source: "image/background.png" }
取而代之,请使用隐式宽度和高度:
Image { source: "image/background.png" }
为组件使用隐式尺寸
通过使用隐式尺寸,您可以减少常用组件上的绑定数量。
例如,考虑在IconButton.qml 中定义的IconButton,它没有隐式尺寸:
这迫使组件的使用者必须指定组件的宽度和高度
IconButton { width: 64 height: 64 iconSource: "home.png" }
相反,应如下所示创建 IconButton:
MouseArea { implicitWidth: img.implicitWidth implicitHeight: img.implicitHeight property alias iconSource: img.source Image { id: img source: "" } }
这样可以减少绑定数量。
IconButton { iconSource: "home.png" }
在这种情况下,虽然组件的大小增加了,但如果该组件被频繁使用,总体上节省的ROM空间将会更多。
文本和图像的可见性
通过分别将空字符串作为text 和source 属性的值,来控制应用程序中文本和图像项的可见性。
例如,由以下代码定义的组件:
Item { property alias iconVisible: img.visible property alias textVisible: txt.visible property alias imageSource: img.source property alias text: txt.text Image { id: img source: "" } Text { id: txt text: "" } }
您可以按以下方式使用此类组件:
MyComponent { textVisible: false text: "" iconVisible: true imageSource: "images/background.png" }
您也可以不使用可见性属性来实现相同的效果:
Item { property alias imageSource: img.source property alias text: txt.text Image { id: img source: "" } Text { id: txt text: "" } }
如下例所示,当您使用该组件时,图像项是可见的,但文本项不可见:
MyComponent { imageSource: "images/background.png" }
使用状态来封装属性
将此方法应用于最常用的组件。例如,以下Header 组件:
Row { property alias button1Text: btn1.text property alias button2Text: btn2.text property alias button3Text: btn3.text Button { id: btn1 text: "" } Button { id: btn2 text: "" } Button { id: btn3 text: "" } }
您需要指定 3 个绑定:
Header { button1Text: "Back" button2Text: "OK" button3Text: "Info" }
或者,你可以将这些属性打包到状态中:
Row { Button { id: btn1 text: "" } Button { id: btn2 text: "" } Button { id: btn3 text: "" } states: [ State { name: "VariantA" PropertyChanges { target: btn1 text: "Back" } PropertyChanges { target: btn2 text: "OK" } PropertyChanges { target: btn3 text: "Info" } } ] }
这将绑定数量减少到仅有一个:
Header { state: "VariantA" }
保持信号简单
只要可能,就应尽量简化信号。例如,当 MyComponent.qml 组件中包含许多逻辑上相似的按钮时:
Item { id: root signal button1Clicked signal button2Clicked Row { Button { text: "Ok" onClicked: { root.button1Clicked() } } Button { text: "Cancel" onClicked: { root.button2Clicked() } } } }
你需要 2 个绑定,每个信号各一个:
Rectangle { MyComponent { onButton1Clicked: { console.log("Ok") } onButton2Clicked: { console.log("Cancel") } } }
相反,应使用一个信号,并通过传递索引来标识哪个按钮被点击
Item { id: root signal buttonClicked(index: int) Row { Button { text: "Ok" onClicked: { root.buttonClicked(0) } } Button { text: "Cancel" onClicked: { root.buttonClicked(1) } } } }
这样,你只需一个绑定即可:
Rectangle { MyComponent { onButtonClicked: { switch(index) { case 0: { console.log("Ok") break; } case 1: { console.log("Cancel") break; } } } } }
缩减模型的规模
不要将所有委托属性都放在模型中。通过在视图中直接指定属性,减少使用的属性数量。
例如,不要创建如下所示的模型:
Rectangle { property ListModel myModel : ListModel { ListElement { textcolor: "blue" name: "John" age: 20 } ListElement { textcolor: "blue" name: "Ochieng" age: 30 } } ListView { anchors.fill: parent model: myModel delegate: Text { width: 50 height: 50 color: model.textcolor text: "Name: %1 Age: %2".arg(model.name).arg(model.age) } } }
如果所有数据的 textcolor 属性值都相同,请将其从模型中移除并作为属性声明,以减小模型大小并避免不必要的重复:
Rectangle { property ListModel myModel : ListModel { ListElement { name: "John" age: 20 } ListElement { name: "Ochieng" age: 30 } } property string textcolor ListView { anchors.fill: parent model: myModel delegate: Text { width: 50 height: 50 color: textcolor text: "Name: %1 Age: %2".arg(model.name).arg(model.age) } } }
共享大型 ListModel
在 QML Singleton 中使用 `ListModel ` 属性,在应用程序的不同部分之间共享 `ListModel `。这有助于节省 ROM 空间。
// AppConfig.qml pragma Singleton .. QtObject { property ListModel mySharedModel: ListModel { ListElement { bgcolor: 'red' } ListElement { bgcolor: 'yellow' } ListElement { bgcolor: 'blue' } ListElement { bgcolor: 'green' } ListElement { bgcolor: 'orange' } ListElement { bgcolor: 'black' } ListElement { bgcolor: 'gray' } ... } }
// Page1.qml Repeater { model: AppConfig.mySharedModel delegate: .. } // Page2.qml ListView { model: AppConfig.mySharedModel delegate: .. }
拆分大型 ListModel
如果您有一个大型的ListModel ,且每个ListElement 都包含许多属性,请考虑将数据按纵向拆分为多个QML基本类型的列表。这将节省ROM空间,并减少绑定生成的C++代码量。有关更多信息,请参阅“减少绑定数量”。
示例:
ListModel {
id: myModel
ListElement { name: "Hans"; age: 25; city: "Berlin"; x: 10; y: 20; }
ListElement { name: "Marie"; age: 30; city: "Paris"; x: 15; y: 25; }
ListElement { name: "Luca"; age: 35; city: "Rome"; x: 20; y: 30; }
ListElement { name: "Eva"; age: 40; city: "Madrid"; x: 25; y: 35; }
// ...
}
Repeater {
model: myModel
Text {
text: model.name + ", " + model.age + ", " + model.city
}
}Qt Quick 在前面的示例中,Ultralite 为每个属性生成了 20 个(5 * number of ListElements )绑定。通过以下方法,您可以将其减少到仅 4 个:
readonly property list user_name: ["Hans", "Marie", "Luca", "Eva", ...] readonly property list user_age: [25, 30, 35, 40, ...] readonly property list user_city: ["Berlin", "Paris", "Rome", "Madrid", ...] readonly property list user_position: [Qt.point(10, 20), Qt.point(15, 25), Qt.point(20, 30), Qt.point(25, 35), ...] Repeater { model: parent.names.length Text { x: user_position[index].x y: user_position[index].y text: user_name[index] + ", " + user_age[index] + ", " + user_city[index] } }
注意: Qt Quick Ultralite 会为对象列表中的每个属性生成绑定。此方法仅适用于 {QML 基本类型}。
目前,length 属性会被复制,而非与模型绑定。这意味着您应显式更新模型值,以确保其能适应列表的大小。
在某些 Qt 许可证下可用。
了解更多。