1

Можно ли задать цвет заднего фона для QLabel без использование сss


class MyLabel(QLabel):
    def __init__(self, *args, **kwargs):
        super().__init__( *args, **kwargs)

    def _set_color(self, col):
        palette = self.palette()
        palette.setColor(QtGui.QPalette.Background, QtGui.QColor(col))
        self.setAutoFillBackground(True)
        self.setPalette(palette)


    color = QtCore.pyqtProperty(QtGui.QColor, fset=_set_color)


class Test:
    def __init__(self, parent):
        self.parent = parent
        self.width = 48
        self.height = 24
        self.border_radius = self.height // 2
        self.switch_radius = self.height - 4
        self.switch_border_radius = self.switch_radius // 2

        self.switch_color = '#ffffff'
        self.active_background_color = '#240DC4'
        self.disable_background_color = '#CCCCCC'

        self.animation_duration = 400

        self.background = self._make_background() 

        # Для примера вызываем метод смены заднего фона с конструктора класса
        self._change_background()


    def _make_background(self):
        background = MyLabel(self.parent)
        background.setObjectName("label_5")
        background.setGeometry(QtCore.QRect(self.x, self.y, self.width, self.height))
        background.setStyleSheet(
            "border-radius: %ipx;" \
            "background-color: %s;"  % (self.border_radius, self.disable_background_color)
        )

        return background


    def _change_background(self):
        self.background_color_animation = QtCore.QPropertyAnimation(self.background, b"color")
        self.background_color_animation.setDuration(self.animation_duration)
        self.background_color_animation.setStartValue(QtGui.QColor(50, 50, 50))
        self.background_color_animation.setEndValue(QtGui.QColor(255, 50, 50))
        self.background_color_animation.setEasingCurve(QtCore.QEasingCurve.InOutCubic)
        self.background_color_animation.start()

введите сюда описание изображения

4
  • stackoverflow.com/questions/2749798/…
    – magrif
    3 июн 2021 в 10:59
  • Проблема в том, что таким образом слетает border-radius
    – Lo_okiMan
    3 июн 2021 в 11:22
  • Опубликуйте пример вашего кода, который демонстрирует что у вас там слетает и лучше расскажите/покажите, что вы хотите получить.
    – S. Nick
    3 июн 2021 в 11:50
  • добавил пример и фото того что выходит
    – Lo_okiMan
    3 июн 2021 в 12:09

1 ответ 1

0

Я не могу воспроизвести ваш пример, потому что он не воспроизводимый. Но глядя на ваше изображение, я вам покажу что-то похожее на то, что вы излбразили.

from PyQt5.QtCore import (Qt, QSize, QPoint, QPointF, QRectF, pyqtProperty,
    QEasingCurve, QPropertyAnimation, QSequentialAnimationGroup, pyqtSlot)
from PyQt5.QtGui import QColor, QBrush, QPaintEvent, QPen, QPainter
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QLabel,
    QCheckBox, QApplication)


class AnimatedToggle(QCheckBox):
    _transparent_pen = QPen(Qt.transparent)
    _light_grey_pen = QPen(Qt.lightGray)

    def __init__(
            self,
            parent=None,
            bar_color=Qt.gray,
            checked_color="#00B0FF",
            handle_color=Qt.white,
            pulse_unchecked_color="#44999999",
            pulse_checked_color="#4400B0EE"
        ):
        super().__init__(parent)

        self._bar_brush = QBrush(bar_color)
        self._bar_checked_brush = QBrush(QColor(checked_color).lighter())
        self._handle_brush = QBrush(handle_color)
        self._handle_checked_brush = QBrush(QColor(checked_color))
        self._pulse_unchecked_animation = QBrush(QColor(pulse_unchecked_color))
        self._pulse_checked_animation = QBrush(QColor(pulse_checked_color))

        self.setContentsMargins(8, 0, 8, 0)
        self._handle_position = 0
        self._pulse_radius = 0

        self.animation = QPropertyAnimation(self, b"handle_position", self)
        self.animation.setEasingCurve(QEasingCurve.InOutCubic)
        self.animation.setDuration(200)                                         
        
        self.pulse_anim = QPropertyAnimation(self, b"pulse_radius", self)
        self.pulse_anim.setDuration(350)                                    
        self.pulse_anim.setStartValue(10)
        self.pulse_anim.setEndValue(20)

        self.animations_group = QSequentialAnimationGroup()
        self.animations_group.addAnimation(self.animation)
        self.animations_group.addAnimation(self.pulse_anim)

        self.stateChanged.connect(self.setup_animation)                      

    def sizeHint(self):            
        return QSize(58, 45)

    def hitButton(self, pos: QPoint):           
        return self.contentsRect().contains(pos)

    @pyqtSlot(int)
    def setup_animation(self, value):
        self.animations_group.stop()
        if value:
            self.animation.setEndValue(1)
        else:
            self.animation.setEndValue(0)
        self.animations_group.start()

    def paintEvent(self, e: QPaintEvent):
        contRect = self.contentsRect()
        handleRadius = round(0.24 * contRect.height())

        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)                 

        p.setPen(self._transparent_pen)
        barRect = QRectF(
            0, 0,
            contRect.width() - handleRadius, 0.40 * contRect.height()
        )
        barRect.moveCenter(contRect.center())
        rounding = barRect.height() / 2
        trailLength = contRect.width() - 2 * handleRadius
        xPos = contRect.x() + handleRadius + trailLength * self._handle_position

        if self.pulse_anim.state() == QPropertyAnimation.Running:
            p.setBrush(
                self._pulse_checked_animation if
                self.isChecked() else self._pulse_unchecked_animation)
            p.drawEllipse(QPointF(xPos, barRect.center().y()),
                          self._pulse_radius, self._pulse_radius)

        if self.isChecked():
            p.setBrush(self._bar_checked_brush)
            p.drawRoundedRect(barRect, rounding, rounding)
            p.setBrush(self._handle_checked_brush)

        else:
            p.setBrush(self._bar_brush)
            p.drawRoundedRect(barRect, rounding, rounding)
            p.setPen(self._light_grey_pen)
            p.setBrush(self._handle_brush)

        p.drawEllipse(
            QPointF(xPos, barRect.center().y()),
            handleRadius, handleRadius)

        p.end()

    @pyqtProperty(float)
    def handle_position(self):
        return self._handle_position

    @handle_position.setter
    def handle_position(self, pos):
        self._handle_position = pos
        self.update()

    @pyqtProperty(float)
    def pulse_radius(self):
        return self._pulse_radius

    @pulse_radius.setter
    def pulse_radius(self, pos):
        self._pulse_radius = pos
        self.update()


if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = QWidget()

    mainToggle = AnimatedToggle()
    secondaryToggle = AnimatedToggle(
            checked_color="#FFB000",
            pulse_checked_color="#44FFB000"
    )
    mainToggle.setFixedSize(mainToggle.sizeHint())       
    secondaryToggle.setFixedSize(mainToggle.sizeHint())  

    window.setLayout(QVBoxLayout())
    window.layout().addWidget(QLabel("Main Toggle"))
    window.layout().addWidget(mainToggle)
    window.layout().addWidget(QLabel("Secondary Toggle"))
    window.layout().addWidget(secondaryToggle)

    mainToggle.stateChanged.connect(secondaryToggle.setChecked)

    window.resize(100, 200)                                        
    window.show()
    sys.exit(app.exec_())
        
  

введите сюда описание изображения

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.