项目中经常使用加载图片:
常用有两种方式:
1.使用 QWidget 加载图片:
效果:
样例源码:
int pict_H = ui->widgetImage->height();int pict_W = ui->widgetImage->width();ui->widgetImage->setFixedSize( pict_W ,pict_H);QPixmap pixmap("C:/Users/A013237/Pictures/volume_2024623184252.png");QPalette palette;palette.setBrush(this->backgroundRole(), QBrush(pixmap.scaled( // 缩放背景图.ui->widgetImage->size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation)));// this->setPalette(palette);ui->widgetImage->setAutoFillBackground(true);ui->widgetImage->setPalette(palette);ui->widgetImage->show();
2.使用 QLabel 加载图片:
QLabel *label = new QLabel(&window);// 加载图片,替换为你的图片路径QPixmap pixmap("path_to_your_image.jpg");// 如果图片不在指定路径或尺寸问题,可以调整大小或使用一个默认的图片if (pixmap.isNull()) {label->setText("无法加载图片");} else {label->setPixmap(pixmap);label->setScaledContents(true); // 自动缩放以适应标签大小}// 在窗口中居中显示QLabellabel->setGeometry(0, 0, window.width(), window.height());
3. 加载 loading gif 图片
效果:
源码样例:
#ifndef WAITING_H
#define WAITING_H#include <QWidget>
#include <QLabel>
#include <QMovie>namespace Ui {
class Waiting;
}class Waiting : public QWidget
{Q_OBJECTpublic:explicit Waiting(QWidget *parent = nullptr);~Waiting();private:QMovie *movie;QLabel *label;QLabel * tip_label;QFrame * background;private:Ui::Waiting *ui;
};#endif
cpp
#include "waiting.h"
#include "ui_waiting.h"
#include<QDebug>
Waiting::Waiting(QWidget *parent) :QWidget(parent),ui(new Ui::Waiting)
{ui->setupUi(this);this->setFixedSize(400,400);background = new QFrame(this);background->setStyleSheet("background-color:#0000;border-radius:1px;");background->setGeometry(0, 50, 400,400);label = new QLabel(background);label->setGeometry(0, 0, 400,400);movie = new QMovie(":/Resources/loading-t.gif");movie->setScaledSize(QSize(400,400));label->setScaledContents(true);label->setMovie(movie);movie->start();}Waiting::~Waiting()
{delete ui;
}
使用:
#include "waiting.h"
void MainWindow::on_pushButton_loading_clicked()
{Waiting *w = new Waiting(this);w->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);w->setWindowModality(Qt::ApplicationModal);w->move(880,450);w->show();}