建设电子商务网站目的百度查重
Loader加载器用于动态加载 QML 组件。加载程序可以加载 QML 文件(使用 source 属性)或组件对象(使用 sourceComponent 属性)
常用属性:
active | 活动 |
asynchronous | 异步,默认为false |
item | 项目 |
progress | 进度 |
source | 资源 |
sourceComponent | 资源组件 |
status | 状态 |
status:enumeration
Loader.Null | 加载器处于非活动状态或未设置 QML 源 |
Loader.Ready | QML 源已加载 |
Loader.Loading | 当前正在加载 QML 源 |
Loader.Error | 加载 QML 源时出错 |
信号:
loaded | 当状态为加载或就绪状态时,发射该信号 |
函数:
setSource() | 设置资源 |
加载QML文件:
myWIdget.qml
import QtQuick 2.9Rectangle{width: 100;height: 100;color: "red"
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2Window {id:window1visible: truewidth: 640height: 480title: qsTr("Hello World")Rectangle{width: 300;height: 300focus:truecolor: "lightBlue"Loader{id:loader1}Keys.onSpacePressed: { //按下空格loader1.source="myWidget.qml" //加载QML文件}}}
加载组件对象:
使用sourceComponent属性
Rectangle{width: 300;height: 300focus:truecolor: "lightBlue"Component{id:con1Image{width: 200;height: 200source: "qrc:/image/zzpic23859.jpg"}}}Loader{sourceComponent: con1}//加载组件对象
状态的使用:
Loader{id:loadsourceComponent: con1//加载的资源控件onStatusChanged: {if(load.status==Loader.Ready)console.log("加载完成")else if(load.status==Loader.Error)console.log("加载失败")else if(load.status==Loader.Loading)console.log("加载中")}}
setSource(url source,Object properties)
- source资源
- properties 对象
- 创建将具有给定属性的给定源组件的对象实例。属性参数是可选的。加载和实例化完成后,可通过 item 属性访问该实例。
//myWidget.qml
import QtQuick 2.9Rectangle{width: 100height: 100color: "red"
}//main.qmlRectangle{width: 300;height: 300focus:truecolor: "lightBlue"Loader{id:load}Component.onCompleted: {load.setSource("myWidget.qml",{color="yellow"})//设置资源和属性}}
加载程序的大小
如果源组件不是 Item 类型,则加载程序不会应用任何特殊的大小调整规则。用于加载视觉对象类型时,加载程序应用以下大小调整规则:
- 如果未为加载器指定显式大小,则加载器会在加载组件后自动调整为加载项的大小。
- 如果通过设置宽度、高度或锚定显式指定加载器的大小,则加载的项目将调整为加载器的大小。
当Loader中没有设置大小,直接使用控件大小
Rectangle{width: 300;height: 300focus:truecolor: "lightBlue"Component{id:com1Rectangle{width: 100height:100color: "red"}}Loader{//anchors.fill: parentsourceComponent: com1}}
当Loader中设置了,优先使用Loader中的设置
例一:
Rectangle{width: 300;height: 300focus:truecolor: "lightBlue"Component{id:com1Rectangle{width: 100height:100color: "red"}}Loader{anchors.fill: parent//填充整个父类sourceComponent: com1}}
例二:
Rectangle{width: 300;height: 300focus:truecolor: "lightBlue"Component{id:com1Rectangle{width: 100height:100color: "red"}}Loader{width:200height:200sourceComponent: com1}}
例一: 例二:
从加载的对象接收信号:
使用item可以获取生成的对象
//myWidget.qmlimport QtQuick 2.9Rectangle{width: 100height: 100color: "red"signal pick //创建一个信号
}//main.qmlRectangle{width: 300;height: 300focus:truecolor: "lightBlue"Loader{id:loadsource: "myWidget.qml"}Connections{target: load.item//获取生成的对象onPick:console.log("执行")}}
焦点和关键事件
加载程序是一个焦点范围。必须将其焦点属性设置为true ,其任何子项才能获得活动焦点
//myWidget.qmlimport QtQuick 2.9Rectangle{width: 100;height: 100;color: "red"focus:trueKeys.onSpacePressed: { //按下空格键触发console.log("加载项触发")event.accepted=true}}//main.qmlRectangle{width: 300;height: 300color: "lightBlue"Loader{id:loadsource: "myWidget.qml"focus:true//获取焦点}}