Set the background color of QWidget in Qt

Source: Internet
Author: User

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());}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.