【问题标题】:QML Dynamically created object lifetimeQML 动态创建的对象生命周期
【发布时间】:2014-12-22 21:43:33
【问题描述】:

当我遇到一些奇怪的行为时,我正在测试自定义弹出菜单策略:删除我动态创建的弹出窗口的请求被忽略。

Window {
    id: window
    width: 400
    height: 400
    color: "red"

    Rectangle {
        id: base
        width: 100
        height: 100
        anchors.centerIn: parent
        color: "green"

        property Window parentWindow: window
        property Window popup: null

        MouseArea {
            anchors.fill: parent
            onClicked: {
                base.popup = popupComp.createObject( null, { "parentWindow": base.parentWindow } );
            }
        }

        Connections {
            target: base.parentWindow
            onClosing: {
                if ( base.popup !== null ) {
                    base.popup.hide();
                    base.popup.destroy(); // 2
                }
            }
        }

        Component {
            id: popupComp

            Window {
                width: 150
                height: 150
                x: parentWindow.x + base.mapToItem( null, 0, 0 ).x
                y: parentWindow.y + base.mapToItem( null, 0, base.height ).y

                flags: Qt.Popup
                color: "blue"
                visible: true

                property Window parentWindow: null

                Component.onCompleted: requestActivate()

                Component.onDestruction: {
                    console.log( "Destroying popup" );
                }

                onActiveChanged: {
                    if ( !active ) {
                        console.log( "Popup inactive" );
                        hide();
                        base.popup = null;
                        destroy(); // 1
                    }
                }
            }
        }
    }
}

我必须动态创建弹出窗口,因为它是指定无父窗口的唯一方法,因为子窗口(即父窗口)QWindow::active 的状态似乎取决于它的父窗口。

一旦弹出窗口关闭,弹出窗口的 destroy() 插槽就会通过 onActiveChanged 处理程序调用 - 但在父窗口的 closing() 信号发出之前,对象不会被销毁。这是两次打开和关闭弹出窗口的调试输出:

qml: Popup inactive
qml: Popup inactive
// Closing the parent window now
qml: Destroying popup
qml: Destroying popup

知道为什么1destroy() 调用在2 被授予时会被忽略吗?

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    我会说这与尚未准备好处理呼叫有关。

    按照这种猜测,enforcing a delay before the destruction occurs 似乎是一个不错的解决方法:

    thisWindow.destroy(1);
    

    【讨论】:

    • 是的,就是这样,只需将其设置为 1 毫秒就足够了。
    猜你喜欢
    • 2013-04-06
    • 2016-07-31
    • 1970-01-01
    • 2017-12-10
    • 2021-06-14
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多