Qt Quick 实例(二)

QtQuick 自定义信号与使用

实例简述

在界面上添加两个按钮和一个text文本,点击按钮切换文本字体颜色,此处通过自定义信号来实现(在上一节基础上添加按钮)

实例效果

在这里插入图片描述

实例代码

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2

Rectangle {
    id: window
    visible: true
    width: 800
    height: 600

    color: Qt.rgba(0.5,0.5,0.5,0.6)
    MouseArea {
        id: dragRegion
        anchors.fill: parent
        property point clickPos: "0,0"
        onPressed: {
            clickPos = Qt.point(mouse.x, mouse.y)
        }
        onPositionChanged: {
            //鼠标偏移量
            var delta = Qt.point(mouse.x - clickPos.x, mouse.y - clickPos.y)
            //如果mainwindow继承自QWidget(用setPos)
            mainwindow.setX(mainwindow.x + delta.x)
            mainwindow.setY(mainwindow.y + delta.y)
        }
    }

    //自定义信号
    Text {
        id: colorText
        text: qsTr("heool world")
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top
        anchors.topMargin: 20
        font.pixelSize: 20
    }

    //触发按钮
    Component {
        id: colorComponent
        Rectangle {
            id: colorPicker
            width: 50
            height: 30
            //自定义信号
            signal colorPicked(color clr);
            MouseArea {
                anchors.fill: parent
                onPressed: colorPicker.colorPicked(colorPicker.color);
            }
        }
    }

    //QML的Loader元素经常备用来动态加载QML组件。可以使用source属性或者sourceComponent属性加载。
    //这个元素最有用的地方是它能在qml组件需要的时候再创建,即延迟创建QML的时间
    Loader {
        id: redLoader
        anchors.left: parent.left
        anchors.leftMargin: 4
        anchors.bottom: parent.bottom
        sourceComponent: colorComponent
        onLoaded: {
            item.color = "red"
        }
    }

    Loader {
        id: blueLoader
        anchors.left: redLoader.right
        anchors.leftMargin: 4
        anchors.bottom: parent.bottom
        sourceComponent: colorComponent
        onLoaded: {
            item.color = "blue"
        }
    }

    //信号与槽链接
    Connections {
        //这里的item指向的是Loader创建的对象
        target: redLoader.item
        onColorPicked: {
            colorText.color = clr
        }
    }

    Connections {
        target: blueLoader.item
        onColorPicked: {
            colorText.color = clr
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kevin_org

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值