Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a background color for the whole window of a Qt application?

Does anyone know how one would be able to set a background color for the whole window of a Qt application?

So far I am using stylesheets but can only figure out how to assign a background color to a widget such as QGroupBox or QPushButton. Basically, if I want a black background how would I make it seamless without any borders of the original background?

like image 319
bryce Avatar asked Nov 04 '09 19:11

bryce


People also ask

How do you add a background in Qt?

You can add a background image to your MainWindow by doing the following: create a QPixmap and give it the path to your image. create a QPalette and set it's QBrush with your pixmap and it's ColorRole to QPalette::Background . set your MainWindow palette to the palette you created.


2 Answers

I would simply use a Style Sheet for the whole window.

For instance, if your window is inheriting from QWidget, here is what I'm doing :

MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow) {     ui->setupUi(this);     this->setStyleSheet("background-color: black;"); } 

On my Mac, my whole application window is black (except the title bar).

EDIT : according to comment, here is a solution without using ui files and loading an external style sheet

#include <QtGui/QApplication> #include <QtGui/QMainWindow> #include <QtGui/QVBoxLayout> #include <QtGui/QPushButton> #include <QtCore/QFile>  int main(int ArgC, char* ArgV[]) { QApplication MyApp(ArgC, ArgV);  QMainWindow* pWindow = new QMainWindow; QVBoxLayout* pLayout = new QVBoxLayout(pWindow); pWindow->setLayout(pLayout);  QPushButton* pButton = new QPushButton("Test", pWindow); pLayout->addWidget(pButton);  QFile file(":/qss/default.qss"); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll());  qApp->setStyleSheet(styleSheet);  pWindow->setVisible(true); MyApp.exec(); } 

The style sheet file (default.qss) is as follow :

QWidget {   background-color: black; } 

This file is part of a resource file (stylesheet.qrc) :

<RCC>   <qresource prefix="/qss">     <file>default.qss</file>   </qresource> </RCC> 

And here is my project file :

TARGET = StyleSheet TEMPLATE = app SOURCES += main.cpp RESOURCES += stylesheet.qrc 
like image 165
Jérôme Avatar answered Sep 21 '22 19:09

Jérôme


This has worked for me:

a = new QApplication(argc, argv); QPalette pal = a->palette(); pal.setColor(QPalette::Window, Qt::white); a->setPalette(pal); 
like image 32
Dirk Eddelbuettel Avatar answered Sep 18 '22 19:09

Dirk Eddelbuettel