qml自定义控件:简易的带图标按钮

在实际需求中,Qt自带的控件显得十分“原始”,因此,想要做出更加好看的样式,常常需要用到自定义控件。下面是一个自定义的带图标的按钮控件,实现方式十分简单。

效果图

在这里插入图片描述

环境

ubuntu16.04 + Qt5.7.1

代码部分

这里主要自定义写了一个控件,方便复用。文件IconButton.qml代码如下:

import QtQuick 2.7//不同Qt版本使用的QtQuick版本可能不同,需修改

Rectangle {
    //自定义属性
    property string btMesg: ""//按钮按下时发出的字符串
    property string btText: ""//按钮文字

    property color  textColor: "#ff000000"
    property string pressedTextColor: textColor
    property string releaseTextColor: textColor

    property real   fontSize: 20

    property string buttonColor: "#00000000"
    property string pressedColor: buttonColor
    property string releaseColor: buttonColor

    property string btIcon: ""
    property string pressedIcon: btIcon
    property string releaseIcon: btIcon

    property string borderColor: textColor
    property string pressdBorderColor: pressedTextColor

    property alias wrapMode: textId.wrapMode
    property alias elide: textId.elide

    width: 80; height: 60
    color: mouseArea.pressed?pressedColor:releaseColor
    border.width: 0
    border.color: mouseArea.pressed?pressdBorderColor:borderColor
    focus : true
    signal clicked()
    signal clickedWithMesg(string mesg)
    signal pressed()
    signal release()

    Image {
        id: image
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top
        anchors.topMargin: (parent.height - height - textId.height - 5) / 2
        source: mouseArea.pressed?pressedIcon:releaseIcon
    }
    Text {
        id: textId
        anchors.top: image.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        horizontalAlignment: Text.AlignHCenter
        wrapMode: Text.WordWrap
        width: parent.width
        text: btText
        color: mouseArea.pressed?pressedTextColor:releaseTextColor
        font.pixelSize: fontSize
    }

    MouseArea{
        id : mouseArea
        hoverEnabled: true
        anchors.fill: parent
        onClicked: {
            parent.clicked()
            parent.clickedWithMesg(btMesg)
        }
        onPressed: {
            parent.pressed(btMesg)
        }
        onReleased: {
            parent.release()
        }
    }
}

实现其实十分简单明了,即在pressed时改变按钮颜色而released时则恢复按钮颜色,便可以出现点击效果。

代码链接

https://download.csdn.net/download/zefinng/11133899

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值