Qt World Summit: Submit your Presentation

Qt dynamic styles [Stylesheet]?

  • I was needing a QLabel that could deal with a mouse hover event - since :hover is not supported by QLabel, I had to override a new class from QLabel, responding to enterEvent() and leaveEvent(). So far so good.

    What I really needed was to put an underline decoration on the QLabel text:

    @QFont f(font());
    f.setUnderline(true [or false]);

    However, wanting to venture deeper into decoration (changing text color, for example), I was met by a road block. The easiest way to change text color is via stylesheets, but in this case I had other styles applied to the element that I did not want to change, so simply setting a new stylesheet would clear the one already set. I could of course append/delete the parts I wished to change, but it seems to me that's sort of overcomplicating matters.

    To the point: Is it in any way possible to change individual stylesheet styles dynamically for a widget? Like,

    @QWidget::setStyle("color", "#CCCCCC");@

    (I know that setStyle is already available, setting a QStyle, but that's beside the point).

  • Moderators

    The :hover property does work for labels, but it seems sorta selective for text decoration, ie. this works as expected:
    setStyleSheet("QLabel { color: red; }
    QLabel:hover { color: blue; } ");
    this works too
    setStyleSheet(" QLabel { text-decoration: underline; } ");
    but this doesn't:
    setStyleSheet(" QLabel:hover { text-decoration: underline; } ");
    It actually looks like a bug to me.

    Anyway, there's no way to selectively change one part of a stylesheet, but you can use a palette trick: set your color in the stylesheet to something like "color: palette(dark)" or any other element you don't plan to use and then change the appropriate palette color for this widget.

  • The "hover" stylesheet event is not defined for QLabel (even though it works in some cases, go figure); this is a documented anti-feature. Beats me though, because in my world it's probably one of the most obvious places to use it.
    Thanks, but I was sort of hoping to avoid playing with QPalette, although if there's no way around I might just have to.

Log in to reply