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:
method 2:
Solution 3
A Popup
needs to be be parented to an Item
, window
isn't one.
You should use window.contentItem
instead.
Author by
A.J
Updated on July 31, 2022Comments
-
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 }