如何在 QML 中动态创建 Popup

A.J*_*A.J 6 qt qml qt5 qtquick2

当我尝试使用Qt.createQmlObject(...)Qt.createComponent(...)动态创建 Popup 时,出现异常:

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()
Run Code Online (Sandbox Code Playgroud)

测试弹出.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
}
Run Code Online (Sandbox Code Playgroud)

And*_* R. 7

Popup不继承QQuickItem,默认情况下它的父级是QML Window,如果您使用 ,则不会实例化QQuickWidget。因此通过parent应该如下完成:

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


eyl*_*esc 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()
            }

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

方法一:

在此输入图像描述

方法2:

在此输入图像描述