Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set QWidget background color?

Tags:

The line w.setBackgroundRole(QPalette.Base) in the code below has no effect. Why? How do I fix that?

import sys from PySide.QtCore import * from PySide.QtGui import *  app = QApplication(sys.argv) w = QWidget() w.setBackgroundRole(QPalette.Base) w.show() app.exec_() 
like image 344
Johan Råde Avatar asked Sep 29 '12 18:09

Johan Råde


People also ask

How to set background color in Qt widget?

Show activity on this post. QWidget *widget = new QWidget(); QCheckBox *checkBox = new QCheckBox(); QHBoxLayout *layout = new QHBoxLayout(widget); layout->addWidget(checkBox); layout->setAlignment(Qt::AlignCenter); layout->setContentsMargins(0, 0, 0, 0); widget->setLayout(layout); table->setCellWidget(0, 0, widget);

How do I change the background color of Qframe?

ui->frame->setStyleSheet(""); ui->frame->setStyleSheet("background-color: rgb(255,255,255)");

How do I change the color of my text in Qt?

The best and recommended way is to use Qt Style Sheet. Docs: Qt 5 Style Sheet, Qt 6 Style Sheet. To change the text color and background color of a QLabel , here is what I would do : QLabel* pLabel = new QLabel; pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");


2 Answers

You need to call setAutoFillBackground(True) on the widget. By default, a QWidget doesn't fill its background.

For more information, see the documentation for the setAutoFillBackground property.

If you want to use an arbitrary background color, you need to modify the widget's palette instead:

p = w.palette() p.setColor(w.backgroundRole(), Qt.red) w.setPalette(p) 
like image 182
jmk Avatar answered Sep 28 '22 04:09

jmk


you can also use setStyleSheet for example:

w.setAttribute(Qt.Qt.WA_StyledBackground, True) w.setStyleSheet('background-color: red;') 
like image 45
Mohammad Nazari Avatar answered Sep 28 '22 02:09

Mohammad Nazari