Troyseph
Troyseph

Reputation: 5138

How do you remove a QPalette from a QWidget

According to Qt's QWidget documentation:

QWidget propagates explicit palette roles from parent to child. If you assign a brush or color to a specific role on a palette and assign that palette to a widget, that role will propagate to all the widget's children, overriding any system defaults for that role.

I have a widget hierarchy:

QMainWindow 'window'
     |_QGroupBox 'box'
          |_QLabel 'label'
          |_QLabel 'label2'

So if I were to call box->setPalette(somePalette) the new palette is used to paint box, label and label2

Now I want to undo this, i.e. I want box, label and label2 to use my default palette, which is easy, I call box->setPalette(window->palette()) right?

The issue with this is box still technically has a custom palette set (it makes a deep copy of the palette you pass it), if I modify the palette of window it no longer propagates through box to label and label2.

So, how do I actually remove the palette from box so that palette propogation is restored?

Upvotes: 2

Views: 1745

Answers (2)

nickexists
nickexists

Reputation: 573

I know this is an old question but all you need to do to unset a palette is pass a default constructed QPalette like this: myWidget->setPalette(QPalette())

When you do this the setPalette function will handle the WA_SetPalette attribute for you and whatever other internal machinery is needed to get things working.

I've tested this in Qt6.5 but I think it should work in older versions as well.

Upvotes: 2

Alexander V
Alexander V

Reputation: 8698

How do I actually remove the palette from box so that palette propagation is restored?

You can use QWidget::setAttribute to explicitly set or remove Qt::WA_WindowPropagation flag to make sure the palette is propagated (or not). From my experience that sometimes require QWidget::update() to be called afterwards.

UPDATE: There is also Qt::WA_SetPalette attribute for enabling/disabling individual widget palette update. With this specific case we need to propagate the palette down to the nested widgets first as the author suggested in comments e.g. box->setPalette(window->palette()); box->setAttribute(WA_SetPalette, false);.

Upvotes: 1

Related Questions