How to get the checked radiobutton from a groupbox in pyqt
我有一个带有一些单选按钮的分组框。我怎么知道哪一个是检查过的?
另一种方法是使用按钮组。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class MoodExample(QGroupBox): def __init__(self): super(MoodExample, self).__init__() # Create an array of radio buttons moods = [QRadioButton("Happy"), QRadioButton("Sad"), QRadioButton("Angry")] # Set a radio button to be checked by default moods[0].setChecked(True) # Radio buttons usually are in a vertical layout button_layout = QVBoxLayout() # Create a button group for radio buttons self.mood_button_group = QButtonGroup() for i in xrange(len(moods)): # Add each radio button to the button layout button_layout.addWidget(moods[i]) # Add each radio button to the button group & give it an ID of i self.mood_button_group.addButton(moods[i], i) # Connect each radio button to a method to run when it's clicked self.connect(moods[i], SIGNAL("clicked()"), self.radio_button_clicked) # Set the layout of the group box to the button layout self.setLayout(button_layout) #Print out the ID & text of the checked radio button def radio_button_clicked(self): print(self.mood_button_group.checkedId()) print(self.mood_button_group.checkedButton().text()) app = QApplication(sys.argv) mood_example = MoodExample() mood_example.show() sys.exit(app.exec_()) |
号
我在以下网站找到了更多信息:
http://codeprogress.com/python/libraries/pyqt/showpyqt示例.php?index=387&key=qButtonGroupClick
http://www.pythonschool.net/pyqt/radio-button-widget/
您需要遍历GroupBox中的所有单选按钮,并检查每个RadioBox的属性
如:
1 2 3 4 5 6 7 8 | radio1 = QtGui.QRadioButton("button 1") radio2 = QtGui.QRadioButton("button 2") radio3 = QtGui.QRadioButton("button 3") for i in range(1,4): buttonname ="radio" + str(i) if buttonname.isChecked(): print buttonname +"is Checked" |
请参阅http://pyqt.sourceforge.net/docs/pyqt4/qradiobutton.html
我使用索引和循环的组合来解决这个问题。
1 | indexOfChecked = [self.ButtonGroup.buttons()[x].isChecked() for x in range(len(self.ButtonGroup.buttons()))].index(True) |
。
1 2 3 4 5 6 7 | def izle(self): radios=["radio1","radio2","radio3","radio4"] for i in range(0,4): selected_radio = self.ui.findChild(QtGui.QRadioButton, self.radios[i]) if selected_radio.isChecked(): print selected_radio.objectName() +"is Checked" |