Qt 如何 給Widget設置背景圖片

方法一:

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);

 

方法三:利用QPainterdrawPixmap函數,這種方法只能用在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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章