Scientized Scientized - 16 days ago 5
C++ Question

How to style a label in QT using code

Seems like the most basic things trip me up.

I am trying to set the background color of a label in QT. I know I can do this using style sheets by right clicking it and adding:

background-color: blue;
or something. And that works great.

But how can I do this without the GUI view.

I know I can add

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


in the mainwindow.cpp to change the main window background color, but how can I target a label with object name TestLabel, and where to place the code?

I tried

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


But that messes up my program. It compiles, but does not do as intended.

Answer

You can use the ID selector syntax:

setStyleSheet("QLabel#TestLabel { background-color: blue }");

This will target the specific QLabel whose object name is TestLabel.

Comments