QT 顯示圖片
QT顯示圖片的方法有很多
大致為
label上顯示
直接畫出來
容器顯示
1---------------顯示gif圖片(label上顯示)
在QT中要顯示GIF圖片,不能通過單單的新增部件來完成.
還需要手動的編寫程式.
工具:QT Creator
新建一個工程,我們先在designer中,新增一個QLabel部件.
如下圖:
將QLabel拉成適當大小.
在類cpp函式中新增如下程式:
#include "widget.h"#include "ui_widget.h"
#include <QLabel>
#include <QMovie
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QMovie *movie =new QMovie("D:/Project/Qt/testclass/2.gif");
ui->label->setMovie(movie);
movie->start();
}
Widget::~Widget()
{
delete ui;
}
如下圖:
這裡要注意QMovie中的路徑名:"D:/Project/Qt/testclass/2.gif" 這裡的路徑斜槓和WINDOWS下是相反的.WINDOWS下預設是反斜槓.
編譯,執行就沒有問題,就會看到GIF檔案在播放了.
如下圖:
當文件GIF圖片顯示:
#include <QLabel>
#include <QMovie>int main(int argc,char*argv[])
{
QApplication app(argc,argv);
QLabel *label =new QLabel();
QMovie *movie =new QMovie("D:/Project/Qt/firstQT/2.gif");
label->setMovie(movie);
movie
label->show();
return app.exec();
}
2-------------------------label上顯示圖片------------------
把你的label.png放到工程目錄頂層,直接
QPixmap pixmap("label.png");
ui->title_label->setPixmap(pixmap);
ui->title_label->show();
---
可以直接:
label->setPixmap(QPixmap("./pic.jpg"));
或者:
QImage *image= new QImage("./pic.jpg");
label->setPixmap(QPixmap::fromImage(image));
再或者在中途換某個影象的話:
QImage *image= new QImage("./pic1.jpg");
label->setPixmap(QPixmap::fromImage(image));
...........
image->load("./pic2.jpg");
3----------直接畫出圖片-------------------------
voidlogindlg::paintEvent(QPaintEvent*)
{
QPainterpainter(this);
QPixmappix;
pix.load("D:/QT/login/login/images/delta.png");
painter.drawPixmap(0,0,100,33,pix);
//painter.drawLine(0,0,100,100);
}
4-----------程式啟動時的圖片
QApplication app(argc, argv);QSplashScreen *splash = new QSplashScreen;
splash->setPixmap(QPixmap(":/images/splash.png"));//設定圖片
splash->show();//顯示圖片
Qt::Alignment topRight = Qt::AlignRight | Qt::AlignTop;
splash->showMessage(QObject::tr("Setting up the main window..."),topRight, Qt::white);//顯示資訊
MainWindow mainWin;
splash->showMessage(QObject::tr("Loading modules..."),
topRight, Qt::white); //顯示資訊
loadModules();
splash->showMessage(QObject::tr("Establishing connections..."),
topRight, Qt::white); //顯示資訊
establishConnections();
mainWin.show();
splash->finish(&mainWin);//圖片一直顯示到mainWin載入完成
delete splash;//釋放空間,節省記憶體
return app.exec(); 首先你得載入一張能顯示透明的圖片,jpg格式肯定是不行的,一般都是png
還有不同的部件載入圖片的方法也不太相同,比如:
QLabel載入圖片:
C/C++ code
QString strPath=imagePath.value(day); //圖片路徑
QPixmap pix(strPath);
dayLabel->setPixmap(pix);
QPushButton載入圖片:
C/C++ code
button->setIcon(QIcon("toolbutton.png"));
button->setIconSize(QSize(48, 48));
其中setIconSize函式是用來擷取圖片的顯示區域,如果沒有該函式,該圖片是被縮放的放到圖片上
用調色盤載入圖片:
C/C++ code
QPalette p = palette();
p.setBrush(QPalette::Button, QBrush(QPixmap("toolbutton.png")));
setPalette(p);
另外實現按鈕的透明:
C/C++ code
button->setFlat(true);
還有就是用繪製事件函數了:
C/C++ code
QPixmap arrayImage("/home/image/array.png"); //圖片路徑
QRect arrayRect(0,0,50,50); //擷取圖片區域
QPainter painter;
painter.drawPixmap(QPoint(100,100),arrayImage,arrayRect); //列印圖片