qt - 在 QML 中嵌套加载器
问题描述
我正在尝试以模块化方式编写我的 QML 组件,以便能够动态更改图形,但我正在努力将它们嵌套在一个层次上,下面是一个示例:
import QtQuick 2.0
import QtGraphicalEffects 1.0
WindowFrame {
id: this_item
property Component body //this wont load the component
property alias footer: footer_loader.sourceComponent //this gives an error -> Invalid alias reference. Unable to find id "footer_loader"
property int footer_height: 70
body: Item {
id: body_component
Loader {
id: body_loader
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: parent.height-this_item.footer_height
sourceComponent: this_item.body
}
Item {
anchors.bottom: parent.bottom
anchors.left: parent.left
anchors.right: parent.right
height: this_item.footer_height
z: 2
Rectangle {
anchors.fill: parent
color: Qt.rgba(0, 0, 0.5, 1)
layer.enabled: true
layer.effect: DropShadow {
transparentBorder: true
horizontalOffset: 0
verticalOffset: -8
radius: 8.0
samples: 17
color: Qt.rgba(0, 0, 0, 0.5)
}
}
Loader {
id: footer_loader
anchors.fill: parent
}
}
}
}
目标是构建具有预定义空间的组件(例如卡片),然后在其中加载其他元素,除了使用加载器之外没有找到其他任何东西,它是如何完成的?有更好的方法吗?
解决方案
你必须创建组件类型对象,而不是项目类型
import QtQuick 2.0
import QtGraphicalEffects 1.0
WindowFrame {
id: this_item
property Component body //this wont load the component
/*
* here is where you went wrong *
*
*/
body: Component { // change Item to Component
id: body_component
}
Card {
id: myCard
}
Component.onCompleted {
myCard.load_face("qrc:///jack.png")
}
}
但更好的答案是创建多个 QML 文件并动态创建这样的东西
卡片.qml
Item {
id: card
Rectangle {
width: 100
height: 100
}
function load_face(imageSource) {
var component = Qt.createComponent("CardFace.qml");
if (component.status == Component.Ready)
component.createObject(card, {"imageSource": imageSource, "y": 100});
}
}
CardFace.qml
Item {
id: face
property var imageSource
Image {
source: face.imageSource
}
}
推荐阅读
- docker - RabbitMq - Docker-compose - 如何修复“连接被拒绝 127.0.0.1:5672”异常
- jquery - Pharo Seaside - 如何在 html 中编辑标签后更新数据库条目
- c# - 如何获取 x:name 用于轻按手势的元素
- r - 当我尝试解析数据框中的 JSON 列时,我在 R 中不断收到错误
- html - 针对不同分辨率缩放页面
- ios - 为什么当 dequeueReusableCellWithIdentifier 发生时单元格中的 init 方法不会被调用
- c# - 远程服务器返回错误 (404) 未找到。在 system.net.httpwebrequest.getresponse()
- symfony - Symfony + Forms,by_reference = true 和 CollectionType 字段中的 allow_add
- mysql - MySQL Workbench 中的 For 循环
- python - 通过 buildozer 将 py 文件编译为 apk 时出现问题