qt 之 How to Change the Background Color of QWidget

Using the Palette

The first example demonstrates how to change the background color using QPalette [qt-project.org]

  1. m_pMyWidget  =  new  QWidget ( this ) ;
  2. m_pMyWidget -> setGeometry ( 0 , 0 , 300 , 100 ) ;
  3. QPalette Pal (palette ( ) ) ;
  4. // set black background
  5. Pal. setColor ( QPalette :: Background ,  Qt :: black ) ;
  6. m_pMyWidget -> setAutoFillBackground ( true ) ;
  7. m_pMyWidget -> setPalette (Pal ) ;
  8. m_pMyWidget -> show ( ) ;

Using Style Sheet

The style sheet contains a textual description of customizations to the widget’s style, as described in the Qt Style Sheets document [qt-project.org].

  1. m_pMyWidget  =  new  QWidget ( this ) ;
  2. m_pMyWidget -> setGeometry ( 0 , 0 , 300 , 100 ) ;
  3. m_pMyWidget -> setStyleSheet ( "background-color:black;" ) ;
  4. 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^3 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 :

  1. void CustomWidget :: paintEvent ( QPaintEvent  * )
  2.   {
  3.       QStyleOption opt ;
  4.      opt. init ( this ) ;
  5.       QPainter p ( this ) ;
  6.      style ( ) -> drawPrimitive ( QStyle :: PE_Widget ,  &opt ,  &p ,  this ) ;
  7.   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值