qt - QML中如何动态创建Popup

标签 qt qml qt5 qtquick2

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

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



这是我的代码:
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
}

最佳答案

父元素必须是从 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()
            }

        }

    }
}

方法一:

enter image description here

方法二:

enter image description here

关于qt - QML中如何动态创建Popup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43038248/

相关文章:

c++ - 如何从 qml 启动一个 Qthread?

c++ Qt/Win32 - USB 以编程方式弹出,但仍显示在 QFileSystemModel 和 GetLogicalDrives() 中

c++ - Qt5:一次性连接到 lambda

c++ - QFileInfo::isExecutable() 为 ".exe"文件返回 false

Qt 多媒体 : cannot find -lpulse

c++ - 函数void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha)有什么用?

python - 如何将 PyQt5 QtWidgets.QTabWidget() 正确添加到子类 QWidget

c++ - 如何在 Qt 中设计异步包装器返回值?

c++ - 具有多个父项目的 Qt 树模型

qml - 我可以使用Qt quick UI 项目来开发一个真正的产品吗?