gpt4 book ai didi

qt - 如何获取 QML 列布局子列表?

转载 作者:行者123 更新时间:2023-12-01 14:21:27 25 4
gpt4 key购买 nike

我正在做一些 QML + c++ 项目,我在 QML 布局方面遇到了一些问题:我有两个自定义组件:

  1. 第一个:是侧边栏“SideTabBar.qml”(下图中的紫色矩形)。
  2. 第二个是侧边栏“SideBarElement.qml”中的元素。

这张图片描述了我在说什么:

我想要的是:在点击时突出显示每个侧边栏元素。

为此,我尝试遍历 columnLayout 子项并使它们变暗,除了单击的子项。但是,我还没有设法让它发挥作用。

SideTabBar.qml:

Item {
id: sideTabBar
width: 70
height: parent.height
property string activeElement: ""
ColumnLayout{
id:sidebarLayout
anchors.fill: parent
spacing:2

SideBarElement{elementId:"a1";image:"../assets/product.svg"}
SideBarElement{elementId:"a2";image:"../assets/product.svg"}

Item {Layout.fillHeight: true}
}
}

边栏元素.qml:

Item {
property alias image: sideBarElementicon.source
property string elementId: ""
id: sideBarElement
width:parent.width
Layout.preferredHeight: 70
Layout.alignment: Qt.AlignTop

Rectangle{
anchors.fill: parent
color:Qt.rgba(0,0,0,0)
}
Image {
id: sideBarElementicon
source: "genericIcon.png"
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
width: 50
height: 50
}
MouseArea{
anchors.fill: parent
onClicked:{ sideTabBar.activeElement = elementId
// compiler does not even enter this loop.
// for(var child in Layout.children){
// console.log("this is a child")
// }
}
}
}

最佳答案

在这种情况下,最好使用 Repeater,因为它具有关联的索引并使用模型来设置属性:

SideBarElement.qml

import QtQuick 2.0

Item {
property alias icon: sideBarElementicon.source
property bool highlight: false
width: parent.width
Rectangle{
anchors.fill: parent
color: highlight ? Qt.rgba(1,1,0,1) : Qt.rgba(0,0,0,0)
}
Image {
id: sideBarElementicon
source: "genericIcon.png"
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
width: 50
height: 50
}
}

SideTabBar.qml

import QtQuick 2.0
import QtQuick.Layouts 1.11

Item {
id: sideTabBar
width: 70
height: parent.height
property int currentIndex: -1
ListModel{
id: elements
ListElement {
image: "../assets/product.svg"
}
ListElement {
image: "../assets/product.svg"
}
ListElement {
image: "../assets/product.svg"
}
ListElement {
image: "../assets/product.svg"
}
ListElement {
image: "../assets/product.svg"
}
ListElement {
image: "../assets/product.svg"
}
}

Rectangle{
anchors.fill: parent
color: "purple"
}

ColumnLayout{
id:sidebarLayout
anchors.fill: parent
spacing:2
Repeater{
model: elements
SideBarElement{
id: element
highlight: ix == currentIndex
icon: image
property int ix: index
Layout.preferredHeight: 70
Layout.alignment: Qt.AlignTop
MouseArea{
anchors.fill: parent
onClicked: currentIndex = ix
}
}
}
Item {Layout.fillHeight: true}
}
}

enter image description here

enter image description here

关于qt - 如何获取 QML 列布局子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com