我是QML的新手,在学习按钮教程时遇到了示波器问题。我解决了它,但我不明白为什么代码最初不起作用:
当按钮悬停在上方时,以下代码给出了运行时参考错误:
main_broken.qml
import QtQuick 2.0
import QtQuick.Controls 1.1
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Button Tester")
Rectangle {
id: simpleButton
height: 75
width: 150
property color buttonColor: "light blue"
property color onHoverColor: "gold"
property color borderColor: "white"
onButtonClick: {
console.log(buttonLabel.text + " clicked")
}
signal buttonClick()
Text {
id: buttonLabel
anchors.centerIn: parent
text: "button label"
}
MouseArea {
id: buttonMouseArea
anchors.fill: parent
onClicked: buttonClick()
hoverEnabled: true
onEntered: parent.border.color = onHoverColor
onExited: parent.border.color = borderColor
}
color: buttonMouseArea.pressed ? Qt.darker(buttonColor, 1.5) : buttonColor
scale: buttonMouseArea.pressed ? 0.99 : 1
}
}
错误:
qrc:///main.qml:37: ReferenceError: onHoverColor is not defined
qrc:///main.qml:38: ReferenceError: borderColor is not defined
qrc:///main.qml:37: ReferenceError: onHoverColor is not defined
qrc:///main.qml:35: ReferenceError: buttonClick is not defined
通过如下方式解决,只需将属性绑定和信号槽移动到“应用程序”窗口对象中:
main_fixed.qml
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Button Tester")
property color buttonColor: "light blue"
property color onHoverColor: "gold"
property color borderColor: "white"
onButtonClick: {
console.log(buttonLabel.text + " clicked")
}
signal buttonClick()
//etc
为什么无法将属性绑定保留在ApplicationWindow对象的Rectangle子对象内?
如果您只想拥有矩形专有的属性(例如颜色),但是使用了ApplicationWindow的某些属性(例如文本大小)怎么办?
我是编码和堆栈溢出的新手(这是我的第一篇文章)。我试图以最清晰的方式提出问题,但是请让我知道它是否不符合堆栈溢出的标准,以及我必须做些什么来更改它。
QML中的范围很容易,也许很奇怪,但很容易:
[使用标识符时,请说foo
在var绑定中,QML引擎按此顺序搜索:
foo
作为其ID的[[对象foo
当前对象中的[[a foo
ReferenceError
。foo
并且具有名为bar
的属性,则可以在需要的任何地方引用foo.bar
。 t在文件中。 希望有帮助。