【问题标题】:Why can't ListView delegate refer to properties of ListView?为什么 ListView 委托不能引用 ListView 的属性?
【发布时间】:2019-03-07 05:58:35
【问题描述】:

如果 ListView 包含用户定义的属性,则可以在 model 的绑定中引用这些属性,但它们不能用于委托内的任何内容。这是为什么呢?

The docs 似乎在说组件应该能够在声明它的封闭范围内看到属性。

import QtQuick 2.12
import QtQuick.Controls 2.12

ApplicationWindow {
    visible:true

    ListView {
        orientation: ListView.Vertical; height: 300; width: 100

        property var myCount: 3
        property var myMessage: "Hello"

        Component {
          id: myComp
          Text {text: myMessage} // ReferenceError: myMessage is not defined
        }
        model: myCount // this works
        delegate: myComp
    }       
}

(在我的实际应用程序中,ListView 是一个组件(.qml 文件),调用者需要传入配置委托所需的信息;不是 像本例中一样的文字文本,但用于嵌套 ListView 的信息。)

感谢您的帮助...

【问题讨论】:

    标签: qt listview properties qml


    【解决方案1】:

    QML 中的变量有一个范围,在你的情况下,当使用 myMessage 而不引用这些表示变量属于 Text 项时。

    # ...
    Component {
        id: myComp
        Text {text: myMessage} 
    }
    # ...
    

    所以解决方法是使用ListView id作为参考:

    # ...
    ListView {
        id: lv
        orientation: ListView.Vertical; height: 300; width: 100
        property var myCount: 3
        property var myMessage: "Hello"
        Component {
          id: myComp
          Text {text: lv.myMessage} 
        }
        model: myCount // this works
        delegate: myComp
    }
    # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-25
      • 2022-01-16
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多