pyqt5显示单击了哪个按钮

时间:2017-03-13 21:26:06

标签: python pyqt pyqt5 qbuttongroup

我是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_())

2 个答案:

答案 0 :(得分:3)

建立代码,您可以将android.widget.TextView[contains(@text,'Data usage')] button1添加到button2QButtonGroup属性设置为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)

  1. 通过setCheckable(True)
  2. 使按钮可以检查
  3. 将按钮添加到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()