QT中 窗口部件的 背景圖片 的設置

  方法一:

首先設置 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(":/images/background.png")));

widget->setPalette(palette);

 

 

方法二:

QPalette的方法

#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QFrame *frame = new QFrame;
frame->resize(400, 700);


QPixmap pixmap11(":/images/frame.png");

QPixmap pixmap = pixmap11 .scaled(400,700);


QPalette palette;
palette.setBrush(frame->backgroundRole(),QBrush(pixmap));
frame->setPalette(palette);
frame->setMask(pixmap.mask()); //可以將圖片中透明部分顯示爲透明的
frame->setAutoFillBackground(true);
frame->show();

return app.exec();
}

 

 

方法三:

setStyleSheet方法( 非常好用的方法 )

設置屬性使背景圖自動調整來適應控件的大小。

#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QFrame *frame = new QFrame;
frame->setObjectName("myframe");
frame->resize(400,700);
frame->setStyleSheet("QFrame#myframe{ border-image : url(:/images/frame.png)}" );
frame->show();

return app.exec();
}

注意代碼中紅線的部分,設置ObjectName,才能保證setStyleSheet只作用在我們的frame上,不影響其子控件的背景設置。之所以用border-image而不用background-image,還是上面的問題,用background-image不能保證圖片大小和控件大小一致,圖片不能完全顯示。


 



 

方法四:

paintEvent事件方法

//myframe.h文件
#ifndef MYFRAME_H
#define MYFRAME_H

#include <QWidget>
#include <QtGui>

class MyFrame : public QWidget
{
public:
MyFrame();
void paintEvent(QPaintEvent *event);
};

#endif // MYFRAME_H

//myframe.cpp文件
#include "myframe.h"

MyFrame::MyFrame()
{
}

void MyFrame::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0,0,400,700,QPixmap("images/frame.png"));
}

//main.cpp文件
#include <QApplication>
#include <QtGui>

#include "myframe.h"

int main(int argc, char *argv[])
{
QApplication app(argc,argv);

MyFrame *frame = new MyFrame;
frame->resize(400,700);
frame->show();

return app.exec();
}

這個背景圖片不隨着窗口的大小而變化,因爲它的固定大小被設置成(400,700)了。重寫QWidget的paintEvent事件,當控件發生重繪事件,比如show() 時,系統就會自動調用paintEvent函數。


轉自: http://blog.sina.com.cn/s/blog_66a133b70100x44p.html





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