In this PyQt6 lesson we want to learn How to Add CSS Stylesheet in PyQt6 Application, as you know that PyQt6 is one of the most powerful GUI Development Framework for Python programming language, also PyQt6 provides different default styling options, for example you can use CSS and style your GUI applications widgets like buttons, labels and etc.
So Cascading Style Sheets or CSS is widely used language for describing the presentation of a document written in HTML or XML. it allows you to define styles for elements on a web page, including fonts, colors, layout and many more. PyQt6 supports using of CSS stylesheets to apply similar concepts to desktop applications.
First of all we need to create a new CSS file with a .qss extension, this file will contain our custom styles. We can use any text editor to create and edit this file.
This is our basic style, in this example, we set the background color for all QWidget elements, defined a style for QPushButton, and set the text color and font for QLabel.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/* styles.qss */ QWidget { background-color: #f0f0f0; } QPushButton { background-color: #ed4c4f; color: #ffffff; padding: 8px 16px; border: none; font-size:15px; } QLabel { color: #555555; font-size:20px; } |
Now for applying CSS style sheet to your PyQt6 application, you need to load it in the code. this is an example of how you can do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import sys from PyQt6.QtWidgets import QApplication, QWidget, QLabel,QVBoxLayout,QPushButton from PyQt6.QtCore import QFile, QIODevice, QTextStream class MainWindow(QWidget): def __init__(self): super().__init__() # Load the CSS style sheet style_sheet_file = QFile("style.qss") if style_sheet_file.open(QIODevice.OpenModeFlag.ReadOnly | QIODevice.OpenModeFlag.Text): style_sheet = QTextStream(style_sheet_file).readAll() self.setStyleSheet(style_sheet) self.setWindowTitle("My PyQt6 Application") # Add your application's widgets and logic here vbox = QVBoxLayout() btn = QPushButton("Click") label = QLabel("Codeloop.org - PyQt6 Tutorial") vbox.addWidget(btn) vbox.addWidget(label) self.setLayout(vbox) if __name__ == "__main__": app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec()) |
In this example, we have created a MainWindow class inherited from QWidget. In the constructor, we load the CSS style sheet using QFile and QTextStream. after that we set the loaded style sheet using setStyleSheet(), also we have created QPushButton and QLabel to see that styles are working are not.
Run the complete code and this will be the output
Subscribe and Get Free Video Courses & Articles in your Email