0
点赞
收藏
分享

微信扫一扫

qml parent属性用法,实现多个页面公用一个控件

老王420 2022-01-15 阅读 84
c++qt5qml

最近的项目中遇到了一个问题,在低配的工控机上面析构带有Surface3D的qml界面,出现了异常退出的情况。我使用了“野路子”来解决这个问题。
        我们的项目有多个模块,每个模块都是一个单独的qml文件,一些模块含有Surface3D,当模块切换时,会将stackView的当前页面析构,之后push新的qml文件。虽然有着多个界面,但是Surface3D控件有一个共同点:显示方式等完全一致。所以我在main.qml文件里定义了Surface3D控件,通过灵活的改变其parent属性,使其正确的显示。示例代码如下所示:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtDataVisualization 1.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    property int currentIndex: 0

    Component.onCompleted:  changeIndex(currentIndex)
    onCurrentIndexChanged: changeIndex(currentIndex)

    Column {
        x: 10; y: 10
        spacing: 10

        Button {
            width: 80; height: 30
            text: "Page 0"
            onClicked: currentIndex = 0
        }

        Button {
            width: 80; height: 30
            text: "Page 1"
            onClicked: currentIndex = 1
        }
    }

    StackView {
        id:_stackView
        anchors.fill: parent
        anchors.leftMargin: 100
    }

    // qml的单例
    Surface3D {
        id: singletonComponennt
        visible: false
        Component.onDestruction: console.log("Surface3D Component.onDestruction")
    }

    function changeIndex(index) {
        _stackView.pop(StackView.Immediate)
        _stackView.push(index === 0 ? "qrc:/page1.qml" : "qrc:/page2.qml",           
                                                        StackView.Immediate)
        _stackView.currentItem.width = _stackView.width
        _stackView.currentItem.height = _stackView.height
    }
// page1
import QtQuick 2.0

Rectangle {
    id: mainPage
    color: "blue"

    Component.onCompleted: {
        singletonComponennt.x = 10
        singletonComponennt.y = 10
        singletonComponennt.width = width - 20
        singletonComponennt.height = height - 20
        singletonComponennt.parent = mainPage
        singletonComponennt.visible = true
    }

    Component.onDestruction: {
        singletonComponennt.visible = false
        singletonComponennt.parent = null
    }
}

// page2
import QtQuick 2.0

Rectangle {
    id: mainPage
    color: "yellow"

    Component.onCompleted: {
        singletonComponennt.x = 10
        singletonComponennt.y = 10
        singletonComponennt.width = width - 20
        singletonComponennt.height = height - 20
        singletonComponennt.parent = mainPage
        singletonComponennt.visible = true
    }

    Component.onDestruction: {
        singletonComponennt.visible = false
        singletonComponennt.parent = null
    }
}

有关quickItem的parent属性,请在Qt的帮助文档中查阅。

       界面显示如下所示:

 

举报

相关推荐

0 条评论