PyQt5 QWidget with Dynamic Background Color

  • Share this:

Code introduction


This function creates a PyQt5 QWidget and sets its background color to the color argument passed in.


Technology Stack : PyQt5, QWidget, QColor

Code Type : PyQt5 GUI application

Code Difficulty : Intermediate


                
                    
def random_color_widget(color):
    from PyQt5.QtWidgets import QWidget
    from PyQt5.QtGui import QColor

    class RandomColorWidget(QWidget):
        def __init__(self, color):
            super().__init__()
            self.initUI(color)

        def initUI(self, color):
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('Random Color Widget')
            self.setStyleSheet(f'background-color: {color.name()}')

    return RandomColorWidget(QColor(color))