如何在QT使用代码样式标签

How to style a label in QT using code

本文关键字:代码 样式 标签 QT      更新时间:2023-10-16

似乎最基本的东西都会绊倒我。

我试图在QT中设置标签的背景颜色。我知道我可以使用样式表通过右键单击它并添加:background-color: blue;或其他东西来做到这一点。这很有效。

但是如果没有GUI视图,我怎么能做到这一点呢?

我知道我可以添加

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

在mainwindow.cpp中改变主窗口背景颜色,但是我如何用对象名称TestLabel来定位标签,以及在哪里放置代码?

I tried

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

但是这打乱了我的程序。它可以编译,但不能按预期执行。

您可以使用ID选择器语法:

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

这将针对对象名称为TestLabel的特定QLabel

标签也可以使用setStyleSheet():

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