Random Color Rectangle Display in PyQt6

  • Share this:

Code introduction


Create a small PyQt6 window that displays a rectangle with a random color.


Technology Stack : PyQt6, QWidget, QPainter, QColor, Qt

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color_widget():
    from PyQt6.QtWidgets import QWidget
    from PyQt6.QtGui import QColor, QPainter
    from PyQt6.QtCore import Qt

    class ColorWidget(QWidget):
        def __init__(self):
            super().__init__()
            self.initUI()

        def initUI(self):
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('Random Color Widget')

        def paintEvent(self, event):
            qp = QPainter()
            qp.begin(self)
            qp.setBrush(QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
            qp.drawRect(self.rect())
            qp.end()

    import random
    app = QApplication([])
    widget = ColorWidget()
    widget.show()
    app.exec()