题
我如何设置文本和背景的颜色 QLabel
?
解决方案
最好和推荐的方法是使用 QT样式表.
更改文本的颜色和背景颜色 QLabel
, ,这是我要做的:
QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
您也可以避免使用QT样式表并更改 QPalette
你的颜色 QLabel
, ,但是您可能会在不同的平台和/或样式上获得不同的结果。
如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颜色,具有透明度的Alpha值),用于我的绘画应用程序中的颜色显示标签。
当我遇到第一个答案时,我无法设置RGBA颜色。我还尝试了类似的事情:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
在哪里 color
是RGBA颜色。
所以,我的肮脏解决方案是扩展 QLabel
和覆盖 paintEvent()
填充其边界矩形的方法。
今天,我已经打开了 qt-assistant
并阅读 样式参考属性列表. 。受损害,它的示例说明了以下内容:
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);
}
设置有关任何小部件颜色的任何功能的最佳方法是使用 qpalette.
找到所需的最简单方法是打开QT设计师并设置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