如何为QML三方切换控件实现红色指示器滑动动画?
解决方案
修改MyRadioButton.qml
移除内部自定义指示器,隐藏默认指示器并确保无文字,仅保留图片:
RadioButton { id: root width: 90 height: 50 text: "" indicator: Item {} Image { source: "qrc:/image.png" sourceSize.width: 50 sourceSize.height: 50 anchors.centerIn: parent } }
修改MyToggle.qml
将红色指示器改为全局独立元素,统一控制滑动动画,同时用RadioGroup实现按钮互斥选中:
Rectangle { color: "gray" width: 400 height: 50 Row { id: rowId anchors.fill: parent spacing: 0 // 全局红色指示器,位于按钮下方 Rectangle { id: indicator width: 90 height: 50 color: "red" opacity: 0.8 z: -1 x: btn1.x } MyRadioButton { id: btn1 checked: true onClicked: animateIndicator() } MyRadioButton { id: btn2 onClicked: animateIndicator() } MyRadioButton { id: btn3 onClicked: animateIndicator() } // 触发指示器滑动动画 function animateIndicator() { const targetBtn = rowId.children.find(btn => btn.checked) if (targetBtn) { animationId.to = targetBtn.x animationId.restart() } } PropertyAnimation { id: animationId target: indicator property: "x" duration: 300 easing.type: Easing.InOutQuad } } // 管理按钮互斥选中状态 RadioGroup { id: radioGroup buttons: rowId.children.filter(child => child instanceof RadioButton) } }
关键修改说明
- 将红色指示器提取为Row内的独立元素,避免每个按钮单独管理指示器的位置计算问题,统一控制滑动目标。
- 隐藏RadioButton的默认指示器并清空文本,严格实现“仅图片无文字”的需求。
- 使用RadioGroup确保三个按钮互斥选中,点击任意按钮时通过统一函数获取选中按钮的x坐标,驱动指示器滑动。
- 调整指示器z值为-1,使其位于按钮图片下方,符合“指示器滑动到点击位置”的视觉效果。
- 初始化时设置指示器默认位置为第一个按钮的x坐标,保证初始状态正确。
内容的提问来源于stack exchange,提问作者user2246120
相关产品推荐
相关产品推荐

