gpt4 book ai didi

qt - QML中如何动态创建Popup

转载 作者:行者123 更新时间:2023-12-04 12:59:46 28 4
gpt4 key购买 nike

当我尝试使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com