I recently started using qt to build a python GUI. I have two problems I can't quite find the solutions to. the code below is a sample of what I need to build.
1: Check which radio button from a list of radio buttons in a vertical layout has been clicked. In the GUI it only selects one radio button out of all others available in the layout. How do I perceive which has been clicked?
2:I would like to add the clicked value to a JSON object but I believe that is a simple if statement of if this then that. Unless it's more complicated in which case please push me in the right direction.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(596, 466)
self.verticalLayoutWidget = QtWidgets.QWidget(Dialog)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(180, 70, 61, 80))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.that = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.that.setObjectName("that")
self.verticalLayout.addWidget(self.that)
self.thi = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.thi.setObjectName("thi")
self.verticalLayout.addWidget(self.thi)
self.sure = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.sure.setObjectName("sure")
self.verticalLayout.addWidget(self.sure)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.that.setText(_translate("Dialog", "that"))
self.thi.setText(_translate("Dialog", "this"))
self.sure.setText(_translate("Dialog", "sure"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
There is a nice way to solve this using Qt Designer, which allows you to group your buttons into a QButtonGroup, and then connect to its buttonClicked signal to get the button that was clicked.
All you need to do is, in Qt Designer, select all the buttons (using Ctrl+click), then right-click one of the buttons and select Assign to button group -> New button group. This will create a new button-group object and automatically add all the buttons to it.
After re-generating your gui module, you can then do somehting like this:
ui.radioButtonGroup.buttonClicked.connect(radioButtonClicked)
def radioButtonClicked(button):
print(button.text())