在 ui.qml 文件中的组件上添加业务逻辑

Adding business logic on components in the ui.qml files

我有一个 QML 快速表单,其中有一个图像和一个关联的鼠标区域,如下所示:

// StatusBarForm.ui.qml
Image {
    id: exitButton
    width: 24
    height: 24
    anchors.verticalCenter: parent.verticalCenter
    anchors.left: parent.left
    anchors.leftMargin: 5
    source: "images/exit.png"

    MouseArea {
        id: exitButtonMouseArea
        anchors.fill: parent
    }
}

现在,根据文档,我应该分离业务逻辑,设计师创建了一个 StatusBar.qml 表单,我添加了:

exitButtonMouseArea.onClicked: {
    Qt.quit()
}

现在问题是我在 mac 上用 Qt 5.9 测试了它并且它有效(尽管 Qt 创建者强调了 onClicked 处理程序抱怨 exitButtonMouseArea identifier was not valid。我也试过 exitButton.exitButtonMouseArea.onClicked:

现在我在 Linux 上用 Qt 5.8 试了一下,但应用程序没有初始化。如果我删除事件处理程序,那很好,当然我无法与图像交互。

所以,我的问题是如何在我的案例中提供 UI 文件之外的业务逻辑。

编辑 按照@derM 的回答,我做了以下事情:

// StatusBarForm.ui.qml
Image {
    id: exitButton
    width: 24
    height: 24
    anchors.verticalCenter: parent.verticalCenter
    anchors.left: parent.left
    anchors.leftMargin: 5
    source: "images/exit.png"    
}

// StatusBar.qml
StatusBarForm {
    property alias exitButton: exitButton

    Image {
        id: exitButton
        MouseArea {
            id: exitButtonMouseArea
            anchors.fill: parent
            onClicked: {
                Qt.quit()
            }
        }
    }
}

当我的组件初始化时,我从未收到 onClicked 事件。

问题是,您只能在同一个文件中或在对象树中向上爬 id 来访问对象。

如果你仔细阅读 this,你会发现,他们不是通过 id 访问按钮,而是 将按钮导出为 属性

这是通过这一行完成的:

property alias button: button

导出后,您可以使用 属性 名称从外部访问它。


来自文档:

The property alias exports the button to the QML code that uses the form. You can use the (Export) button in the Navigator to export an item as a property:
(source: doc.qt.io)


在您的代码中,它看起来像这样:

// StatusBarForm.ui.qml

Image {
    id: exitButton
    width: 24
    height: 24
    anchors.verticalCenter: parent.verticalCenter
    anchors.left: parent.left
    anchors.leftMargin: 5
    source: "images/exit.png"

    // export the MouseArea as a property here
    property alias exitButtonMouseArea: exitButtonMouseArea

    MouseArea {
        id: exitButtonMouseArea
        anchors.fill: parent
    }
}

//main.qml

StatusBarExitForm {
    // access the MouseArea via the property here
    exitButtonMouseArea.onClicked: Qt.quit()
}