QML使用自定义组件的两种方式

使用QML进行UI开发,非常灵活方便,且动画效果容易实现,但因为灵活,为了美观需要使用很多自定义的组件。
这里列举了两种使用自定义组件的方式,主要是为了日后自己翻阅


以下示例的开发环境

  • ubuntu16.04
  • Qt5.12.12
  • ubuntu16.04自带的gcc编译器

工程目录说明

ImpCompDemo/
├── CustomComponents
│   ├── DeButton.qml
│   └── SubDir
│       └── DeTextField.qml
├── ImpCompDemo.pro
├── ImpCompDemo.pro.user
├── main.cpp
├── main.qml
├── Parameters
│   ├── GlobalParameters.qml
│   └── qmldir
└── qml.qrc

main.qml文件下,包括有CustomComponents和Parameters两个目录
其中CustomComponents下的两个自定义组件,以相对路径方式调用(DeTextField.qml在SubDir目录下)
Parameters下的GlobalParameters.qml定义一些配置信息,使用单例方式注册

以下是程序说明

方式一:使用相对路径方式

使用相对路径方式主要用于较为简单,且调用方和被调用方的相对路径不长且固定的场合

该示例工程中,使用了一个自定义的Button和TextField为例
从工程目录结构可以看到这2个组件分别在main.qml所在目录的CustomComponents文件夹和CustomComponents下的SubDir文件夹中,所以在main.qml中,通过相对路径访问这2个组件使用

// main.qml代码
import QtQuick 2.12
import QtQuick.Window 2.12

// 使用相对路径方式调用组件
import "./CustomComponents"
import "./CustomComponents/SubDir"

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    // 使用相对路径方式调用组件DeTextField
    DeTextField {
        id: text
        anchors.centerIn: parent
        width: 200
        height: 50
    }

    // 使用相对路径方式调用组件DeButton
    DeButton {
        anchors.top: text.bottom
        anchors.topMargin: 25
        anchors.horizontalCenter: parent.horizontalCenter
        width: 150
        height: 50

        text: qsTr("ok")
    }
}

使用相对路径方式调用,确实很方便,只要import 后把被调用组件的相对路径加进来即可

方式二:使用模块注册方式

该方式使用qmldir文件对组件进行模块化管理
如该工程所示,Parameters目录下的GlobalParameters.qml即为该方式调用

// GlobalParameters.qml代码
pragma Singleton

import QtQuick 2.12

Item {

    enum Status {
        Idle,
        Off,
        On
    }

    readonly property color btnBkColor: "lightblue"
    readonly property int txtPointSize: 12
}

由于GlobalParameters.qml内管理工程中的全局参数,故使用了单例方式

qmldir文件内容

module Parameters
singleton GlobalParameters 1.0 GlobalParameters.qml

注:模块名称,应与模块所在的目录名称完全一致

使用该模块注册方式需要有3步操作

  1. 使用import导入模块
  2. 在工程pro文件中QML_IMPORT_PATH变量,添加模块所在目录的上级目录
  3. 在main.cpp中使用addImportPath添加该模块的上级目录
// 使用模块注册方式步骤1:导入模块
import Parameters 1.0
# 使用模块注册方式步骤2:QML_IMPORT_PATH变量,添加模块所在目录的**上级**目录
QML_IMPORT_PATH += \
    $$PWD
QQmlApplicationEngine engine;
// 使用模块注册方式步骤3:使用addImportPath添加该模块的**上级**目录
engine.addImportPath("qrc:/");

组件通过模块方式注册后,可以方便的使用其内部的资源,比如枚举

Component.onCompleted: {
        // 使用已注册的模组内单例组件的枚举类型
        console.log(GlobalParameters.Status.On)
    }

示例工程源码,提交在码云

https://gitee.com/sonicss/QmlImportDemo.git

git@gitee.com:sonicss/QmlImportDemo.git


版权声明:本文为sonicss原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。