How dynamically creates Popup in QML

13,515

Solution 1

Popup is not inheriting QQuickItem, and by default it is parented by QML Window, which is not instantiated if you are using QQuickWidget. Thus passing parent should be done as follows:

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

Solution 2

The parent must be an element that inherits from QQuickItem

Example:

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()
            }

        }

    }
}

method 1:

enter image description here

method 2:

enter image description here

Solution 3

A Popup needs to be be parented to an Item, window isn't one. You should use window.contentItem instead.

Share:
13,515
A.J
Author by

A.J

Updated on July 31, 2022

Comments

  • A.J
    A.J almost 2 years

    When I try to dynamically creates Popup with Qt.createQmlObject(...) or Qt.createComponent(...), I got exception:

    QML Popup: cannot find any window to open popup in.

    Here is my code:

    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
    }