Qt设置背景图片方法
本文主要介紹三種Qt設置背景圖片的方法:
1、QPalette
2、重寫paintEvent
3、設置Qss(Qt style sheet)
1、QPalette
(1)示例
//.cppthis->resize(450,700);QPalette pa(this->palette());QImage img = QImage(":/img/01.jpg");img = img.scaled(this->size());QBrush *pic = new QBrush(img);pa.setBrush(QPalette::Window,*pic);//this->setAutoFillBackground(true);this->setPalette(pa);QPalette主要通過void QPalette::setBrush (?ColorRole?role, const?QBrush?&?brush?);函數來設置背景圖片,其中ColorRole設置為QPalette::window(具體信息查看QPalette的講解)。當設置具有父窗體的窗體背景時,需要加上setAutoFillBackground(true)來顯示背景。
(2)結果圖
2、重寫paintEvent
所有QWidget的子類都繼承了QWidget中的虛函數:[virtual protected] void QWidget::paintEvent(QPaintEvent *event)。在新的窗體中通過對改虛函數進行重寫,即可完成對窗體的背景進行設置。
(1)示例
//.cpp#include "pain.h" #include <QPainter> #include <QPixmap> #include "palette.h"Pain::Pain(QWidget *parent) : QWidget(parent) {this->resize(450,700);this->setWindowTitle("PainEvent"); }void Pain::paintEvent(QPaintEvent *event) {QPainter *painter = new QPainter(this);QPixmap pic = QPixmap(":/img/03.jpg");//pic = pic.scaled(this->width(),this->height());painter->drawPixmap(0,0,this->width(),this->height(),pic);}在本例中,重寫paintEvent事件時使用QPainter類的 void QPainter::drawPixmap(int x, int y, int w, int h, const QPixmap &pixmap, int sx, int sy, int sw, int sh)方法對窗體的背景進行設置。
(2)結果圖
3、設置Qss
Qss使用Qt開發的一種類似于Css的語法機制,能夠設置各種樣式的窗體。窗體通過使用void?setStyleSheet(const QString &sheet)來設置與 字符串sheet相對應的樣式。具體的Qss語法機制可查看幫助文檔(Qt style sheet)。
(1)示例
//.cpp#include "setstyle.h" #include "pain.h" #include <QFrame>SetStyle::SetStyle(QFrame *parent) : QFrame(parent) {this->resize(450,700);this->setWindowTitle("Qss");this->setStyleSheet("QFrame{background-image:url(:/img/02.jpg)}"); }(2)結果圖
4、三種方法簡單比較
使用三種方法都可以設置背景圖片,但是當窗體大小變化時,背景圖片的覆蓋方式會隨著變化。
(1)QPalette設置的背景圖片會重疊覆蓋,如:
?
(2)paintEvent設置的圖片會進行拉伸覆蓋窗體,如:
(3)而設置Qss方式上面兩種覆蓋方式都可實現。
? ? ? ? ? ?當Qss設置為? ?background-image:url(:/img.jpg)? 則完成重疊式覆蓋
? ? ? ? ? ??當Qss設置為? ?border-image:url(:/img.jpg)? 則完成拉伸式覆蓋
?
本文是自己的學習筆記,可能不完全正確,僅供參考!
? ? ? 參考連接:1、https://wenku.baidu.com/view/f5cdfdeaaeaad1f346933f27
? ? ? ? ? ? ? ? ? ? ? ? ?2、https://blog.csdn.net/qq_25800311/article/details/80874757
?
?
?
總結
以上是生活随笔為你收集整理的Qt设置背景图片方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ♥数据库课程设计之《学生成绩管理系统》♥
- 下一篇: IO那些事01-IO总述和文件描述符