Как динамически подогнать размер label под layout?

Мой код

import sys
from PyQt5.QtWidgets import (QRadioButton, QHBoxLayout, QButtonGroup, 
    QApplication, QWidget, QLabel)
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import QSize, Qt
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *



class Label(QLabel):
    def __init__(self, parent=None):
        super(Label, self).__init__(parent)
        self.parent = parent
        self._animation = QtCore.QVariantAnimation(
                startValue=QtGui.QColor("blue"),
                endValue=QtGui.QColor("green"),
                valueChanged=self._on_value_changed,
                duration=400,
            )
        self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))


    def _on_value_changed(self, color):
        foreground = (
            QtGui.QColor("black")
            if self._animation.direction() == QtCore.QAbstractAnimation.Forward
            else QtGui.QColor("yellow")
        )
        self._update_stylesheet(color, foreground)

    def _update_stylesheet(self, background, foreground):
        self.setStyleSheet(
            """
        QLabel{
            padding:10;
            margin10;
            background: %s;
            color: %s;
        }
        """
            % (background.name(), foreground.name())
        )
    def enterEvent(self, event):
        self._animation.setDirection(QtCore.QAbstractAnimation.Backward)
        self._animation.start()
        super().enterEvent(event)

    def leaveEvent(self, event):
        self._animation.setDirection(QtCore.QAbstractAnimation.Forward)
        self._animation.start()
        super().leaveEvent(event)

    def mousePressEvent(self, event):
        self.parent.click()


class Radio(QRadioButton): 
    def __init__(self, parent=None):
        super(Radio, self).__init__(parent)
        lay = QtWidgets.QGridLayout(self)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        self.setText('0')
        self.label = Label(self)
        self.label.setText('test0098908uhjhjk9')

        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())


        self.setStyleSheet('QRadioButton{background:red} QRadioButton::indicator{ text:rgba(0, 0, 0, 0); background:rgba(0, 0, 0, 0)}')


        self.label.setSizePolicy(sizePolicy)

        self.label.setStyleSheet('padding:10;margin10;background:green')
        self.label.setAlignment(Qt.AlignCenter)
        lay.addWidget(self.label, 0, 0, 1, 1)

        print('radio-2 h - {}'.format(self.height()))
        print('radio-2 w - {}'.format(self.width()))
        print('label h -{}'.format(self.label.height()))
        print('label w -{}'.format(self.label.width()))

        self.setMinimumSize(QSize(140, 34))

        self.toggled.connect(self.on_off)
    def on_off(self):
        if self.isChecked():                                   
            self.label.setText('<div>&#xe3434</div>')
        else:
            self.label.setText('<div>&#xe3456</div>')


class Window(QWidget):
    def __init__(self):
        super().__init__()

        self._dictRB = {                                            
            '0': False,
            'rb1': False,
            'rb2': False,
            'rb3': False,
        }

        self.main_layout = QHBoxLayout(self)

        self.buttonGroup = QButtonGroup()
        self.attr_layout = QHBoxLayout()
        self.main_layout.addLayout(self.attr_layout)

        self.rb0 = Radio()                             #QRadioButton() # 'rb0'

        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.rb0.sizePolicy().hasHeightForWidth())
        self.rb0.setSizePolicy(sizePolicy)

        self.attr_layout.addWidget(self.rb0)
        self.buttonGroup.addButton(self.rb0)

        self.rb1 = QRadioButton('rb1')
        self.attr_layout.addWidget(self.rb1)
        self.buttonGroup.addButton(self.rb1)               

        self.rb2 = QRadioButton('rb2')
        self.attr_layout.addWidget(self.rb2)
        self.buttonGroup.addButton(self.rb2) 

        self.rb3 = QRadioButton('rb3')                               
        self.buttonGroup.addButton(self.rb3)                         

        self.buttonGroup.buttonClicked.connect(self.check_button)

    def check_button(self, radioButton):
        if self._dictRB[radioButton.text()]:
            self._dictRB[radioButton.text()] = False
            self._dictRB['rb3'] = True
            self.rb3.setChecked(True)              
        else:
            for b in self._dictRB:
                self._dictRB[b] = False
            self._dictRB[radioButton.text()] = True

        print("Button -> `{} - {}`".format(radioButton.text(), radioButton.isChecked()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Window()
    #w.setMinimumSize(QSize(0, 400))
    w.show()
    sys.exit(app.exec_())

Мне нужно чтобы Radio() не было меньше QLabel. И вела себя примерно как если бы QLabel был подключен к Layout находясь внутри QWidget С сохраненым margin, padding, font-size, border,

image

Примерно как здесь

image

но сделать это динамически чтобы не писать вручную каждый раз setMinimumSize()


Ответы (1 шт):

Автор решения: Sergey Tatarincev

Почитайте документацию по компоновке. Все эти вещи задаются с помощью QWidget::sizePolicy(). Через эту политику можно задать как растягивать и в каких пропорциях каждый из элементов QLayout.

→ Ссылка