如何在连接函数QML中的Repeater中索引数组

问题描述 投票:0回答:1
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 从字符串“0”和“1”创建一个数组,它看起来像这样: Application screenshot

我想做的是更改某个矩形的颜色,访问连接到 C++ 信号的 Connections 函数中给定索引处的某个矩形。

函数中的代码不起作用(它说“位”未定义),但说明了我想要实现的目标。如何才能实现这一目标?

c++ qt qml
1个回答
0
投票

在 MVVM 模式中,将数据/模型需求与视觉需求分开:

  • 型号:汉明码是一个数字。
  • 视图模型:将汉明码转换为字符串‘0’或‘1’的数组。
  • 视图:将数组绘制为“0”为黑色,“1”为“红色”。

以下是对上述内容的解释:

import QtQuick
import QtQuick.Controls
Page {
    property int hammingCode: 127
    ListView {
        anchors.centerIn: parent
        width: 50 * 7
        height: 50
        orientation: ListView.Horizontal
        model: 7
        delegate: Rectangle {
            property int bitMask: 64 >> index
            property bool bitSet: (hammingCode & bitMask) != 0
            property color bitColor: bitSet ? "red" : "black"
            width: 50
            height: 50
            border.color: bitColor
            Text {
                anchors.centerIn: parent
                text: bitSet ? "1" : "0"
                color: bitColor
            }
            MouseArea {
                anchors.fill: parent
                onClicked: hammingCode ^= bitMask;
            }
        }
    }
}

既然您提到了 C++,我只需将整数 hammingCode 从 QML 移动到 C++ 并将其公开为 Q_PROPERTY。这样,如果 C++ 端想要设置它,那很好,QML 将通过更改信号收到通知,并且上述情况仍然会发生。

© www.soinside.com 2019 - 2024. All rights reserved.