如何在QML中动态创建弹出窗口

6
当我尝试使用 Qt.createQmlObject(...)Qt.createComponent(...) 动态创建弹出窗口时,我遇到了异常:

QML 弹出窗口:找不到任何可以打开弹出窗口的窗口。

这是我的代码:

var popup1 = Qt.createQmlObject('import QtQuick 2.8; import QtQuick.Controls 2.1; Popup { id: popup; x: 100; y: 100; width: 200; height: 300; modal: true; focus: true; closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutsideParent; visible: false }',
                                window,
                                "DynamicPopup");
popup1.open()

var popupComponent = Qt.createComponent("qrc:/TestPopup.qml")
var popup2 = popupComponent.createObject(window);
popup2.open()

TestPopup.qml:

import QtQuick.Window 2.2
import QtQuick.Controls 2.1

Popup {
    x: 100
    y: 100
    width: 200
    height: 300
    modal: true
    focus: true
    closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutsideParent
    visible: false
}
4个回答

6

弹出窗口并没有继承QQuickItem,默认的它是由QML窗口作为父级实例化的,而如果您使用QQuickWidget则不会实例化。因此传递parent应该按照以下方式进行:

var popupComponent = Qt.createComponent("qrc:/TestPopup.qml")
var popup2 = popupComponent.createObject(window, {"parent" : window});
popup2.open()

1
@A.J,你的示例中的“window”是什么?试着将“Popup”绑定到“QQuickItem”。 - Andrei R.
好的,我的窗口是一个ApplicationWindow。非常感谢。 - A.J
这个解决方案对我有效,但似乎不需要 <code>{"parent": window}</code>。当我指定它时,会出现错误“Error: Cannot assign QObject* to QQuickItem*”,当我删除第二个参数时,错误就消失了。我的Qt版本是6.3.1。 - MartinZ

5

父元素必须是从 QQuickItem 继承而来的元素。

示例:

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.1

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

    Row{
        Button{
            id: item1
            text: "btn1"
            onClicked: {
                var popup1 = Qt.createQmlObject('import QtQuick 2.8; import QtQuick.Controls 2.1; Popup { id: popup; x: 100; y: 100; width: 200; height: 300; modal: true; focus: true; closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutsideParent; visible: false }',
                                                item1,
                                                "DynamicPopup");
                popup1.open()

            }
        }

        Button{
            id: item2
            text: "btn2"
            onClicked: {
                var popupComponent = Qt.createComponent("qrc:/TestPopup.qml")
                var popup2 = popupComponent.createObject(item2);
                popup2.open()
            }

        }

    }
}

方法1:

这里输入图片描述

方法2:

这里输入图片描述


2
一个Popup需要被父级控件是一个Itemwindow不是一个。 你应该使用window.contentItem代替。

1
一种良好的动态加载弹出窗口的方法是使用 Loader:
Loader {
    id: popupLoader

    active: false
    source: "qrc:/TestPopup.qml"
    onLoaded: item.open()
}

function openMyPopup() {
    if( popupLoader.active )
        popupLoader.item.open()
    else
        popupLoader.active = true
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接