Can't access QML item by id inside SplitView

I've began learning QML and I'm getting the following error:

ReferenceError: chatTextArea is not defined

I have a global function that does something on an item within the same QML file, by id.

For some reason I can't access via the ID of my TextArea, or any item inside of the SplitView. But I am able to manipulate the properties of TabView and each Tab.

My broken code:

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
                }
            }
        }
    }
}
}

Any idea why chatTextArea is out of scope of my function? Thanks in advance.


Change the starting portion of your code to smth like this:

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

Reason this works, is that Tab turns out to behave like a Loader (per the docs), loading whichever Component you give it; thus, the SplitView in your code is a Component specification, and that component is instantiated by the Tab in a separate QML context (parented to that of the document root item). Which is why everything inside that context can see things up the scope chain (like the appendMessage() function), but not the reverse :)

链接地址: http://www.djcxy.com/p/22618.html

上一篇: PHP脚本写入本地主机上的文件,但不写入IIS服务器

下一篇: 无法通过SplitView中的id访问QML项目