Qt 如何在QML上重用代码
我有一段QML代码:Qt 如何在QML上重用代码,qt,qml,Qt,Qml,我有一段QML代码: Column { spacing: units.gu(2) anchors { fill: parent centerIn: parent } Row { spacing: units.gu(4) ... } Row { spacing: units.gu(4)
Column {
spacing: units.gu(2)
anchors {
fill: parent
centerIn: parent
}
Row {
spacing: units.gu(4)
...
}
Row {
spacing: units.gu(4)
...
}
Row {
spacing: units.gu(4)
...
}
Row {
spacing: units.gu(4)
...
}
}
关于QML编程的最佳实践,如何重用代码以避免公共元素的重复属性?与上面的示例类似,避免使用“spacing:units.gu(4)”行。将代码放在单独的qml文件中,并将该文件名用作元素。例如 //文件MyCustomRow.qml
Row {
spacing: units.gu(4)
...
}
然后在其他qml文件中:
Column {
spacing: units.gu(2)
anchors {
fill: parent
centerIn: parent
}
MyCustomRow{
}
MyCustomRow{
}
MyCustomRow{
}
MyCustomRow{
}
}
事实上,您可以使用中继器:
Column
{
spacing: units.gu(2)
anchors
{
fill: parent
centerIn: parent
}
Repeater
{
model : 5
MyCustomRow
{
}
}
}
编辑: 要在单个文件中执行此操作(如注释中所述),可以将Qml元素与元素一起使用:
有趣。如何在同一个文件中实现这一点?
Column {
spacing: units.gu(2)
anchors {
fill: parent
centerIn: parent
}
Component
{
id : myCustomRow
Row
{
spacing: units.gu(4)
...
}
}
Loader {
sourceComponent : myCustomRow
}
Loader {
sourceComponent : myCustomRow
}
Loader {
sourceComponent : myCustomRow
}
Loader {
sourceComponent : myCustomRow
}
}