关于QML中是否存在ListModel属性的问题

问题描述 投票:0回答:1

在实际开发中,我定义了一个ListModel,其中每个元素都有不同的属性。有些元素没有 power 属性,有些元素没有wavelength 属性,有些元素没有 moduleId 属性。我想使用全局模型。获取(当前索引)。 property===undefined 判断某个属性是否存在,但是全部失败。以下是我发现的问题: 当ListElement的属性不存在时,无法与undefined进行比较

  1. 如果该属性存在于其他ListElements中并且是数字类型,则默认为0而不是undefined
  2. 如果这个属性存在于其他ListElements中并且是字符串类型,那么它是未定义的
import QtQuick.Window 2.12
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    ListModel {
        id: globalModel
        ListElement { moduleId: "module1"; power: 30; wavelength: 650 }
        ListElement { moduleId: "module2"; power: 50; wavelength: 700 }

        ListElement { moduleId: "module3"; wavelength: 500 }
        ListElement { moduleId: "module4"; power: 80 }
        ListElement { moduleId: "module5"; power: 80 }
        ListElement { moduleId: "module6" }
        ListElement { }
    }

    ComboBox {
        id: comboBox
        model: globalModel
        currentIndex: 0
        textRole: "moduleId" 
        onCurrentIndexChanged: {
            // No matter how I switch, the output is always false
            console.log(globalModel.get(currentIndex).power === undefined, globalModel.get(currentIndex).wavelength === undefined)
            
            //When I switched to the last one, it output undefined 0 0, which means the last ListElement's moduleId field is undefined! But the power and wavelength attributes are 0, so logically they should also be undefined!         
            var currentItem=globalModel.get(currentIndex)
            console.log(currentItem.moduleId,currentItem.power,currentItem.wavelength)
        }
    }
}
qt qml
1个回答
0
投票

模型中所有元素的角色名称应该相同。来自

ListElement
的文档:

角色使用的名称必须以小写字母开头,并且 给定模型中的所有元素应该是通用的。

作为解决方案,您可以为不适用于元素的角色定义特殊值(例如-1):

ListElement { moduleId: "module1"; power: -1; wavelength: 650 }
ListElement { moduleId: "module2"; power: 50; wavelength: -1 }

您可以检查该值:

console.log(globalModel.get(currentIndex).power === -1, globalModel.get(currentIndex).wavelength === -1)
© www.soinside.com 2019 - 2024. All rights reserved.