QML中如何在Connections函数里索引Repeater生成的数组元素
问题
我有一个Page组件,通过Repeater从由'0'和'1'组成的字符串生成一组矩形。希望在与C++信号关联的Connections函数中,根据给定索引修改对应矩形的颜色,但当前代码中直接使用bit[index]会提示“bit未定义”,请问该如何实现?
原代码如下:
import QtQuick import QtQuick.Controls 2.15 import QtQuick.Layouts 6.3 Page { width: root.width height: root.height visible: true background: Rectangle { color: "white" } Text{ id: stageText anchors.horizontalCenter: parent.horizontalCenter topPadding: root.height / 4 font.pixelSize: 26 text: "" color: "black" } ColumnLayout { width: parent.width height: parent.height scale: root.width / 1000.0 RowLayout{ Layout.alignment: Qt.AlignCenter spacing: 0 id: visualizeRow property string myArr : hammingCode.getDataStr(); Repeater { model: visualizeRow.myArr.length Rectangle { id: bit width: 50 height: 50 Text { anchors.centerIn: parent text: visualizeRow.myArr.charAt(index) color: "black" } border.width: 1 color: "white" } } Component.onCompleted: { stageText.text = "Encoding"; hammingCode.encodeData(true); } } } Connections{ target: hammingCode function onTurnBitOff(index){ bit[index].color = "black"; } function onTurnBitOn(index){ bit[index].color = "red"; } //put signals from c++ here that change visual stuff and shit } }
解决方案
问题核心是:Repeater内部定义的bit是每个重复项的局部id,外部无法通过bit[index]这种数组形式直接访问。以下是两种可行的实现方式:
方法一:利用Repeater的itemAt()方法
给Repeater添加全局可访问的id,通过itemAt(index)方法直接获取对应索引的矩形项:
修改后的关键代码片段:
RowLayout{ // 保留原有代码... Repeater { id: bitRepeater // 给Repeater添加全局id model: visualizeRow.myArr.length Rectangle { id: bit // 矩形原有属性不变 } } } Connections{ target: hammingCode function onTurnBitOff(index){ const targetBit = bitRepeater.itemAt(index); if(targetBit) targetBit.color = "black"; // 加判断避免索引越界报错 } function onTurnBitOn(index){ const targetBit = bitRepeater.itemAt(index); if(targetBit) targetBit.color = "red"; } }
方法二:通过数据模型绑定颜色(更符合Qt Quick设计思路)
如果可以调整C++端的数据结构,可给每个位数据添加高亮状态属性,让UI自动绑定刷新:
// 假设C++端返回包含bitValue和isHighlighted的列表模型 RowLayout{ // 保留原有代码... Repeater { model: hammingCode.bitModel // 替换为带状态的模型 Rectangle { color: model.isHighlighted ? "red" : "white" width: 50 height: 50 Text { anchors.centerIn: parent text: model.bitValue color: "black" } border.width: 1 } } }
这种方式下,C++端只需更新模型中对应项的isHighlighted属性,UI会自动同步颜色变化,无需手动操作控件。
内容的提问来源于stack exchange,提问作者Michael21
相关产品推荐
相关产品推荐

