How to Add CSS Stylesheet in PyQt6 Application

In this PyQt6 Application tutorial 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.

 

 

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:

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

How to Add CSS Stylesheet in PyQt6 Application
How to Add CSS Stylesheet in PyQt6 Application

 

 

Learn More on PyQt6

 

Leave a Comment