Row{ width: parent.width Repeater { model: buttonLabels.length Button{ width: parent.width / buttonLabels.length background: Rectangle { color: "#114670" // 设置背景颜色为红色 radius: 5 // 设置圆角半径为5 } contentItem: Text { id: btnText text: "第"+ buttonLabels[index] +"层" font.pointSize : 13 color: "#ffffff" verticalAlignment: Text.AlignVCenter horizontalAlignment: Text.AlignHCenter } onClicked: { floor = btnText.text console.log("Button clicked:", text) } } } } 这段代码中点击后改变背景颜色,将其他按键还原
时间: 2024-02-10 12:17:35 浏览: 25
可以 `Repeater` 中绑定一个 `currentIndex` 属性,表示当前选择的按钮索引,然后在 `Button` 的 `background` 中使用条件语句来判断是否为当前选中的按钮,从而设置不同的背景颜色。同时,在点击其他按钮时,将 `currentIndex` 修改为当前按钮的索引,这样就可以实现点击后改变背景颜色,将其他按键还原的效果。
以下是修改后的代码示例:
```qml
Row {
width: parent.width
Repeater {
model: buttonLabels.length
property int currentIndex: -1 // 添加 currentIndex 属性
Button {
width: parent.width / buttonLabels.length
background: Rectangle {
color: index === currentIndex ? "#114670" : "#ffffff" // 根据 currentIndex 判断是否选中
radius: 5
}
contentItem: Text {
id: btnText
text: "第" + buttonLabels[index] + "层"
font.pointSize: 13
color: index === currentIndex ? "#ffffff" : "#114670" // 根据 currentIndex 判断字体颜色
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
onClicked: {
if (index !== currentIndex) { // 判断是否为当前选中的按钮
currentIndex = index // 修改 currentIndex 为当前按钮的索引
console.log("Button clicked:", text)
}
}
}
}
}
```