python-3.xradio-buttonpyside2groupbox

Make widget borders colored on activation in Pyside2


I have a group of three QRadioButtons and three QGroupBoxes on my Pyside2 window application. When I click one radio button - a group box gets enabled.

enter image description here

if self.ui.radioButton_1.isChecked():
    self.ui.groupBox_1.setEnabled(True)
    self.ui.groupBox_2.setEnabled(False)
    self.ui.groupBox_3.setEnabled(False)    
elif self.ui.radioButton_2.isChecked():
    self.ui.groupBox_1.setEnabled(False)
    self.ui.groupBox_2.setEnabled(True)
    self.ui.groupBox_3.setEnabled(False)    
elif self.ui.radioButton_3.isChecked():
    self.ui.groupBox_1.setEnabled(False)
    self.ui.groupBox_2.setEnabled(False)
    self.ui.groupBox_3.setEnabled(True)

Is it possible via implementing styles or enabling some option in Qt Designer to make borders of a chosen QGroupBox colored on activation? Something like this:

enter image description here

The exact width of green lines in not important, the colored border lightening matters only.


Solution

  • You can set a border in the style sheet for QGroupBox with the :enabled pseudo-state.

    import sys
    from PySide2.QtWidgets import *
    
    class Template(QWidget):
    
        def __init__(self):
            super().__init__()
            grid = QGridLayout(self)
            for i in range(3):
                radio_btn = QRadioButton(f'RadioButton_{i + 1}', checked=not i)
                group_box = QGroupBox(f'GroupBox_{i + 1}', enabled=not i)
                radio_btn.toggled[bool].connect(group_box.setEnabled)
                hbox = QHBoxLayout(group_box)
                hbox.addWidget(QLabel(f'Test_{i + 1}'))
                hbox.addWidget(QLineEdit())
                grid.addWidget(radio_btn, i, 0)
                grid.addWidget(group_box, i, 1)
    
            self.setStyleSheet('''
            QGroupBox {
                margin-top: 1ex;
            }
            QGroupBox:enabled {
                border: 3px solid green;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 1ex;
            }''')
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        window = Template()
        window.show()
        sys.exit(app.exec_())
    

    enter image description here