BlueRoseNote/07-Other/Qt/QtQuick/QtQuick中QML文件间的通讯问题.md
2023-06-29 11:55:02 +08:00

121 lines
2.4 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 前言
本人发现有关QML文件之间的通讯的资料不多而且都不太好找所以在这里总结一下方便后续的开发者
## 直接导入qml
目录结构:
```
myapp
|- mycomponents
|- CheckBox.qml
|- DialogBox.qml
|- Slider.qml
|- main
|- application.qml
```
那么可以:
```
import "../mycomponents"
DialogBox {
CheckBox {
// ...
}
Slider {
// ...
}
}
```
但是创建一个命名空间来导入会更好
```
import "../mycomponents" as MyComponents
MyComponents.DialogBox {
// ...
}
```
## qml文件间通讯
3.题回正传直接上代码以StackView管理页面为例
(1)page1.qml跳转到page2.qml传值
```
page1.qml
Rectangle
{
id:rect1
...
MouseArea {
id: maStartQuery
anchors.fill: parent
onClicked:
{
if(!stackView.busy)
stackView.push(Qt.resolvedUrl("qrc:///qml/page2.qml"),
{name:"张三"})//给page2.qml的name传值“张三”,name必须在page2.qml中定义成属性
}
}
...
}
page2.qml定义如下
Rectangle
{
id:rect2
...
property string name:""//要传的值
...
}
```
(2)page2.qml点击"确定"按钮时将结果返回给page1.qml
A.在page1.qml中增加一个函数clickedfunc当点击page2.qml中"确定"按钮时调用;
B.在page2.qml中增加一个属性containerqml用来记录page1.qml
C.在从page1.qml跳转到page2.qml时将rect1传给page2.qml的containerqml属性。
```
page1.qml
Rectangle
{
id:rect1
...
MouseArea {
id: maStartQuery
anchors.fill: parent
onClicked:
{
if(!stackView.busy)
stackView.push(Qt.resolvedUrl("qrc:///qml/page2.qml"),
{name:"张三",containerqml:rect1})
}
}
//当点击page2.qml中"确定"按钮时调用
  function clickedfunc(temp)
{
console.log("改成了:"+temp);
 stackView.pop();//返回到本页
}
...
}
page2.qml
Rectangle
{
id:rect2
...
property variant containerqml: null
property string name:""//要传的值
...
MouseArea {
id: btnOK
anchors.fill: parent
onClicked:
{
containerqml.clickedfunc("李四");//调用page1.qml中的函数实现了传返回值。
}
}
}
```
另一种就是信号与槽