QML笔记Loader的使用方法

Loader简介

Loader is used to dynamically load QML components.
Loader can load a QML file (using the source property) or a Component object (using the sourceComponent property). It is useful for delaying the creation of a component until it is required: for example, when a component should be created on demand, or when a component should not be created unnecessarily for performance reasons.
祥见Loader QML Type | Qt Quick 5.9

译文:
loader用于动态加载qml组件。
加载程序可以加载qml文件(使用source属性)或组件对象(使用source component属性)。将组件的创建延迟到需要时非常有用:例如,当应按需创建组件时,或者当不应因性能原因而不必要地创建组件时。

为什么要使用Loader

在使用QML开发复杂界面时,应为需要实现一个系统下各个子系统的滑动效果。如果不使用动态加载,每一个子系统界面进行数据交互会导致系统卡顿或者浪费大量不比要的资源。
之前使用了Loader的sourceComponent来实现,但是会导致程序在点击进入该界面时卡顿严重,具体原因我猜测是QML在加载界面时会把所有Component组件全部加载一遍。因此使用Loader的source直接动态加载qml文件。

Loader的sourceComponent用法

在同一个qml文件中定义

// 申明Loader
Loader{
   
        id:componetLoader
        sourceComponent: undefined
    }
//创建组件
Component{
   
        id:resectionSystemCom
        Rectangle{
   
            x:577;y:
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,使用 Loader 实现登录功能。 首先,在主界面中添加一个 Loader 组件,用于加载登录界面: ``` import QtQuick 2.0 Rectangle { width: 400 height: 400 Loader { id: loginLoader anchors.fill: parent } } ``` 接着,在主界面中添加一个按钮,点击后加载登录界面: ``` Button { text: "登录" onClicked: { loginLoader.source = "Login.qml" } } ``` 在 Login.qml 文件中,可以定义登录界面的样式和逻辑。例如,下面是一个简单的登录界面,包含两个文本框和一个按钮: ``` import QtQuick 2.0 Rectangle { width: 200 height: 200 TextInput { id: usernameInput anchors.top: parent.top width: parent.width placeholderText: "用户名" } TextInput { id: passwordInput anchors.top: usernameInput.bottom width: parent.width placeholderText: "密码" echoMode: TextInput.Password } Button { text: "登录" anchors.top: passwordInput.bottom anchors.horizontalCenter: parent.horizontalCenter onClicked: { // 在这里执行登录逻辑 } } } ``` 在按钮的 onClicked 信号中,可以执行登录逻辑,例如验证用户名和密码是否正确。如果登录成功,可以在主界面中显示其他内容,例如一个欢迎消息: ``` Rectangle { width: 400 height: 400 Loader { id: loginLoader anchors.fill: parent onLoaded: { // 登录成功后显示欢迎消息 if (username === "admin" && password === "123456") { loginLoader.source = "Welcome.qml" } } } } ``` 在 Welcome.qml 文件中,可以定义欢迎消息的样式和内容,例如: ``` import QtQuick 2.0 Rectangle { width: 200 height: 200 Text { text: "欢迎," + usernameInput.text font.pointSize: 20 anchors.centerIn: parent } } ``` 这样,使用 Loader 就可以实现登录功能了。当用户点击登录按钮时,会加载 Login.qml 文件,并在其中执行登录逻辑。如果登录成功,会加载 Welcome.qml 文件,并显示欢迎消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值