sci-guy
sci-guy

Reputation: 2584

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.

Upvotes: 0

Views: 305

Answers (2)

Edward
Edward

Reputation: 159

You can use setStyleSheet() for label too:

ui->TestLabel->setStyleSheet("background-color: blue");

Upvotes: 1

Mike
Mike

Reputation: 8355

You can use the ID selector syntax:

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

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

Upvotes: 2

Related Questions