我正在创建一个自定义QML组件(其特殊性ListView允许多个选择).我想为提供给我的组件的对象提供附加属性.我看到如何使用C++创建附加属性.但是,我找不到有关在纯QML中添加自定义属性的信息.这可能使用QML吗?
这可能使用QML吗?
没有.
在 QML 中有一种替代的、简单而干净的方法 - 只需使用实现所需属性的适配器对象。然后,而不是仅将嵌套附加到适配器中 - 将其用作父级/容器。您还可以将对象嵌套到适配器中,从而获得另一个 C++ 专有的分组属性。最小化这种开销的一种可能方法是使用 JS 对象和属性,但有一个缺点 - 没有更改通知,您可以通过手动发送来缓解这种情况。
一个例子:
// Adapter.qml - interface with attached properties
Item {
id: adapter
property int customInt : Math.random() * 1000
property var group : {"a" : Math.random(), "b" : Math.random() }
default property Component delegate
width: childrenRect.width
height: childrenRect.height
Component.onCompleted: delegate.createObject(adapter)
}
// usage
ListView {
width: 100
height: 300
model: 5
delegate: Adapter {
Row {
spacing: 10
Text { text: index }
Text { text: customInt }
Text { text: group.a }
Text { text: group.a }
}
}
}
Run Code Online (Sandbox Code Playgroud)
与其他一些 QML 解决方法相比,它相当轻松和方便。您甚至不必这样做parent.parent.customInt- 属性可以直接访问,就好像它们是附加的一样,这是因为动态范围。在default property允许避免设置内委托作为一个属性,你只是窝要直接在适配器的委托。
在许多情况下,这些杂技是矫枉过正的,你可以直接包装:
ListView {
width: 100
height: 300
model: 5
delegate: Item {
width: childrenRect.width
height: childrenRect.height
property string custom1: "another"
property string custom2: "set of"
property string custom3: "properties"
Row {
spacing: 10
Text { text: index }
Text { text: custom1 }
Text { text: custom2 }
Text { text: custom3 }
}
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的关键部分是适配器对象大小的绑定,以便视图可以正确地布局对象。我经常使用一个Wrap基本相同但用 C++ 实现的元素,它比 QML 绑定更有效。