本文主要是介绍qml 实现胶囊按钮(半边圆角按钮),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
项目场景:
项目中,UI上要实现类似胶囊切换按钮,站在巨人的肩膀上实现了,效果如下:
实现细节:
宽度、高度、圆角均可自定义 其实实现是两个按钮放在了一起,只不过按钮的圆角可以自定义设置 先看按钮的实现:import QtQuick 2.0Rectangle {id: rootheight:100width:200property string title : ""property int textSize : 20property color bgColor : checked?"yellow":"gray"property color textColor : checked?"black":"#FFFFFF"color: bgColorproperty bool checked: falseproperty int radiusCorners: Qt.AlignLeft | Qt.AlignRight | Qt.AlignTop | Qt.AlignBottom /* Default: *//*Qt.AlignLeft | Qt.AlignLeft | Qt.AlignRight | Qt.AlignLeft | Qt.AlignLeft |Qt.AlignRight | Qt.AlignTop | Qt.AlignTop | Qt.AlignRight | Qt.AlignRight |None:0 Qt.AlignTop | Qt.AlignBottom Qt.AlignBottom Qt.AlignTop Qt.AlignBottomQt.AlignBottom***************** ************* *************** *************** ************* ****************** * * * * * * * * * * ** * * * * * * * * * * ** * * * * * * * * * * ** * * * * * * * * * * ** * * * * * * * * * * ** * * * * * * * * * * ****************** ************* *************** *************** ***************** **************/Repeater {model: [ {x: 0,y: 0,visible: internal.aligns(Qt.AlignLeft | Qt.AlignTop),radius: root.radius},{x: root.width - root.radius,y: 0,visible: internal.aligns(Qt.AlignRight | Qt.AlignTop),radius: root.radius},{x: 0,y: root.height - root.radius,visible: internal.aligns(Qt.AlignLeft | Qt.AlignBottom),radius: root.radius},{x: root.width - root.radius,y: root.height - root.radius,visible: internal.aligns(Qt.AlignRight | Qt.AlignBottom),radius: root.radius} ]Rectangle {x: modelData.x; y: modelData.ywidth: modelData.radius; height: widthvisible: !modelData.visiblecolor: parent.color}}QtObject {id: internalfunction aligns(direction) {return (root.radiusCorners & direction) === direction}}Text{id:contenttext: titlefont.pixelSize: textSizecolor: textColoranchors.centerIn: parent}
}
实现其实是矩形的四个角加上四个小矩形来实现各种类型圆角配置。
本文章代码如下:
import QtQuick 2.11
import QtQuick.Window 2.11Window {visible: truewidth: 640height: 480ButtonA{id:mywidth :100height:80anchors.centerIn: parent//color: "red"radius: height/2radiusCorners: Qt.AlignLeft | Qt.AlignBottom | Qt.AlignToptitle:"btn1"MouseArea{anchors.fill: parent// onPressed: {// my.color = "gray"// }// onReleased: {// my.color = "yellow"// }onClicked: {console.debug("左边点击")my.checked = true;my2.checked = false}}}ButtonA{id:my2width :100height:80anchors.left: my.righty:my.y//color: "red"radius: height/2radiusCorners: Qt.AlignRight | Qt.AlignBottom | Qt.AlignToptitle:"btn2"MouseArea{anchors.fill: parentonClicked: {console.debug("右边点击")my.checked = false;my2.checked = true}}}Component.onCompleted:{my2.checked = true}
}
扩展:
实现不规则按钮也可以用qml Shape来实现。具体问题具体研究
这篇关于qml 实现胶囊按钮(半边圆角按钮)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!