QT开发(五十四)———QML组件

    QML组件是由基本元素组合成的一个复杂的可重用的组合元素。QML 提供了多种方法来创建组件。

    基于文件的组件将QML元素放置在一个单独的文件中,然后给文件一个名字,可以通过名字来使用组件。如果有一个文件名为Cell.qml,就可以在QML中使用Cell { … }形式。自定义组件的文件名的首字母必须大写。

Cell.qml文件:

import QtQuick 2.0
 
Item
{
    id: container
    property alias cellColor: rectangle.color
    signal clicked(color cellColor)
 
    width: 40; height: 25
    Rectangle
    {
        id: rectangle
        border.color: "white"
        anchors.fill: parent
    }
    MouseArea
    {
        anchors.fill: parent
        onClicked: container.clicked(container.cellColor)
    }
}

    Rectangle有一个Text用于显示按钮的文本;有一个MouseArea用于接收鼠标事件。用户可以定义按钮的文本,用过设置Text的text属性实现的。为了不对外暴露Text元素,给Text的text属性一个别名。signal clicked给Cell一个信号。由于clicked信号是无参数的,也可以写成signal clicked(),二者是等价的。clicked信号会在MouseArea的clicked信号被发出,具体就是在MouseArea的onClicked属性中调用个clicked信号。

Main.qml文件:

import QtQuick 2.0
 
Rectangle
{
    id: page
    width: 320; height: 480
    color: "lightgray"
    Text
    {
        id: helloText
        text: "Hello world!"
        y: 30
        anchors.horizontalCenter: page.horizontalCenter
        font.pointSize: 24; font.bold: true
    }
    Grid
    {
        id: colorPicker
        x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4
        rows: 2; columns: 3; spacing: 3
        Cell { cellColor: "red"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
    }
}

    QT开发(五十四)———QML组件_开发

    main.qml中,直接使用了Cell组件。由于Cell.qml与main.qml位于同一目录下,所以不需要额外的操作。但如果将Cell.qml放在不同目录,main.qml的import部分增加一行import ../components才能够找到Cell组件。

    选择一个组件的根元素很重要。比如Cell组件,使用Rectangle作为其根元素。Rectangle元素可以设置背景色等。如果不允许用户设置背景色,可以选择使用Item元素作为根。