How to Change the Background Color of QWidget

From Qt Wiki
Jump to navigation Jump to search

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh


QWidget is the base class of all user interface objects which means that the same approaches for changing the background color can be used with them too.

Using the Palette

The first example demonstrates how to change the background color using QPalette

m_myWidget = new QWidget(this);
m_myWidget->setGeometry(0, 0, 300, 100);

QPalette pal = QPalette();

// set black background
// Qt::black / "#000000" / "black"
pal.setColor(QPalette::Window, Qt::black);


Using Style Sheet

Warning: Function setStyleSheet is particularly useful for demonstration purposes, where you want to show Qt's styling capabilities. Real applications should avoid it and use one consistent GUI style instead. As applicable to setStyle too.

The style sheet contains a textual description of customizations to the widget's style, as described in the Qt Style Sheets document.

m_myWidget = new QWidget(this);
m_myWidget->setGeometry(0, 0, 300, 100);

Note: If you subclass a custom widget from QWidget, then in order to use the StyleSheets you need to provide a paintEvent to the custom widget :

void CustomWidget::paintEvent(QPaintEvent* event)
    QStyleOption opt;
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);


Both ways to change the background color of QWidget have been successfully built using Qt SDK 1.1 and tested on Symbian devices.