the font of a stylesheeted spinbox cannot be resized

Whenever a stylesheet is set to a widget, Qt automatically disables that widget’s palette and font propagation. This means that all child widget will not be notified about font (and palette) changes from the parent.

This is explained in the inheritance chapter of the stylesheet syntax:

In classic CSS, when font and color of an item is not explicitly set, it gets automatically inherited from the parent. By default, when using Qt Style Sheets, a widget does not automatically inherit its font and color setting from its parent widget.

Note that the above obviously refers to fonts set using setFont() and colors set using setPalette(). If you set a font or a color in the stylesheet, the propagation of those properties will work as expected according to the cascading nature of stylesheets.

QSpinBox, like other widgets such as QComboBox and item views, is a complex widget, that use children widgets to display and interact with it, and in this case it’s a QLineEdit (accessible through lineEdit()).

In order to solve your issue there are multiple approaches available:

  1. set the AA_UseStyleSheetPropagationInWidgetStyles attribute on the application:

    QApplication.setAttribute(
        Qt.AA_UseStyleSheetPropagationInWidgetStyles, True)
    

    This obviously has the side effect that the propagation will work for all widgets of the application, it’s up to you to decide if that is fine or not.
    Note: this attribute has been introduced from Qt 5.7.

  2. check if the widget is a QSpinBox and set the font for its line edit:

    for widget in self.widgets:
        font = widget.font()
        font.setPointSize(scale * f0)
        if isinstance(widget, QSpinBox):
            widget.lineEdit().setFont(font)
        else:
            widget.setFont(font)
    
  3. set the font with the stylesheet. In your case, you could check if the widget has a stylesheet and use a template to update it:

    baseStyleSheet = '''
    {} {{
        background-color: red;
        font-size: {}px;
    }}
    '''
    
    # ...
        def resizeEvent(self, event):
            w0, h0, f0 = self.initial_size
            w, h = self.width(), self.height()
            scale = min(w/w0, h/h0)
            font_size = scale * f0
    
            for widget in self.widgets:
                if widget.styleSheet():
                    widget.setStyleSheet(baseStyleSheet.format(
                        widget.__class__.__name__, font_size))
                else:
                    font = widget.font()
                    font.setPointSize(font_size)
                    widget.setFont(font)
    

Obviously the above works only in this specific situation where only simple properties are set.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top