无法在SplitView中按ID访问QML项目

时间:2014-09-04 01:44:00

标签: qt qml

我开始学习QML,我收到以下错误:

  

ReferenceError:未定义chatTextArea

我有一个全局函数,它通过id在同一个QML文件中对某个项执行某些操作。

由于某种原因,我无法通过TextArea的ID或SplitView中的任何项目进行访问。但我能够操纵TabView和每个Tab的属性。

我的破码:

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

Rectangle {
id: lobby

function appendChatMsg(msg) {
    chatTextArea.append(msg) //causes: ReferenceError: chatTextArea is not defined
}

TabView {
    id: frame

    Tab { //I CAN access this item via ID.
        id: controlPage

        SplitView {
            anchors.fill: parent

            TableView {
                Layout.fillWidth: true
            }

            GridLayout {
                columns: 1

                TextArea { //This item I CANNOT access via ID.
                    id: chatTextArea

                    Layout.fillHeight: true
                    Layout.fillWidth: true
                }

                TextField {
                    placeholderText: "Type something..."
                    Layout.fillWidth: true
                }
            }
        }
    }
}
}

知道为什么chatTextArea超出了我的功能范围吗?提前谢谢。

1 个答案:

答案 0 :(得分:3)

将代码的起始部分更改为smth,如下所示:

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

Rectangle {
id: lobby

function appendChatMsg(msg) {
    controlPage.chatArea.append(msg) //causes: ReferenceError: chatTextArea is not defined
}

TabView {
    id: frame

    Tab { //I CAN access this item via ID.
        id: controlPage
        property Item chatArea: item.chatArea

        SplitView {
            property Item chatArea: chatTextArea

这有效的原因是,Tab的行为类似于Loader(根据文档),加载您提供的组件;因此,代码中的SplitView是一个组件规范,该组件由Tab在单独的QML上下文中实例化(以文档根项的为主)。这就是为什么上下文中的所有东西都可以看到范围链上的东西(比如appendMessage()函数),而不是相反的情况:)

相关问题