QML组件的使用

声明属性

/*
    *声明一个信号函数 变量名是cellColor 值是rectangle.color的值
    *alias就是自动解析类型
    */
    property alias cellColor: rectangle.color

声明信号函数

 /*
     * 声明一个信号函数
    */
    signal clicked(color cellcolor)

响应鼠标事件

MouseArea{
        anchors.fill: parent
        onClicked: container.clicked(container.cellcolor)
    }

响应槽函数

 /*
         * 处理cell的信号事件,如果cell发送了信号就设置Text的值
        */
        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 }

声明组件

import QtQuick 2.0
import QtQuick.Controls 2.2
/*
*组件名字的首字母都必须是大写的
*/
Item {
    id:container
    /*
    *声明一个信号函数 变量名是cellColor 值是rectangle.color的值
    *alias就是自动解析类型
    */
    property alias cellColor: rectangle.color
    /*
     * 声明一个信号函数
    */
    signal clicked(color cellcolor)
    width: 40
    height: 25
    Rectangle{
        id:rectangle
        border.color: "white"
        anchors.fill: parent
        height:25
    }
    MouseArea{
        anchors.fill: parent
        onClicked: container.clicked(container.cellcolor)
    }
}

使用组件

import QtQuick 2.0
import QtQuick.Controls 2.2
Rectangle {
    id:page
    width: 320
    height: 480
    color: "lightgray"
    Text{
        id:helloText
        text:"hello world"
        anchors.topMargin: 30
        anchors.top: page.top
        anchors.horizontalCenter: page.horizontalCenter
    }
    Grid {
        id: colorPicker
        x: 4
        anchors.bottom: page.bottom
        anchors.bottomMargin: 4
        rows: 2
        columns: 3
        spacing: 3
        /*
         * 处理cell的信号事件,如果cell发送了信号就设置Text的值
        */
        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 }

    }
}

猜你喜欢

转载自blog.csdn.net/kebiaoy/article/details/81064208