WiseOwl Training - Established 1992 Wise Owl Training

Established May 1992
30 years in business
Wise Owl Training
30 years in business
See 519 reviews for our classroom and online training
Should you be using QT for Python as a GUI?
Part seven of an eight-part series of blogs

If you need to build a GUI system in Python, PyQt5 is probably the best choice, but don't take our word for it - read this blog and see what you think.

  1. Should you be using PyQt?
  2. QT Designer
  3. Widgets
  4. Layouts
  5. Forms and code
  6. Slots and Signals
  7. CSS and Formatting (this blog)
  8. Models and Data

Posted by Andy Brown on 21 June 2022

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

CSS and Formatting

By far the easiest way to attach formatting to the widgets of a form is using a cascading style sheet.  Here we have a simple form with absolutely no formatting:

Basic unformatted form

The form looks drab, but CSS will sort this out.

 

For the title at the top of the form saying that CSS is great, we've added this dynamic property:

Dynamic properties

I probably should have mentioned that you can add your own properties to widgets earlier!

 

You could now create a style sheet - here's mine:

CSS style sheet

This style sheet sets a default Verdana 14 point font for all widgets, then sets specific formatting for QT labels, push buttons and any widgets to which we've attached the class h1_title.

 

You can then apply this in your code:

# opens style sheet and returns string of text containing CSS

with open(r"temp.css") as css_file:

css = css_file.read()

 

# apply CSS

self.setStyleSheet(css)

This is what would appear when you run your form and click on the button:

Formatted form

In retrospect I should have put a bit more effort into making the styles look nice!  Notice that the title appears in a different font size, because it has its dynamic property class set to h1_title.

 

This ability to attach CSS style sheets to GUI forms is a big selling-point to me for PyQt5.

This blog has 0 threads Add post