Set the background color of QWidget in Qt
Brief Introduction
QWidget is the base class of all user interface objects, which means you can change the background color for other subclass controls in the same way.
Three methods are described below for setting the window background in Qt.
Use QPalette to use Style Sheet to draw events
Generally, I do not need to set the window background for QSS, and it is not recommended. (Here is the window, if it is a sub-part, of course ). The window uses QSS to set the background. If the child part is not set in the same way, the style of the parent window is inherited by default.
Use 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 (); // set the background to black pal. setColor (QPalette: Background, Qt: black); m_pWidget-> setAutoFillBackground (true); m_pWidget-> setPalette (pal); m_pWidget-> show ();
Use Style Sheet
Use a Style sheet to set the background color. See the Qt Style sheet document.
m_pWidget = new QWidget(this);m_pWidget->setGeometry(0, 0, 300, 100);m_pWidget->setStyleSheet("background-color:black;");m_pWidget->show();
If You subclass a Widget from QWidget, you need to provide a paintEvent event for the custom Widget to be able to use the style sheet.
void CustomWidget::paintEvent(QPaintEvent *event){ Q_UNUSED(event); QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);}
Drawing event
Override paintEvent and use QPainter to draw the background.
void Widget::paintEvent(QPaintEvent *event){ Q_UNUSED(event); QPainter p(this); p.setPen(Qt::NoPen); p.setBrush(Qt::black); p.drawRect(rect());}