【问题标题】:Can't reference stuff in ListView's highlight无法引用 ListView 的突出显示中的内容
【发布时间】:2018-08-30 09:12:30
【问题描述】:

正如标题所说,我遇到了一个问题,我有一个 ListView,通常是 delegatehighlight

在我的突出显示中,我放置了一个带有idText 组件,以便我可以引用它。

所以行为应该是这样的,我在ListView 的项目中移动,当我在键盘上按下一个数字时,highlight 内的文本应该显示它。

但任何时候我尝试对上述Text 组件做任何事情(通过id 引用它,比如textComponent.text = "123" 我得到一个ReferenceError: textComponent is not defined

我浏览了文档,但没有找到任何与无法通过 id 突出显示内容有关的内容。

是否有人知道这可能是什么原因,或者根本不支持这种行为?

我没有包含任何代码,因为这个问题很容易解释和重现,但是如果有人需要它,我很乐意包含这个东西的简短 sn-p。

编辑 代码

  ListView
    {
        height: 500
        width: 500

        model: ListModel { id: channelListModel }

        highlightMoveDuration: 200
        highlightRangeMode: ListView.ApplyRange
        snapMode: ListView.SnapToItem

        preferredHighlightBegin: height * 0.2
        preferredHighlightEnd: height * 0.8

        delegate: Item
        {
            id: channelItem
            width: ListView.view.width * 0.96
            height: parent.height

            Text
                {
                    anchors.fill: parent
                    text: "generic row text"
                }
        }

        Keys.onPressed:
        {
            switch(event.key)
            {
                case Qt.Key_0:
                case Qt.Key_1:
                case Qt.Key_2:
                case Qt.Key_3:
                case Qt.Key_4:
                case Qt.Key_5:
                case Qt.Key_6:
                case Qt.Key_7:
                case Qt.Key_8:
                case Qt.Key_9:
                    textComponent.text = event.key
             }
         }

        highlight: Rectangle
        {
            id: highlight
            color: "#40ffffff"

            Text
                {
                    id: textComponent
                    anchors.fill: parent
                }
         }

【问题讨论】:

  • 你有一些代码示例吗?

标签: listview reference qml


【解决方案1】:

如果您查看ListView 的文档,您会发现type of the property highlightComponent

Component 总是为ids 创建一个新的上下文,就像它在另一个文件中一样。 这意味着,您无法从外部访问Component 内的ids。该组件可能已被实例化多次或根本没有实例化 - 所以id 不会是唯一的。

你能做什么?

ListView 中创建一个property 并从组件中读取它。

ListView {
    id: myListView
    ...
    property string hightlightText

    highlight: SomeItem { // Will be automatically transformed in a Component and initaly not fully created
        Text {
            text: myListView.highlightText // You can reference ids of the 'outside world'
        }
    }
}

【讨论】:

  • 啊,我明白了。我在这里以Text 为例,实际上我有一个必须从外部调用的函数的组件,所以我在ListView 中放置了一个signal 并使用keyPress 触发它,然后使用了Connections 从亮点收听。但是您的评论完美地说明了这个问题,所以谢谢!
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 2013-06-22
  • 2016-05-25
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
相关资源
最近更新 更多