Search code examples
pythonpython-3.xpysideqtstylesheetspyside6

Width, Height, and Margin doesn't work in QT Style Sheet in PySide6


So I have a Qt StyleSheet called main.qss in the style sheet I am trying to set width and height it doesn't work it just remains the same. This same thing happens for Margins aswell.

Here is the QSS:

QFrame#mainFrame {
    background-color: #282C34;
}

QFrame#menuFrame {
    background-color: #21252B;
}

QPushButton.menuButton {
    background-color: #21252B;

    padding-left: 12px;
    padding-top: 1px;
    padding-bottom: 1px;

    border: 0;
    font-family: "Times New Roman";
    font-size: 20pt;

    color: #FFFFFF;

    width: 300pt; <-- Problem here
    height: 15px; <-- Problem here
}

QPushButton.menuButton:hover {
    background-color: #282C34;
}

QPushButton.menuButton:pressed {
    background-color: #BD93F9;
}

and here is my QPushButton:

self.menu_toggle_button = QtWidgets.QPushButton(self.menu_frame)
self.menu_toggle_button.setIcon(QtGui.QPixmap("menu_icons/menu.png"))
self.menu_toggle_button.setText("  Hide")
self.menu_toggle_button.setObjectName("menuToggleButton")
self.menu_toggle_button.setProperty("class", "menuButton")
self.menu_toggle_button.setIconSize(QtCore.QSize(20, 20))

So what am I doing wrong?

I know this works because in the Qt Style Sheet Reference, which can be found here: https://doc.qt.io/qtforpython-6/overviews/stylesheet-reference.html?highlight=stylesheet, It says that width, height, and margins are supported for QPushButtton.


Solution

  • Your stylesheet doesn't work for two reasons:

    1. the width (and height) properties generally don't apply to widgets, but only to subcontrols, as explained in the docs:

    Warning: Unless otherwise specified, this property has no effect when set on widgets. If you want a widget with a fixed width, set the min-width and max-width to the same value.

    1. the "dot" separator doesn't work as it does in python, but as it does in css: it's a class selector:

    .QPushButton          Matches instances of QPushButton, but not of its subclasses.

    If you want to match the objectName property, you need the ID selector:

        QPushButton#menuButton {...}
    

    Consider that while Qt stylesheets support those properties, it's generally better to leave those kind of settings to the layout manager and directly use the widget functions (setFixedSize(), setFixedWidth(), setFixedHeight()).

    Finally, the margins don't work because you're using the padding. Qt uses the same concept as CSS also for the Box Model:

    stylesheet box model

    So, the padding you're setting is between the border of the button and the content (icon and/or text, which is the QStyle SE_PushButtonContents sub element). What you're looking for is the margin.