如何设置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,但是您必须设置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的颜色角色部分。
我添加了这个答案,因为我认为它可能对任何人都有用。
我遇到了一个问题,即在我的绘画应用程序中设置RGBA颜色(即具有透明度的RGB颜色)。当我遇到第一个答案时,我无法设置RGBA颜色。我还尝试过像以下代码一样的东西:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
其中color
是一个RGBA颜色。
因此,我的“肮脏解决方案”是扩展QLabel
并重写paintEvent()
方法填充其边界矩形。
今天,我打开了qt-assistant
并阅读了style reference properties list。幸运的是,它有一个示例,声明如下:
QLineEdit { background-color: rgb(255, 0, 0) }
这启发我做一些像下面这样的示例代码:
myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color = QtGui.QColor(233, 10, 150)
alpha = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
g = color.green(),
b = color.blue(),
a = alpha
)
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
setAutoFillBackground()
设置为False
不会使其起作用。唯一对我有效的是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);
}
<font/>
标签中放置其他一些花哨的东西(对于熟悉 HTML 的人来说更加熟悉:D),而不仅仅是颜色,因此它给您带来了更大的灵活性。 - rbaleksandar设置任何小部件颜色方面的最佳方法是使用QPalette。
查找您要查找的内容最简单的方法是打开Qt Designer,设置QLabel的调色板并检查生成的代码。
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; }");
getColor()
方法返回所选颜色。您可以使用 stylesheet
更改标签颜色。
color
属性无效。只有通过 HTML<font color="#FFFFFF">...</font>
才能设置字体颜色(在这种情况下为白色)。 - Paulo Carvalhocolor: ;
作为“重置”似乎可以做到这一点,但这是好的实践吗,还是有更好的方法? - AstroFloyd