PyQt6 Random Color Selection Widget

  • Share this:

Code introduction


This function creates a PyQt6-based random color selector widget. Users can select a color, and the selected color will be applied to the widget's background.


Technology Stack : PyQt6, QWidget, QColorDialog

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_color_widget(parent=None):
    from PyQt6.QtWidgets import QWidget, QColorDialog
    from PyQt6.QtCore import Qt

    class ColorWidget(QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
            self.setWindowTitle("Random Color Widget")
            self.setGeometry(100, 100, 200, 200)
            self.color_dialog = QColorDialog(self)

        def show_color_dialog(self):
            color = self.color_dialog.open()
            if color == QColorDialog.ColorDialogResult.Accepted:
                self.setStyleSheet(f"background-color: {color.name()}")

    return ColorWidget