html5 label背景色,QLabel:设置文字和背景的颜色

最好的和推荐的方法是使用Qt样式表 。

要更改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);

但正如我所说,我强烈build议不要使用调色板,并去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 ,颜色angular色部分了解更多详情

我添加这个答案是因为我认为这对任何人都有用。

我在我的绘画应用程序中为彩色显示标签设置了RGBA颜色(即透明度为Alpha值的RGB颜色)的问题。

当我遇到第一个答案时,我无法设置RGBA颜色。 我也尝试过这样的事情:

myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())

其中color是RGBA颜色。

所以,我的肮脏的解决scheme是扩展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+"); }")

请注意,设置为False setAutoFillBackground()不会使其工作。

问候,

设置任何有关小部件颜色的function的最好方法是使用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 = ""; QString notifyHtml = ""; QString infoHtml = ""; QString endHtml = "
"; 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; }");

getColor()方法返回所选的颜色。 您可以使用stylesheet更改标签颜色

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值