QML范围:子对象失败的属性绑定

问题描述 投票:3回答:1

我是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的某些属性(例如文本大小)怎么办?


我是编码和堆栈溢出的新手(这是我的第一篇文章)。我试图以最清晰的方式提出问题,但是请让我知道它是否不符合堆栈溢出的标准,以及我必须做些什么来更改它。

scope qt-creator qml property-binding
1个回答
4
投票

QML中的范围很容易,也许很奇怪,但很容易:

[使用标识符时,请说foo在var绑定中,QML引擎按此顺序搜索:

  • [当前文件中以foo作为其ID的[[对象
  • [全局范围中的[[对象(主要QML文件),其ID为foo当前对象中的[[a
  • 属性,称为foo
  • foo的当前组件(当前文件)的根对象中的a
  • 属性
  • )>如果找不到,则会抛出ReferenceError
并且不,直接的父母或子女是
  • 不在范围内。这看似很奇怪,但这就是它的工作方式。
  • 如果需要引用范围外的变量,只需在其前面使用一个ID:如果对象名为foo并且具有名为bar的属性,则可以在需要的任何地方引用foo.bar。 t在文件中。 希望有帮助。
    © www.soinside.com 2019 - 2024. All rights reserved.