如何设置QWidget的背景颜色

来源:互联网 发布:ubuntu tftp-hpa配置 编辑:程序博客网 时间:2024/05/17 09:38

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 backgroundPal.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 theQt 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);}



0 0
原创粉丝点击