【问题标题】:Adding business logic on components in the ui.qml files在 ui.qml 文件中的组件上添加业务逻辑
【发布时间】:2017-07-17 11:30:31
【问题描述】:

我有一个 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 事件。

【问题讨论】:

    标签: qt qml qt-quick qtquick-designer


    【解决方案1】:

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

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

    这是通过这一行完成的:

    property alias button: button
    

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


    来自文档:

    属性别名将按钮导出到使用表单的 QML 代码。 您可以使用导航器中的(导出)按钮将项目导出为属性
    (来源: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()
    }
    

    【讨论】:

    • 感谢您的回答。请看我的编辑。我不确定我错过了什么。问题是我正在尝试的事件是在 Image 对象的 MouseArea 上。
    • 我认为在你的编辑中,你把它搞砸了。您可以/应该在表单中添加MouseArea。您将其作为属性导出到表单中。当您实例化/使用表单时,您可以通过之前创建的属性访问MouseArea 来处理信号。
    • 好的,我知道了。问题是导出必须在顶层完成,所以不是在Image 组件内部,而是在它外部。感谢您的帮助!
    • 是的,您可以/应该始终只访问组件根节点的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多