环境
Ubuntu16.04+Qt5.7
描述
qml中有一个控件RadioButton,单选按钮,即在一个按钮组中只能选中一个;如果想自定义实现按钮的样式的话,则需要使用到一个qml类型:ExclusiveGroup。
效果
如图,左上方的是使用RadioButton实现的效果,中间的则为自定义按钮互斥效果。
实现
首先实现自定义按钮的样式,然后再寻找一种方法使这些按钮群产生互斥的效果即可。这个实现查到一种十分便捷的方法,即ExclusiveGroup。其中,Exclusive有“独家,独占的”之意。
Qt助手中,ExclusiveGroup的描述为“ExclusiveGroup可以包含多个Action项,这些项将自动获取其Action :: exclusiveGroup属性。几个控件已经支持ExclusiveGroup,例如 Action,MenuItem,Button和RadioButton。”
再看Qt助手中给出的例子:大致意思为给一个Item添加互斥属性,需要如下操作。
疑问:注意上图的最后一句:如上图所示是向Item添加互斥属性的最少且必须的代码。遗憾的是,我试着这样做但是没有互斥效果,究其原因,是缺少了一个onCheckedChanged的处理,但是不明白为什么Qt助手中会这样描述。
例子
CheckButton.qml部分代码如下:
import QtQuick 2.1
import QtQuick.Controls 1.4
Rectangle{
……
property bool checked: false
property ExclusiveGroup exclusiveGroup: null //对外开放一个ExclusiveGroup接口,用于绑定同个组
onExclusiveGroupChanged: {
if (exclusiveGroup) {
exclusiveGroup.bindCheckable(checkButton)
}
}
//如果少了这个信号处理,则无法出现互斥效果
onCheckedChanged: {
checked ? checkPic.source = "qrc:/icon_choose.png" : checkPic.source = "qrc:/icon_choose_not.png"
}
Image {
……
}
Text {
……
}
MouseArea {
……
}
}
用法
main.qml部分代码如下:
import QtQuick 2.5
import QtQuick.Controls 1.4
Rectangle {
id: root
width: 640; height: 480
color: "#ff0099FF"
……
Text{
id: text
anchors.bottom: buttonRow.top
anchors.left: buttonRow.left
anchors.margins: 5
text: "请任意选择一项:"
font.pixelSize: 20
color: "white"
}
Row {
id: buttonRow
spacing: 5
anchors.centerIn: parent
ExclusiveGroup { id: buttonGroup } //提供一个组给按钮绑定
CheckButton {
id: btnA
buttontext: "A"
textColor: "white"
exclusiveGroup: buttonGroup //绑定到组
}
CheckButton {
id: btnB
buttontext: "B"
textColor: "white"
exclusiveGroup: buttonGroup //绑定到组
}
CheckButton {
id: btnC
buttontext: "C"
textColor: "white"
exclusiveGroup: buttonGroup //绑定到组
}
CheckButton {
id: btnD
buttontext: "D"
textColor: "white"
exclusiveGroup: buttonGroup //绑定到组
}
}
}
完整项目代码可从此处下载。
版权声明:本文为ZefinNg原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。