Randomly Colored QWidget Class

  • Share this:

Code introduction


This code defines a class named RandomColorWidget, which inherits from QWidget. The class sets a randomly generated color as the background color of the window upon initialization.


Technology Stack : PyQt5, QWidget, QColor, QPalette, random

Code Type : PyQt5 GUI Application

Code Difficulty : Intermediate


                
                    
def random_color_widget(arg1, arg2):
    from PyQt5.QtWidgets import QWidget
    from PyQt5.QtGui import QColor, QPalette
    import random

    class RandomColorWidget(QWidget):
        def __init__(self, parent=None):
            super(RandomColorWidget, self).__init__(parent)
            self.initUI(arg1, arg2)

        def initUI(self, width, height):
            self.setGeometry(300, 300, width, height)
            self.setWindowTitle('Random Color Widget')
            palette = QPalette()
            color = QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            palette.setColor(QPalette.Window, color)
            self.setPalette(palette)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = RandomColorWidget(200, 200)
    widget.show()
    sys.exit(app.exec_())