You can download this code by clicking the button below.
This code is now available for download.
This function creates a random color selection widget based on PyQt5. When the user clicks the button, it will pop up a color selection dialog and apply the selected color to the background.
Technology Stack : PyQt5
Code Type : Custom function
Code Difficulty : Intermediate
def random_color_widget(parent=None):
from PyQt5.QtWidgets import QWidget, QColorDialog
from PyQt5.QtCore import Qt
class ColorWidget(QWidget):
def __init__(self, parent=None):
super(ColorWidget, self).__init__(parent)
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Random Color Widget')
self.color_button = QPushButton('Pick Random Color', self)
self.color_button.setGeometry(50, 50, 150, 50)
self.color_button.clicked.connect(self.show_color_dialog)
def show_color_dialog(self):
color = QColorDialog.getColor()
if color.isValid():
self.setStyleSheet(f"background-color: {color.name()}")
return ColorWidget()