如何设置QLabel的文本和背景颜色?


当前回答

最好的和推荐的方法是使用Qt样式表。文档:Qt 5样式表,Qt 6样式表。

要改变一个QLabel的文本颜色和背景颜色,下面是我要做的:

QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");

您也可以避免使用Qt样式表,并更改QLabel的QPalette颜色,但在不同的平台和/或样式上可能会得到不同的结果。

正如Qt文档所述:

使用QPalette并不能保证适用于所有样式,因为样式作者受到不同平台的指导方针和本机主题引擎的限制。

但是你可以这样做:

 QPalette palette = ui->pLabel->palette();
 palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
 palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
 ui->pLabel->setPalette(palette);

但正如我所说,我强烈建议不要使用调色板,而是使用Qt样式表。

其他回答

关于任何小部件的颜色设置任何特性的最佳方法是使用QPalette。

找到你要找的最简单的方法是打开Qt Designer,设置QLabel的面板,并检查生成的代码。

对我来说唯一有用的就是html。

我发现这比任何程序化的方法都要容易得多。

下面的代码根据调用者传递的参数更改文本颜色。

enum {msg_info, msg_notify, msg_alert};
:
:
void bits::sendMessage(QString& line, int level)
{
    QTextCursor cursor = ui->messages->textCursor();
    QString alertHtml  = "<font color=\"DeepPink\">";
    QString notifyHtml = "<font color=\"Lime\">";
    QString infoHtml   = "<font color=\"Aqua\">";
    QString endHtml    = "</font><br>";

    switch(level)
    {
        case msg_alert:  line = alertHtml % line; break;
        case msg_notify: line = notifyHtml % line; break;
        case msg_info:   line = infoHtml % line; break;
        default:         line = infoHtml % line; break;
    }

    line = line % endHtml;
    ui->messages->insertHtml(line);
    cursor.movePosition(QTextCursor::End);
    ui->messages->setTextCursor(cursor);
}

这台工作得很完美

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

方法返回所选颜色。 您可以使用样式表更改标签颜色

你可以使用QPalette,但是你必须设置setAutoFillBackground(true);启用背景色

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

它在Windows和Ubuntu上运行良好,我还没玩过其他任何操作系统。

注:详情请参阅QPalette,颜色角色部分

最好的和推荐的方法是使用Qt样式表。文档:Qt 5样式表,Qt 6样式表。

要改变一个QLabel的文本颜色和背景颜色,下面是我要做的:

QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");

您也可以避免使用Qt样式表,并更改QLabel的QPalette颜色,但在不同的平台和/或样式上可能会得到不同的结果。

正如Qt文档所述:

使用QPalette并不能保证适用于所有样式,因为样式作者受到不同平台的指导方针和本机主题引擎的限制。

但是你可以这样做:

 QPalette palette = ui->pLabel->palette();
 palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
 palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
 ui->pLabel->setPalette(palette);

但正如我所说,我强烈建议不要使用调色板,而是使用Qt样式表。