我开始学习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
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
知道为什么chatTextArea超出了我的功能范围吗?提前致谢.
将代码的起始部分更改为如下所示:
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
Run Code Online (Sandbox Code Playgroud)
它起作用的原因是,它的Tab行为就像一个加载器(根据文档),加载您给它的任何组件;因此,SplitView代码中的 是一个组件规范,并且该组件由Tab单独的 QML 上下文中的 实例化(父级为文档根项的上下文)。这就是为什么该上下文中的所有内容都可以看到作用域链上的内容(如函数appendMessage()),但反之则不然:)