Important: Please read the Qt Code of Conduct -

setStyleSheet doesn't change font on QListWidget, but changes background color

  • I have a QListWidget, some items have custom background colors set via setBackground().
    I'm trying to change the font weight of selected items in QListWidget with the following code:
    self.setStyleSheet("QListWidget::item:selected {color: red; border: 2px solid black; font: bold;}")

    It does make the text color of the selected items red and it does add the border, but it doesn't make the font bold (I also tried italic and also tried font-weight:bold; - nothing worked). Why is that?

    Also, it changes the item background although I don't need that, I need to keep the background of the items.
    My goal is to indicate the selected items visually because the default styling doesn't work well with my custom backgrounds.

    A related question is: if I set an image in the stylesheet with image-position: left; style it overlaps the text. Is there a way to set some fixed size indentation for text? There's a workaround - I can put the image to the right, but would be cool to have it on the left.

    I'm using PySide6.

  • Lifetime Qt Champion


    It looks like you should rather implement a custom QStyledItemDelegate.

  • @SGaist Thanks for the idea. But my question is: why can't I use the stylesheet approach? It seems to work, but it works in a strange way - some styles are applied, some are ignored, some override the default styles. I would like to understand why it works like that. Maybe I can achieve what I need with the stylesheets - after all they are intended specifically for this if I understand it correctly.

  • Lifetime Qt Champion

    Sorry, I wasn't precise enough. When you start using stylesheet you have to do the complete styling as the application default style is not used anymore and is replaced by the one handling the stylesheet.

  • @SGaist Thanks. What about setStyleSheet changing the color, but not changing the font weight? Is this a bug? Or is this by design?

  • Lifetime Qt Champion

    Can you provide a minimal runnable script so we can reproduce this locally ?

  • @SGaist Sure, here it is:

    from PySide2.QtWidgets import QListWidget, QApplication
    app = QApplication()
    listw = QListWidget()
    listw.setStyleSheet("QListWidget::item:selected {color: red; border: 2px solid black; font: bold;}")

    If you select a list item, the color changes to red and the border appears, but the font weight doesn't change (I tried bold and italic).

  • @midnightdim
    This has always been the case, e.g. see QListView item font StyleSheet not working:

    seems like setting the font via stylesheet for the ::itemsubcotnrol isn't supported at all. Only setting the font on the item-widget itself, but then the font gets applied for all items.

    That post suggests the only way to achieve it is via data(Qt::FontRole) method.

Log in to reply