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

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

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

    基于文件的组件将QML元素放置在一个单独的文件中,而后给文件一个名字,能够经过名字来使用组件。若是有一个文件名为Cell.qml,就能够在QML中使用Cell { … }形式。自定义组件的文件名的首字母必须大写。ui

Cell.qml文件:spa

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信号。component

Main.qml文件:blog

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 }
    }
}

    wKiom1hVVQugCS0UAAA4J8mXzYQ429.png

    main.qml中,直接使用了Cell组件。因为Cell.qml与main.qml位于同一目录下,因此不须要额外的操做。但若是将Cell.qml放在不一样目录,main.qml的import部分增长一行import ../components才可以找到Cell组件。事件

    选择一个组件的根元素很重要。好比Cell组件,使用Rectangle做为其根元素。Rectangle元素能够设置背景色等。若是不容许用户设置背景色,能够选择使用Item元素做为根。图片

相关文章
相关标签/搜索