Qt Change QWidget Color

Qt Change QWidget Color

I am write this tutorial because after long periode use Qt, I am rarely use Qt feature color. If use Qt Designer, we can can create Qt Change QWidget Color with QPallete or QStyleSheet method. This is a picture how Qt Change QWidget Color with Qt Designer :

Qt change QWidget color with QPallete
Qt change QWidget color with QPallete


But, if you want to Qt Change QWidget Color with QStyleSheet, you can use StyleSheet editor in Qt Designer like this picture :

QWidget change color with stylesheet
Qt change QWidget color with QStyleSheet

This is an example how Qt Change QWidget color in our code. If you want to use QPallete method, you can use this sample method to change your QWidget color (in sample code, I want to change QLabel color) :

QPalette pal = ui.label_pallete->palette();
pal.setColor(ui.label_pallete->backgroundRole(), Qt::red);
pal.setColor(ui.label_pallete->foregroundRole(), Qt::blue);
ui.label_pallete->setPalette(pal);
ui.label_pallete->setAutoFillBackground(true);

From this example, we want to change QLabel color at background with red color and foreground color with blue. The simple method Qt change QWidget color is use QStyleSheet. This is a method how to change QLabel color with QStyleSheet method :

ui.label_stylesheet->setStyleSheet("QLabel { background-color: rgb(205, 215, 255) ; color : blue; }");

or use this method :

ui.label_stylesheet->setStyleSheet("QLabel { background-color: red; color : blue; }");

This is a simple output from my code about how Qt Change QWidget Color with QPallete and QStyleSheet method :

Qt QWidget Change Color
Qt QWidget Change Color

We can use Qt Color defined (red, blue, black, etc) or use RGB value. I think the simple method Qt Change QWidget Color is use QStyleSheet. How about you, are you have any method how Qt Change QWidget Color ?

You can download the complete source code Qt Change QWidget Color at here.

Add a Comment

Your email address will not be published. Required fields are marked *