How to get the checked radiobutton from a groupbox in pyqt

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I have a groupbox with some radiobuttons. How do I get to know which one which is checked.

回答1:

Another way is to use button groups. For example:

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

I found more information at:

http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=387&key=QButtonGroupClick

http://www.pythonschool.net/pyqt/radio-button-widget/



回答2:

you will need to iterate through all the radio buttons in the groupbox and check for the property isChecked() of each radiobox.

eg:

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" 

for reference, check http://pyqt.sourceforge.net/Docs/PyQt4/qradiobutton.html



回答3:

I managed to work around this problem by using a combination of index and loop.

indexOfChecked = [self.ButtonGroup.buttons()[x].isChecked() for x in range(len(self.ButtonGroup.buttons()))].index(True) 


回答4:

    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" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!