Qt Style Sheets or QSS is very much similar to Cascading Style Sheets (CSS) for the web. However, QSS supports only a limited number of rules in comparison with CSS. For example, QSS supports the box model but doesn’t support the flexbox and grid layouts.
To set the style sheets for a widget, you call its setStyleSheet() method with a style sheet string. To demonstrate QSS, we’ll turn the following login window:
…into the following login window:
The following program creates a login window that appears in the first picture without any style sheets.
subheading = QLabel( 'Please enter your email and password to log in.', alignment=Qt.AlignmentFlag.AlignHCenter ) subheading.setObjectName('subheading')
self.email = QLineEdit(self) self.email.setPlaceholderText('Enter your email')
self.password = QLineEdit(self) self.password.setEchoMode(QLineEdit.EchoMode.Password) self.password.setPlaceholderText('Enter your password')
subheading = QLabel( 'Please enter your email and password to log in.', alignment=Qt.AlignmentFlag.AlignHCenter ) subheading.setObjectName('subheading')
self.email = QLineEdit(self) self.email.setPlaceholderText('Enter your email')
self.password = QLineEdit(self) self.password.setEchoMode(QLineEdit.EchoMode.Password) self.password.setPlaceholderText('Enter your password')
First, right-click the form and select Change StyleSheet … menu:
Second, enter the Qt Style Sheets into the Style Sheet Editor and click the Apply button. Once the QSS is applied, you’ll see its effect in the design:
Third, close the style sheet editor and preview the form (Ctrl-R):