如何设置QLabel
的文本颜色和背景颜色?
发布于 2012-07-20 07:41:27
您可以使用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,颜色角色部分
发布于 2011-07-30 00:59:18
我添加这个答案是因为我认为它对任何人都有用。
我遇到了在绘画应用程序中为颜色显示标签设置RGBA颜色(即具有Alpha值的透明度的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+"); }")
请注意,在False
中设置的setAutoFillBackground()
不会使其工作。
致以敬意,
发布于 2011-08-04 07:03:26
唯一对我有效的就是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);
}
https://stackoverflow.com/questions/2749798
复制相似问题