我有一个 ListView,它显示来自 API 的一些数据。在我的列表项中,我需要有两个不同的组件树,具体取决于该行的数据。更具体地说,如果该行有关联的图像,我需要显示带有标签的图像,并以某种方式排列。如果它没有图像,那么我只想显示一个标签,以不同的方式排列。对我来说,这听起来像是我想创建两个不同的组件并动态选择要包含的组件。
目前它看起来像这样,以缩写形式:
ListItem.Empty {
id: matchItem
property string team1Name
property string team2Name
property string team1Logo
property string team2Logo
width: parent.width
Item {
id: team1Info
width: parent.width*0.3
anchors {
left: parent.left
top: parent.top
bottom: parent.bottom
}
Item {
anchors.fill: parent
anchors.margins {
top: units.gu(2)
bottom: units.gu(2)
}
Image {
id: team1LogoImage
source: team1Logo
width: parent.width
height: units.gu(5)
fillMode: Image.PreserveAspectFit
anchors.horizontalAlignment: parent.horizontalCenter
}
Label {
text: team1Name
anchors.horizontalAlignment: Text.Center
}
}
}
// Some more elements and a repeat of the above for the second team
}
问题是如果team1Logo
or team2Logo
不是有效的 URL,例如如果团队没有徽标,则图像组件将失败。
我想做的基本上是:
if (team1Logo === "") {
Label {
// Stuff to make it look good without an image
}
} else {
Image {
source: team1Logo
}
Label {
// Stuff
}
}
但据我所知,QML 并不是这样工作的。
我已经看了一下Loader
组件,这看起来可能符合要求,因为我可以在设置时使用条件source
加载器上的属性,但我无法让它工作。有谁知道如何实现我所描述的目标?
事实证明,实施起来相当简单Loader
。例子:
Item {
id: team1Info
Loader {
id: team1ItemLoader
property string name: model.team1Name
property string logo: model.team1Logo
source: (logo) ? "TeamLogoItem.qml" : "TeamItem.qml"
}
}
在这个例子中,name
and logo
然后在里面可用TeamLogoItem.qml
or TeamItem.qml
作为属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)