Search code examples
c++qtqt4qtstylesheets

[Qt]How to support :pressed state of style sheet for custom widget?


What i have :-

I have a custom widget which extends QFrame (instead of QWidget as QFrame already has a working paintEvent implementation). I have overridden the mousePressed() and mouseReleased() to emit the pressed() released() and clicked() Signals. Everything upto this point is woring fine as expected.

What i need :-

This custom widget is having basic style sheet support and it supports the :hover state just fine. But the :pressed state is not working. I have already figured out that this is bcoz its not supported by QFrame/QLabel etc. I wish to know what do i need to do in order to support the :pressed state. Should i set some attribute / property on pressed and released OR anything else ?


Solution

  • You can set a property to your QLabel (or whatever widget you are using) and change the value of that property. Then you use that property in your stylesheets.

    Example:

    this->setStyleSheet("*[myproperty=\"true\"] { background-color: red }");
    d_label = new QLabel("dynamic label", this);
    d_label->setProperty("myproperty", false);
    

    Then in your mousePressEvent you set and in mouseReleaseEvent you unset that property:

    d_label->setProperty("myproperty", true); // or false when you wish to unset it
    style()->unpolish(d_label);
    style()->polish(d_label); // force a stylesheet recomputation