在qt中实现图片的加载

(走了个弯路。用opencv显示qt图片。。。可以但没必要)

下面是常见的Qlabel加载图片

检测图片是否可以加载

QString filename = "C:\\Users\\Administrator\\Desktop\\1.png";
            QImage* img=new QImage;
            if(! ( img->load(filename) ) ) //加载图像
            {
                QMessageBox::information(this,
                                         tr("打开图像失败"),
                                         tr("打开图像失败!"));
                delete img;
                return;
            }

显示图片并利用setScaledContents(true)方法实现图片自适应label大小

ui->label_showImage->setPixmap(QPixmap::fromImage(*img));
ui->label_showImage->setScaledContents(true);

完整的mainwindow.cpp如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString filename = "C:\\Users\\Administrator\\Desktop\\6.png";
            QImage* img=new QImage;
            if(! ( img->load(filename) ) ) //加载图像
            {
                QMessageBox::information(this,
                                         tr("打开图像失败"),
                                         tr("打开图像失败!"));
                delete img;
                return;
            }
            ui->label_showImage->setPixmap(QPixmap::fromImage(*img));
            ui->label_showImage->setScaledContents(true);
}



MainWindow::~MainWindow()
{
    delete ui;
}

猜你喜欢

转载自blog.csdn.net/jianlai_/article/details/129080719