h5網(wǎng)站建設(shè)短鏈接
最近在學(xué)習(xí)Qml,但對(duì)Qml的各種用法都不太熟悉,總是會(huì)搞忘,所以寫幾篇文章對(duì)學(xué)習(xí)過程中的遇到的東西做一個(gè)記錄。
學(xué)習(xí)參考視頻:https://www.bilibili.com/video/BV1Ay4y1W7xd?p=1&vd_source=0b527ff208c63f0b1150450fd7023fd8
目錄
- 1 動(dòng)態(tài)加載控件
- 1.1 用Component加載
- 1.1.1 使用方法
- 2 用Loader加載
- 2.1 用法
- 加載qml文件
- 加載Component
1 動(dòng)態(tài)加載控件
1.1 用Component加載
Component提供了createObject方法,可以在程序運(yùn)行時(shí)調(diào)用,以添加控件,它的官方例程如下。
var component = Qt.createComponent("Button.qml");
if (component.status == Component.Ready)component.createObject(parent, {x: 100, y: 100});
該方法需要先把加載的控件封裝到一個(gè)qml文件中,然后通過createComponent加載qml文件,如果qml文件是可用的(component.status == Component.Ready),那就用createObject來創(chuàng)建一個(gè)實(shí)例,參數(shù)1是實(shí)例的父控件id,參數(shù)2是實(shí)例的初始屬性。
1.1.1 使用方法
下面舉例說明使用流程。
創(chuàng)建一個(gè)Rect.qml文件。
在Rect.qml填入以下內(nèi)容,定義一個(gè)長寬為30的藍(lán)色矩形。
import QtQuick 2.0Rectangle { width: 30; height: 30; color: 'blue' }
在main,qml填入一下內(nèi)容,用按鈕來動(dòng)態(tài)添加Rect控件到網(wǎng)格布局。
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12Window {visible: true; width: 200; height: 120GridLayout {id: layoutcolumns: 4}Button {anchors.bottom: parent.bottomonClicked: {let component = Qt.createComponent("Rect.qml");if (component.status == Component.Ready)component.createObject(layout);}}
}
效果:
2 用Loader加載
Qml提供的Loader類動(dòng)態(tài)加載控件,以下是官方說明:
Loader可以加載QML文件(使用source屬性)或Component對(duì)象(使用sourceComponent屬性)。這對(duì)于將組件的創(chuàng)建延遲到需要時(shí)非常有用:例如,當(dāng)應(yīng)按需創(chuàng)建組件時(shí),或者出于性能原因不應(yīng)不必要地創(chuàng)建組件時(shí)。
它與Component加載有以下兩處不一樣。
1、Loader是延遲加載預(yù)先設(shè)定好的控件,并不是像Component那樣可以加載任意數(shù)量的控件。
2、Loader加載的可以是Component對(duì)象或者qml文件,Component只能加載qml文件。
2.1 用法
加載qml文件
以上一節(jié)的Rect,qml為例。
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12Window {visible: true; width: 200; height: 120Loader { id: loader}Button {anchors.bottom: parent.bottomonClicked: loader.setSource("Rect.qml")}
}
加載Component
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12Window {visible: true; width: 200; height: 120Loader { id: loader }Component {id: componentRect {}}Button {anchors.bottom: parent.bottomonClicked: loader.sourceComponent = component}
}