0

我的代码

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 在 QWidget 内连接到布局一样,并保存了边距和填充。

在此处输入图像描述

我尝试使用 setMinimumSize() 但 QLabel 始终为 30X100,直到您手动指定大小。但是不断计算margin、padding、font-size、border等qss属性太不方便了。

它应该像这样工作

在此处输入图像描述

但无需不断编写 self.setMinimumSize(QSize (140, 34)) 手册

4

0 回答 0