如何设置QWidget的背景颜色

本文档介绍了如何使用QPalette和StyleSheet设置QWidget及其子类的背景颜色。通过设置autoFillBackground属性,定义QPalette对象并调整其背景,可以改变背景颜色。而使用Qt的StyleSheet时,需要注意默认会作用于所有子控件。通过三种不同方式限制StyleSheet的作用范围,避免影响到不希望更改的控件,如QTextEdit的例子。详细展示了如何只影响特定控件的背景,确保样式不会泄露。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Introduction

QWidget is the base class of all user interface objects which means that the same approaches for changing the background color can be used with them too.

Using the Palette

The first example demonstrates how to change the background color using QPalette

首先设置autoFillBackground属性为真

然后定义一个QPalette对象

设置QPalette对象的背景属性(颜色或图片)

最后设置QWidget对象的Palette

 
  
m_pMyWidget = new QWidget(this);
m_pMyWidget->setGeometry(0,0,300,100);
QPalette Pal(palette());
 
// set black background
Pal.setColor(QPalette::Background, Qt::black);
m_pMyWidget->setAutoFillBackground(true);
m_pMyWidget->setPalette(Pal);
m_pMyWidget->show();

Using Style Sheet

Qt的StyleSheet是很方便的一个设置各种控件风格形态的属性,但是默认的StyleSheet会作用于所有的子控件,容易带来麻烦,以下几种情况,可以限制作用范围

以QTextEdit为例,实体名为edTest

一:作用于所有子控件

  StyleSheet:  background:argb(0, 0, 0, 0%)

这样的好处是简单,坏处就是连ContextMenu也成背景透明的了,明显不是我们想要的


二:作用于此类控件

  StyleSheet: QTextEdit{background:argb(0, 0, 0, 0%)}

这样,ContextMenu是没问题了,不过这个还是可能导致StyleSheet漏到其它控件上,他的意思是把所有QTextEdit的子控件的背景设置透明


三:只作用于特定控件

  StyleSheet: QTextEdit#edTest{background:argb(0, 0, 0, 0%)}

这样就完全不会泄露了,只有edTest这个控件才会受到影响


找到这个文档真是费了很大的力气…google出来的都不是我想要的,看着文档,参考着代码终于搞定了:)


The style sheet contains a textual description of customizations to the widget's style, as described in the Qt Style Sheets document.

m_pMyWidget = new QWidget(this);
m_pMyWidget->setGeometry(0,0,300,100);
m_pMyWidget->setStyleSheet("background-color:black;");
m_pMyWidget->show();

Both ways to change the background color of QWidget have been successfully built using Qt SDK 1.1 and tested on Symbian devices.

Note: If you subclass a custom widget from QWidget, then in order to use the StyleSheets you need to provide a paintEvent to the custom widget :

void CustomWidget::paintEvent(QPaintEvent *)
{
 QStyleOption opt;
 opt.init(this);
 QPainter p(this);
 style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值