PyQt5-QButtonGroup-按钮组
一、描述
- 提供一个抽象的按钮容器,可以将多个按钮划分到一个组中
- 不具备可视化效果
- 一般存放的都是可以被检查的按钮
二 、继承
QButtonGroup继承自QObject,直接继承自QObject一般不具备可视化效果
三、使用
1、创建4个单选按钮并添加到2个按钮组
#创建两个单选按钮按钮
r_male = QRadioButton("男",self)
r_male.move(50,100)
r_female = QRadioButton("女",self)
r_female.move(50,150)
#创建按钮组
sex_group = QButtonGroup(self)
#将按钮添加到按钮组
sex_group.addButton(r_male)
sex_group.addButton(r_female)
r_yes = QRadioButton("是",self)
r_yes.move(100,100)
r_no = QRadioButton("否",self)
r_no.move(100,150)
answer_group = QButtonGroup(self)
answer_group.addButton(r_yes)
answer_group.addButton(r_no)
这样 ”男“ ”女“ 单选按钮是一组,”是“ ”否“单选按钮是一组,这两组互不影响。
下面是QButtonGroup的构造方法,需要写上父控件,默认为None
init(parent: QObject = None)
addButton方法内有两个参数,要添加的按钮以及id,id默认值为-1
如果没有设置id,系统为自动设置id,id从-2开始,都为负数,如果要设置id请使用正数。
addButton(QAbstractButton, id: int = -1)
2、查看按钮组中的按钮
- 获取按钮组中的全部按钮
sex_buttons = sex_group.buttons()
answer_buttons = answer_group.buttons()
获取的结果是一个含有按钮元素的列表
- 获取按钮组中的单个按钮
获取按钮组中的单个俺就是使用id获取,前提是需要添加按钮到按钮组时需要设置id
r_male = QRadioButton("男",self)
r_female = QRadioButton("女",self)
#创建按钮组
sex_group = QButtonGroup(self)
#将按钮添加到按钮组并未按钮设置id
sex_group.addButton(r_male,1)
sex_group.addButton(r_female,2)
m = sex_group.button(1)#获取男按钮
f = sex_group.button(2)#获取女按钮
3、查看按钮组中哪个按钮被选中
r_male = QRadioButton("男",self)
#设置按钮 “男”被选中
r_male.setChecked(True)
r_male.move(50,100)
r_female = QRadioButton("女",self)
r_female.move(50,150)
sex_group = QButtonGroup(self)
sex_group.addButton(r_male,1) #添加到按钮组
sex_group.addButton(r_female,2)
print(sex_group.checkedButton())#查看哪个按钮被选中
4、从按钮组移除按钮
r_male = QRadioButton("男",self)
r_female = QRadioButton("女",self)
sex_group = QButtonGroup(self)
sex_group.addButton(r_male,1)
sex_group.addButton(r_female,2)
print(sex_group.buttons()) #查看按钮组中的按钮
sex_group.removeButton(r_female) #从按钮组中移除按钮
print(sex_group.buttons()) #再次查看按钮组中的按钮
5、设置id 和获取id
如果创建按钮时没有设置id,后面也可以有方法添加。
r_yes = QRadioButton("是",self)
r_yes.move(100,100)
r_no = QRadioButton("否",self)
r_no.move(100,150)
answer_group = QButtonGroup(self)
answer_group.addButton(r_yes)
answer_group.addButton(r_no)
answer_group.setId(r_yes,1) #为按钮添加id
answer_group.setId(r_no,2)
print(answer_group.id(r_yes)) #获取id
print(answer_group.id(r_no))
6、检查被选中按钮的id
r_yes = QRadioButton("是",self)
r_yes.move(100,100)
r_no = QRadioButton("否",self)
r_no.setChecked(True)
r_no.move(100,150)
answer_group = QButtonGroup(self)
answer_group.addButton(r_yes)
answer_group.addButton(r_no)
answer_group.setId(r_yes,1)
answer_group.setId(r_no,2)
print(answer_group.checkedId()) #检查被选中按钮的id
7、按钮组独占设置以及获取设置
r_yes = QRadioButton("是",self)
r_yes.move(100,100)
r_no = QRadioButton("否",self)
# r_no.setChecked(True)
r_no.move(100,150)
answer_group = QButtonGroup(self)
answer_group.addButton(r_yes)
answer_group.addButton(r_no)
answer_group.setId(r_yes,1) #为按钮添加id
answer_group.setId(r_no,2)
#设置独占 ,设置True为互斥
answer_group.setExclusive(False)
#获取按钮组是否独占
print(answer_group.exclusive())