3

I have a custom widget which inherits from QWidget and contains some labels in its layout. I would like to change the background color of the widget and the labels in the widget (this is, everything!) every time I put the mouse over it.

When using *:hover { background: red; } in my custom widget, I only get the contents red when moving the mouse over the labels, but not outside them, between labels, etc. I don't understand this behavior taking into account that I put the StyleSheet in the parent widget.

Any ideas? Many thanks,

Didac Perez Parera
  • 3,734
  • 3
  • 52
  • 87

2 Answers2

4

You can set the parent's stylesheet which will cascade to children like this:

parent->setStyleSheet("* {background: red}");

For hovering only:

parent->setStyleSheet("*:hover {background: red}");

Check out https://qt-project.org/doc/qt-5.1/qtwidgets/stylesheet-syntax.html

fxam
  • 3,874
  • 1
  • 22
  • 32
  • Thank you so much. But, in that case, how can I do it for mouse over? I mean, I was trying to use `QWidget:hover { background: foo; }`, may I use `*:hover { background: foo; }` ? – Didac Perez Parera Sep 30 '13 at 15:34
  • Works for all widgets but not the parent!! I am completely suprised! – Didac Perez Parera Sep 30 '13 at 15:43
  • @DídacPérez, your custom widget is inherited from which QWidget? I believe some widget has no hover event (eg: QGroupBox). You also don't need to use "*:hover". What you need to do is override enterEvent() and leaveEvent(). In enterEvent() you setStyleSheet("* {background: red}"), while in leaveEvent() you setStyleSheet("") to reset it. – fxam Sep 30 '13 at 16:03
  • OKAY, fixed the problem with a QFrame holding all the widgets. – Didac Perez Parera Sep 30 '13 at 16:10
1

Finally I solved the problem creating a QFrame inside the main QWidget and setting the StyleSheet of that QFrame.

Didac Perez Parera
  • 3,734
  • 3
  • 52
  • 87