Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1811063
  • 博文数量: 496
  • 博客积分: 12043
  • 博客等级: 上将
  • 技术积分: 4778
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 14:26
文章分类

全部博文(496)

文章存档

2014年(8)

2013年(4)

2012年(181)

2011年(303)

2010年(3)

分类: C/C++

2011-11-30 16:55:27

方法一:

1.在要换背景的类的构造函数中装载一个图片,变量要为全局的,接下来会用到

    _image.load("image/image_background");
    setAutoFillBackground(true);   // 这个属性一定要设置
    QPalette pal(palette());
    pal.setBrush(QPalette::Window, QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio,
                        Qt::SmoothTransformation)));
    setPalette(pal);


2.实现resizeEvent函数,在里面画背景
void Example::resizeEvent(QResizeEvent *event) 

{
    QWidget::resizeEvent(event);
    QPalette pal(palette());
    pal.setBrush(QPalette::Window,QBrush(backgroundImage.scaled(event->size(), Qt::IgnoreAspectRatio,Qt::SmoothTransformation)));
    setPalette(pal);
}

 

方法二:利用QPalette

利用QPalette,既可以将背景图设置部分话在paintEvent()函数中,也可以将它放在构造函数中。如下所示我所使用的一个程序片断:

QPalette pal;

  QString filename = QDir::currentPath()+ "/image/1.bmp";

  QPixmap pixmap(filename);

  pal.setBrush(QPalette::Window,QBrush(pixmap));

  setPalette(pal);

 或者

QPixmap pixmap(":/img/aa.bmp");

QPalette palette;

palette.setBrush(backgroundRole(), QBrush(pixmap));

setPalette(palette);

 

首先设置autoFillBackground属性为真

然后定义一个QPalette对象

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

最后设置QWidget对象的Palette

QWidget *widget = new QWidget;

widget->setAutoFillBackground(true);

QPalette palette;

palette.setColor(QPalette::Background, QColor(192,253,123));

//palette.setBrush(QPalette::Background, QBrush(QPixmap(":/background.png")));

widget>setPalette(palette);

 

方法三:利用QPainter的drawPixmap函数,这种方法只能用在paintEvent()函数中,

如下所示为我所使用的一个程序片断:

  QPixmap pixmap(":/new/prefix1/image/1.bmp");

  painter.drawPixmap(pixmap.rect(),pixmap);

 

其他参考:

 

给widget设置背景图片
a、for Qt3:
//对于继承QScrollView:
QListView* lv = new QListView();
lv->setStaticBackground( true );
lv->setPaletteBackgroundPixmap( QPixmap("logo.png") );
//对于QTextEdit:
QTextEdit* edit =...
QBrush brush;
brush.setPixmap( QPixmap("logo.png") );
edit->setPaper( brush );
edit->setBackgroundOrigin( QWidget::WindowOrigin );
//对于一般的QLabel等:
QLabel *label = ...
label->setPaletteBackgroundPixmap( QPixmap("logo.png") );
label->setBackgroundOrigin( QWidget::WindowOrigin );

b、for Qt4:
QListWidget* lv = new QListWidget( 0 );
QPalette palette;
palette.setBrush(QPalette::Base, QBrush(QPixmap("logo.png")));
lv->setPalette(palette);
阅读(817) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~