QML弹窗
目标:QML实现弹窗实现点击按钮弹窗,点击不同的按钮 弹窗的内容会改变,但窗口不消失。点击窗口外部则窗口消失。
效果:
代码:
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
width: 400
height: 300
visible: true
// 弹窗控制器
property string currentContent: ""
// 主界面按钮
Row {
spacing: 10
Button {
text: "显示内容A"
onClicked: {
currentContent = "A"
popup.open()
}
}
Button {
text: "显示内容B"
onClicked: {
currentContent = "B"
popup.open()
}
}
}
// 弹窗定义
Popup {
id: popup
anchors.centerIn: parent
modal: true
dim: true // 点击外部关闭
closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
// 核心:动态内容加载器
Loader {
id: contentLoader
sourceComponent: {
if (currentContent === "A") return contentA
else if (currentContent === "B") return contentB
else return null
}
}
}
// 定义不同内容组件
Component {
id: contentA
Rectangle {
width: 200
height: 100
color: "lightblue"
Text { text: "这是内容A"; anchors.centerIn: parent }
}
}
Component {
id: contentB
Rectangle {
width: 200
height: 150
color: "lightgreen"
Column {
anchors.centerIn: parent
Text { text: "这是内容B" }
Button { text: "子按钮"; onClicked: console.log("点击B的子按钮") }
}
}
}
}