示例是几个按钮,按下哪个按钮,哪个按钮显示不同
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QButtonGroup
import sys
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.__initUI__()
def __initUI__(self):
self.resize(400,200)
btn_1 = QPushButton("btn1" ,self)
btn_1.setGeometry(150, 10, 50, 20)
btn_1.setCheckable(True)
btn_2 = QPushButton("btn2" ,self)
btn_2.setGeometry(150, 40, 50, 20)
btn_2.setCheckable(True)
btn_3 = QPushButton("btn3" ,self)
btn_3.setGeometry(150, 70, 50, 20)
btn_3.setCheckable(True)
btn_4 = QPushButton("btn4" ,self)
btn_4.setGeometry(150, 100, 50, 20)
btn_4.setCheckable(True)
btn_group = QButtonGroup(self)
# 把按钮添加到QButtonGroup中,参数1是按钮实例对象,参数2是给按钮设置一个id,不同分组的id可以重复,如果id为-1,则将为该按钮分配一个id。自动分配的ID保证为负数,从-2开始。
btn_group.addButton(btn_1, 1)
btn_group.addButton(btn_2, 2)
btn_group.addButton(btn_3, 3)
btn_group.addButton(btn_4, 4)
print(btn_group.buttons()) # 返回按钮组中的所有按钮对象
print(btn_group.button(2)) # 返回按钮组中指定id号的按钮
print(btn_group.checkedButton()) # 返回按钮组中被选中的按钮
btn_group.removeButton(self.rb) # 从按钮组中移除指定按钮;不是删除按钮
btn_group.setId(btn_4, 5) # 给组中的按钮设置id
print(btn_group.id(btn_3)) # 返回按钮id,如果不存在此按钮,则返回-1
print(btn_group.checkedId()) # 返回选中按钮的id
btn_group.setExclusive(True) #独占
btn_group.buttonClicked.connect(self.cao) # 组中按钮被点击时发出信号
btn_group.buttonClicked[int].connect(self.cao1) # 组中按钮被点击时发出信号,其中的int就是按钮的id号,会向槽函数传递被点击按钮的id,而不是传递按钮
btn_group.buttonToggled.connect(self.cao2) # 当按钮组中的按钮被切换状态时, 发射此信号,会向槽函数传递状态发生改变的按钮
def cao(self):
print(666)
def cao1(self, id):
print(id)
def cao2(self, btn):
print(btn)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Demo()
window.show()
sys.exit(app.exec_())