Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt changing the background color of QWidget using palette doesn't work

Tags:

c++

qt

I want to change the background color in a custom subclass of QWidget. Here is the code:

WorldView::WorldView(QWidget *parent) : QWidget(parent)
{
    QPalette p(palette());
    p.setColor(QPalette::Background, Qt::black);
    setAutoFillBackground(true);
    setPalette(p);
}

But it doesn't work as expected. The background color remains unchanged.

I don't know why.

like image 686
crupest Avatar asked Feb 07 '23 08:02

crupest


1 Answers

As you can read in the documentation, QPalette::Background is obsolete. Use QPalette::Window instead. Note that some widgets use some other role for the background. See the QPalette::ColorRole documentation

Also:

Warning: Some styles do not use the palette for all drawing, for instance, if they make use of native theme engines. This is the case for both the Windows XP, Windows Vista, and the OS X styles.

In this case I suggest to use style sheets. See Qt Style Sheets Reference

However, if WorldView is a custom widget, with your custom paintEvent, it's up to you to draw the background

like image 147
Fabio Avatar answered Feb 24 '23 11:02

Fabio