Chinaunix首页 | 论坛 | 博客
  • 博客访问: 489550
  • 博文数量: 74
  • 博客积分: 750
  • 博客等级: 军士长
  • 技术积分: 1453
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-29 15:59
文章分类
文章存档

2014年(30)

2013年(8)

2012年(36)

分类: C/C++

2013-08-14 15:20:34

结合网上多篇资料整理如下,给自己和别人一个参考

方法一:

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);
    QPalettepal(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()函数中,

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

  QPixmappixmap(":/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);

基本上,图片作为背景后,都是平铺的。Qt3、Qt4对于背景图片有不同的处理方式,比较而言,Qt4对于背景图片处理要好的多。

阅读(15933) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~