一 RadioButton的简单用法
QML的单选按钮是RadioButton,例如下面的界面
实现代码如下:
RadioButton {
id:rb1
checked: true
text: qsTr("First")
}
RadioButton {
id:rb2
text: qsTr("Second")
}
RadioButton {
id:rb3
text: qsTr("Third")
}
Button{
text: "获取单选状态"
onClicked: {
console.log("单选按钮1:" + rb1.checked)
console.log("单选按钮2:" + rb2.checked)
console.log("单选按钮3:" + rb3.checked)
}
}
可以通过checked属性,获取单选的结果,控制台输出:
qml: 单选按钮1:false
qml: 单选按钮2:true
qml: 单选按钮3:false
二 自定义RadioButton
2.1 自定义效果,可以设置圆圈的半径大小,颜色样式等
实现代码
//自定义单选按钮
RadioButton {
id: control
text: qsTr("自定义RadioButton")
checked: true
indicator: Rectangle {
implicitWidth: 56
implicitHeight: 56
x: control.leftPadding
y: parent.height / 2 - height / 2
radius: 28
border.color: control.down ? "#17a81a" : "#21be2b"
Rectangle {
width: 34
height: 34
x: 11 // (56 - 34) / 2
y: 11
radius: 17
color: control.down ? "#17a81a" : "#21be2b"
visible: control.checked
}
}
contentItem: Text {
text: control.text
font: control.font
opacity: enabled ? 1.0 : 0.3
color: control.down ? "#17a81a" : "#21be2b"
verticalAlignment: Text.AlignVCenter
leftPadding: control.indicator.width + control.spacing
}
}
2.2 默认的单选按钮文字在右边,圆圈在左边,可以修改为文字在左边
代码:
import QtQuick 2.12
import QtQuick.Controls 2.12
RadioDelegate {
id: control
text: qsTr("RadioDelegate")
checked: true
contentItem: Text {
rightPadding: control.indicator.width + control.spacing
text: control.text
font: control.font
opacity: enabled ? 1.0 : 0.3
color: control.down ? "#17a81a" : "#21be2b"
elide: Text.ElideRight
verticalAlignment: Text.AlignVCenter
}
indicator: Rectangle {
implicitWidth: 26
implicitHeight: 26
x: control.width - width - control.rightPadding
y: parent.height / 2 - height / 2
radius: 13
color: "transparent"
border.color: control.down ? "#17a81a" : "#21be2b"
Rectangle {
width: 14
height: 14
x: 6
y: 6
radius: 7
color: control.down ? "#17a81a" : "#21be2b"
visible: control.checked
}
}
background: Rectangle {
implicitWidth: 100
implicitHeight: 40
visible: control.down || control.highlighted
color: control.down ? "#bdbebf" : "#eeeeee"
}
}
以上这些自定义的实现在Qt助手都可以找到,具体位置
搜索RadioButton,翻到底部就可以找到,有各种各样的实现。