Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt 通过函数将属性绑定到委托索引时出现意外循环_Qt_Qml - Fatal编程技术网

Qt 通过函数将属性绑定到委托索引时出现意外循环

Qt 通过函数将属性绑定到委托索引时出现意外循环,qt,qml,Qt,Qml,我需要在ListView中对前面元素的值求和。有人能给我解释一下输出吗?为什么该方法会从同一个ListView元素执行三次?为什么一次又一次地从头开始 import QtQuick 2.15 import QtQuick.Window 2.15 Window { width: 640 height: 480 visible: true title: qsTr("Hello World") ListModel { id: fruitModel ListElem

我需要在ListView中对前面元素的值求和。有人能给我解释一下输出吗?为什么该方法会从同一个ListView元素执行三次?为什么一次又一次地从头开始

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
ListModel {
    id: fruitModel
    ListElement {name: "Apple";cost: 2}
    ListElement {name: "Orange";cost: 3}
    ListElement {name: "Banana";cost: 4}
}
ListView{
    anchors.fill:parent
    id:listView
    model:fruitModel
    delegate: Item{
        property var myData: model
        width:50
        height:50
        Text{
            text: sum_up(index)
            Component.onCompleted: console.debug("onCompl: "+index)
        }
        function sum_up(foo_index)
        {
            console.debug(foo_index)
            var sum=0;
            for (var i = 0; i <= foo_index; i++)
            {
                sum+=listView.contentItem.children[i].myData.cost
            }
            return sum
}}}}
预期输出:

0
onCompl: 0
0
0
1
onCompl: 1
qrc:/main.qml:33: TypeError: Cannot read property 'cost' of undefined 
0
1
2
onCompl: 2
qrc:/main.qml:33: TypeError: Cannot read property 'cost' of undefined
qrc:/main.qml:33: TypeError: Cannot read property 'cost' of undefined
0
onCompl: 0
1
onCompl: 1
2
onCompl: 2

发生的是您的
总结
函数正在引用
listView.contentItem.children
。这一行:

    text: sum_up(index)
在文本字段和整个代理列表之间创建绑定。因此,当ListView构造其子项时,该绑定将继续被通知。通过删除对
子项的引用,可以看出这是正确的:

    function sum_up(foo_index)
    {
        console.debug(foo_index)
    }
输出:

qml: 0
qml: onCompl: 0
qml: 1
qml: onCompl: 1
qml: 2
qml: onCompl: 2

我将文本绑定移动到delegate onCompleted中。这个很好用。还有一件事。contentItem中有4项。第四个是什么?添加到contentItem的内容取决于ListView实现。它可以是滚动条,也可以是突出显示项。