Import 从导入的JS访问导入的QML组件ID
我试图通过包含的JavaScript函数访问包含的QML id。我得到了一个错误:Import 从导入的JS访问导入的QML组件ID,import,qml,scope,Import,Qml,Scope,我试图通过包含的JavaScript函数访问包含的QML id。我得到了一个错误: Reference error: textItem is not defined. main.qml import QtQuick 2.1 import "functions.js" as Logic Rectangle { anchors.fill: parent; Button { } MouseArea { onClicked: Logic.changeText(
Reference error: textItem is not defined.
main.qml
import QtQuick 2.1
import "functions.js" as Logic
Rectangle {
anchors.fill: parent;
Button { }
MouseArea {
onClicked: Logic.changeText()
}
}
Button.qml
import QtQuick 2.1
Rectangle {
width: 100; height: 30
color: "black"
Text {
id: textItem
anchors.centerIn: parent
font.pointSize: 20
color: "white"
text: "Hello!"
}
}
functions.js
function changeText() {
textItem.text = "Goodbye!";
}
有没有办法从导入的JS文件访问导入的QML的id作用域?正如folibis所说,
textItem
无法访问functions.JS
。不过,您的代码还有更多问题。要更改其文本的按钮没有ID,因此即使要更改,也无法更改其文本
给按钮一个ID,然后将按钮传递到changeText()
:
下一个问题是,按钮
类型不公开文本属性。您应该为textItem
的text属性设置别名:
import QtQuick 2.1
Rectangle {
width: 100; height: 30
color: "black"
property alias text: textItem.text
Text {
id: textItem
anchors.centerIn: parent
font.pointSize: 20
color: "white"
text: "Hello!"
}
}
那么剩下的就行了:
function changeText(button) {
button.text = "Goodbye!";
}
为了引用其他文件(或QML文件内部)中的内容,您需要考虑QML树(使用id属性浏览树)。话虽如此,我建议进行以下修改: 在Button.qml中: 在“function.js”中,您可以这样引用它: 函数更改文本(buttonId){ buttonId.text=“再见!”;}
当然,由于作用域可见,textItem不可见。将项目id传递给JS函数或类似的东西
function changeText(button) {
button.text = "Goodbye!";
}
import QtQuick 2.1
import "functions.js" as Logic
Rectangle {
id: rootRec
anchors.fill: parent;
Button {id: myButton}
MouseArea {
onClicked: Logic.changeText(myButton)
}
}
import QtQuick 2.1
Rectangle {
id: rootRec
width: 100; height: 30
color: "black"
property string text: "Hello"
Text {
id: textItem
anchors.centerIn: parent
font.pointSize: 20
color: "white"
text: rootRec.text
}
}