版本:Qt5.12.5 ,参考Qt源码及文档示例
代码链接:https://github.com/gongjianbo/QmlComponentStyle.git
自定义样式与默认样式的对比:
扁平样式实现代码:
import QtQuick 2.12
import QtQuick.Templates 2.12 as T
import QtQuick.Controls 2.12
import QtQuick.Controls.impl 2.12
import QtQuick.Shapes 1.12
//qtquickcontrols2\src\imports\controls\CheckBox.qml
//from Customizing CheckBox
T.CheckBox {
id:control
//可以像源码一样,定义一个全局的样式,然后取全局样式中对应的颜色
//checked选中状态,down按下状态,hovered悬停状态
property color textColor: "white"
property color backgroundTheme: "darkCyan"
property color backgroundColor: control.down
? Qt.darker(backgroundTheme)
: (control.hovered||control.highlighted)
? Qt.lighter(backgroundTheme)
: control.checked
? backgroundTheme
: backgroundTheme
property color indicatorColor: "white" //勾选框颜色
property int radius: 0
implicitWidth: 90
implicitHeight: 30
leftPadding: 5
rightPadding: 5
spacing: 5
font{
family: "SimSun"
pixelSize: 16
}
//勾选框,用贴图更方便
indicator: Rectangle {
implicitWidth: control.height-2*control.leftPadding
implicitHeight: width
x: control.leftPadding
y: (parent.height-height) / 2
color: "transparent"
border.width: 1
border.color: indicatorColor
antialiasing: false
//源码中是用ColorImage加载的按钮图标
Shape { //indicator全部用shape算了
id: checked_indicator
anchors.centerIn: parent
width: parent.width-6
height: parent.height-6
visible: control.checkState === Qt.Checked
//smooth: true //平滑处理
//antialiasing: true //反走样抗锯齿
ShapePath {
strokeWidth: 2
strokeColor: indicatorColor
//fillRule: ShapePath.WindingFill
fillColor: "transparent"
startX: 0; startY: checked_indicator.height/2
PathLine { x:checked_indicator.width/2; y:checked_indicator.height }
PathLine { x:checked_indicator.width; y:0 }
}
}
Rectangle {
anchors.centerIn: parent
width: parent.width/2
height: parent.height/2
color: indicatorColor
antialiasing: false
visible: control.checkState === Qt.PartiallyChecked
}
}
//勾选框文本
contentItem: CheckLabel {
text: control.text
font: control.font
color: textColor
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
renderType: Text.NativeRendering
elide: Text.ElideRight
leftPadding: control.indicator.width + control.spacing +control.leftPadding
rightPadding: control.rightPadding
}
background: Rectangle{
radius: control.radius
color: backgroundColor
}
}
//main.qml
Row{
id:checkbox_row
spacing: 10
Text {
width: 90
height: 30
renderType: Text.NativeRendering
text: "CheckBox:"
}
ButtonGroup{
id:checkbox_group2
}
CheckBox{
width: 90
height: 30
text: "Box A"
checked: true
ButtonGroup.group: checkbox_group2
}
BasicCheckBox{
text: "Box B"
textColor: "white"
backgroundTheme: "orange"
ButtonGroup.group: checkbox_group2
}
BasicCheckBox{
text: "Box C"
textColor: "cyan"
backgroundTheme: "purple"
indicatorColor: "cyan"
tristate: true
checkState: Qt.PartiallyChecked
radius: 3
}
}