Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly use CSS inside PySide2

My code succeeds in displaying 'Hello World!', however the CSS styling is not applied. I don't know how to do this properly. If anyone has some good explanations on this topic it would be very much appreciated.

The output of my code

from PySide2.QtWidgets import QApplication, QLabel, QWidget

app = QApplication([])

window = QWidget()
window.setStyleSheet('''
    p {
        font-size: 100px;
    }
''')

label = QLabel('<p>Hello World!</p>', parent=window)

window.show()
app.exec_()
like image 582
Benjamin Smus Avatar asked Oct 30 '25 06:10

Benjamin Smus


1 Answers

First of all, there is a different Qt StyleSheet that applies to all widgets and the html that some widgets support.

The Qt StyleSheets are a simple way to set the style and some properties to the QWidgets and that are based on CSS 2.1 but adapted to Qt.

Instead some widgets support rich text like html, and that is the case of QLabel, in this case the style must be placed inline

Considering there are several solutions:

from PySide2.QtWidgets import QApplication, QLabel, QWidget

app = QApplication([])

label = QLabel('<p style="font-size: 100px">Hello World!</p>', parent=window)

window.show()
app.exec_()
from PySide2.QtWidgets import QApplication, QLabel, QWidget

app = QApplication([])

window = QWidget()
window.setStyleSheet('''
    QLabel {
        font-size: 100px;
    }
''')

label = QLabel('<p>Hello World!</p>', parent=window)

window.show()
app.exec_()
from PySide2.QtWidgets import QApplication, QLabel, QWidget

app = QApplication([])

window = QWidget()

label = QLabel('<p style="font-size: 100px">Hello World!</p>', parent=window)
font = label.font()
font.setPointSize(100)
label.setFont(font)

window.show()
app.exec_()
like image 55
eyllanesc Avatar answered Nov 01 '25 20:11

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!