Qt set QWidget background color

Briefly

QWidget is the base class for all user interface objects, which means that the background color can be changed in the same way for other subclassed controls.

There are three methods for setting the window background in Qt.

  1. Using QPalette
  2. Using Style Sheets
  3. drawing event

Generally I don't use QSS to set the window background, nor do I recommend it. (This is for windows and of course if it's a child widget). Because after the window uses QSS to set the background, if the child component is not set in the same way, it will inherit the style of the parent window by default.

Using QPalette

Use QPalette to set the background color

m_pWidget = new QWidget(this);
m_pWidget->setGeometry(0, 0, 300, 100);
QPalette pal(m_pWidget->palette());

//设置背景黑色
pal.setColor(QPalette::Background, Qt::black);
m_pWidget->setAutoFillBackground(true);
m_pWidget->setPalette(pal);
m_pWidget->show();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Using Style Sheets

Use style sheets to set the background color, you can refer to: Qt Style Sheets documentation

m_pWidget = new QWidget(this);
m_pWidget->setGeometry(0, 0, 300, 100);
m_pWidget->setStyleSheet("background-color:black;");
m_pWidget->show();
  • 1
  • 2
  • 3
  • 4

Regarding subclassing QWidget, there is a paragraph in the helper:

// If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
void CustomWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

If you want to subclass a QWidget, in order to be able to use the style sheet, you need to provide the paintEvent event. This is because QWidget's paintEvent() is empty, and the style sheet is drawn into the window through paint.

Warning: Make sure subclassed QWidget defines the Q_OBJECT macro.

drawing event

Override paintEvent and use QPainter to paint the background.

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter p(this);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRect(rect());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324734225&siteId=291194637