【问题标题】:How to access the function of a Repeater's children in QML?如何在 QML 中访问中继器子代的功能?
【发布时间】:2021-02-16 14:25:31
【问题描述】:

我正在寻找访问 qml 中中继器元素内的函数。 无论我尝试直接调用该函数还是在 rect1 和 rect2 之间连接信号,它似乎都不起作用。我错过了什么或有其他方法可以做到这一点?

下面的代码是我正在使用的简化版本。

Rectangle {
    signal save
    id : rect1
    onSave : {
        rect2.saveState()
    }
    Repeater {
        id: repeat1
        model: length
        delegate:
            Row {
            id: row1

            Rectangle {
                id: rect2

                function saveState()
                {
                    rect2.grabToImage(function(result) {result.saveToFile(filepath);});
                }
            }
        }
    }
}

【问题讨论】:

  • 因为您使用的是Repeater,所以您可以看看它,就像有一个未知数量的rect2,您想使用哪个?
  • 我明白了。假设我想使用第一个,我该怎么做?
  • 使用Repeater 可以获得count 的属性和itemAt(index) doc.qt.io/qt-5/qml-qtquick-repeater.html#itemAt-method 的方法@ 请注意重复项的创建和对它的访问。如果 Repeater 尚未完成创建项目,itemAt() 将返回 null。为此使用Component.onCompleted

标签: qt qml signals repeater


【解决方案1】:

由于您在中继器中使用该函数,您将拥有该函数的多个副本,您仍然可以使用该矩形的子级来调用该函数。请看下面的代码

 Rectangle {
    signal save
    id : rect1
    onSave : {
        rect1.children[1].saveState()
        rect1.children[2].saveState()
        rect1.children[3].saveState()
        rect1.children[4].saveState()
        rect1.children[5].saveState()
        rect1.children[6].saveState()
    }
    Repeater {
        id: repeat1
        model: 6
        delegate:
            Row {
            id: row1
            property var saveState: rect2.saveState
            Rectangle {
                id: rect2
                
                function saveState()
                {
                    console.log("index",index)
                    rect2.grabToImage(function(result) {result.saveToFile(filepath);});
                }
            }
        }
    }
}

Rectangle {
    anchors.fill: parent
    color: "#55550000"
    MouseArea{
        anchors.fill: parent
        onClicked: rect1.save()
    }
    
}

【讨论】:

    【解决方案2】:

    您可以使用Repeater 类的方法itemAt(index) 来访问特定的矩形。比如你想调用第一个 Rectangle 函数。

    Component.onCompleted : {
            repeat1.itemAt(0).saveState()
        }
    

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2023-04-02
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多