您的位置:首页 > 编程语言 > Qt开发

Qt 如何 给Widget设置背景图片

2010-08-24 21:50 567 查看
方法一:
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: