Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How dynamically creates Popup in QML

Tags:

qt

qt5

qml

qtquick2

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
}
like image 540
A.J Avatar asked Jan 05 '23 06:01

A.J


2 Answers

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()
like image 140
Andrei R. Avatar answered Jan 06 '23 20:01

Andrei R.


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

like image 23
eyllanesc Avatar answered Jan 06 '23 19:01

eyllanesc