Python PyQt program - Color picker
Write a Python program to create a combobox with a list of colors using PyQt. When the user selects a color from the dropdown, change the main window background color.
From doc.qt.io:
QApplication Class: The QApplication class manages the GUI application's control flow and main settings.
QMainWindow Class: The QMainWindow class provides a main application window.
QComboBox Class: The QComboBox widget is a combined button and popup list.
QVBoxLayout Class: The QVBoxLayout class lines up widgets vertically.
QWidget: The QWidget class is the base class of all user interface objects.
QColor Class: The QColor class provides colors based on RGB, HSV or CMYK values.
Sample Solution:
Python Code:
Explanation:
In the exercise above -
- Import the necessary modules.
- Create a 'QMainWindow' named ColorPickerApp with a central widget.
- Set the window's title and initial size.
- Make a 'QComboBox' widget ('color_combo') and populate it with the names of the colors.
- The "currentIndexChanged" signal of the combo box should be connected to the "change_color()" method, which will be called by the user when the color is selected.
- Based on the selected color from the combo box, "change_color()" sets the background color of the central widget.
- In the main() function, we create the PyQt application, create an instance of the "ColorPickerApp" class, show the window, and run the application's event loop.
Output:
Flowchart:
Python Code Editor:
Previous: Simple text editor.
Next: Button color changer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics