我是PyQT5的新手,我希望有几个按钮,并且在“已检查”状态下单击最后一个按钮。当点击另一个按钮时,前一个按钮被“取消选中”,而被点击的按钮被“检查”。
import sys
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
答案 0 :(得分:3)
建立代码,您可以将android.widget.TextView[contains(@text,'Data usage')]
和button1
添加到button2
,QButtonGroup
属性设置为exclusive
。
True
这里我还将一个空槽连接到信号class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.btn_grp = QButtonGroup()
self.btn_grp.setExclusive(True)
self.btn_grp.addButton(self.button1)
self.btn_grp.addButton(self.button2)
self.btn_grp.buttonClicked.connect(self.on_click)
self.show()
def on_click(self, btn):
pass # do something with the button clicked
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
,只要点击该组中的按钮就会发出该信号QButtonGroup.buttonClicked
。
要找出当前选中的按钮,您可以调用方法QButtonGroup.checkedButton()
和QButtonGroup.checkedId()
。前者将返回QButton
对象,后者将返回索引int
,对应于按钮添加到组中的顺序。
答案 1 :(得分:-2)
将按钮添加到QButtonGroup(),其余按钮自动排序:
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button1.setCheckable(True)
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.button2.setCheckable(True)
self.my_button_group = QButtonGroup()
self.my_button_group.addButton(self.button1)
self.my_button_group.addButton(self.button2)
self.show()