Qt image browser

reference

Qt image browser

After the adaptive label+pixmap in Qt fills the window, it cannot be zoomed out but can only be zoomed in

Can display jpg, jpeg, png, bmp. You can drag the picture from the computer to the window and display it or open the file selection

Overload implements dragEnterEvent (drag), dropEvent (drag and drop), resizeEvent (window size change)

structure

insert image description here

ImageEye.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    imageeye.cpp

HEADERS += \
    imageeye.h

FORMS += \
    imageeye.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${
    
    TARGET}/bin
else: unix:!android: target.path = /opt/$${
    
    TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    res.qrc

main.cpp

#include "imageeye.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    ImageEye w;
    w.show();
    return a.exec();
}

imageeye.h

#ifndef IMAGEEYE_H
#define IMAGEEYE_H

#include <QMainWindow>
#include <QWidget>
#include <QSize>
#include <iostream>
#include <QPixmap>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QFileInfo>
#include <QMessageBox>
#include <QResizeEvent>
#include <QStringList>
#include <QLabel>
#include <QFileDialog>
#include <QDebug>

using namespace std;

QT_BEGIN_NAMESPACE
namespace Ui {
    
     class ImageEye; }
QT_END_NAMESPACE

class ImageEye : public QMainWindow
{
    
    
    Q_OBJECT

private:
    QPixmap pixmap;

public:
    ImageEye(QWidget *parent = nullptr);
    ~ImageEye();


    void dragEnterEvent(QDragEnterEvent *event)override;//拖进事件
    void dropEvent(QDropEvent *event)override;// 拖进放下事件
    void resizeEvent(QResizeEvent *event)override;//用于在窗口大小改变时处理事件
public slots:
    void    OnSetMediaFile(void);//载入
    void    OnClean(void);//载入

private:
    Ui::ImageEye *ui;
};
#endif // IMAGEEYE_H

imageeye.cpp

#include "imageeye.h"
#include "ui_imageeye.h"

ImageEye::ImageEye(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::ImageEye)
{
    
    
    ui->setupUi(this);
    this->setWindowTitle("图片浏览器");
    this->setWindowIcon(QIcon(":/ImageEye.jpg"));
    this->setAcceptDrops(true);//设置允许向窗口拖入图片
    this->setMinimumSize(QSize(400,300));// 设置最小值

    ui->label->setAlignment(Qt::AlignCenter);  //居中显示

    //自适应的label+pixmap充满窗口后,无法缩小只能放大
    ui->label->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored);// Ignored忽略

    // 设置拉伸因子(默认缩到最小时失效:一样大小)
    ui->verticalLayout->setStretch(10,1);

    //设置窗口布局,(此时控件会随窗口缩放)
    ui->centralwidget->setLayout(ui->verticalLayout);

    // 2.界面美化
    QPalette qplte;// 调色板
    qplte.setColor(QPalette::Window, QColor(0,0,0));// 透明
    this->setPalette(qplte);// 设置窗口部件的调色板

    ui->BtnClean->raise();//显示在最上层
    ui->BtnLoad->raise();//显示在最上层
    ui->label->lower();//显示在最下层

    connect(ui->BtnLoad, SIGNAL(clicked()), this, SLOT(OnSetMediaFile()));//载入
    connect(ui->BtnClean, SIGNAL(clicked()), this, SLOT(OnClean()));

}

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

//拖进事件
void ImageEye::dragEnterEvent(QDragEnterEvent *event)
{
    
    
    // 如果文件的后缀名是jpg、jpeg、bmp或png,则接受拖放事件,否则忽略拖放事件
    QStringList acceptedFileTypes;
    acceptedFileTypes.append("jpg");
    acceptedFileTypes.append("jpeg");
    acceptedFileTypes.append("bmp");
    acceptedFileTypes.append("png");
    // 用于检查拖放的数据是否包含URL,并且获取拖放事件中的URL数量==1
    if(event->mimeData()->hasUrls()&&event->mimeData()->urls().count()==1)
    {
    
    
        // 获取拖放事件中的第一个URL的本地文件路径
        QFileInfo file(event->mimeData()->urls().at(0).toLocalFile());
        // 检查文件的后缀名是否在接受的文件类型列表中;(获取文件的后缀名,并将其转换为小写字母)
        if(acceptedFileTypes.contains(file.suffix().toLower()))
        {
    
    
            event->acceptProposedAction();//表明用户可以在窗口部件上拖放对象[接受拖放事件的操作]
        }
    }
}
// 拖进放下事件
void ImageEye::dropEvent(QDropEvent *event)
{
    
    
    // 获取拖放事件中的第一个URL的本地文件路径
    QFileInfo file(event->mimeData()->urls().at(0).toLocalFile());

    qDebug()<<"绝对路径:"<<file.absoluteFilePath();
    //从文件中加载图片,参数file.absoluteFilePath()表示文件的绝对路径,load()返回一个bool值,表示是否加载成功
    if(pixmap.load(file.absoluteFilePath()))
    {
    
    
        // 将图片缩放到指定大小,参数ui->label->size()表示缩放的大小,Qt::KeepAspectRatio表示保持图片的宽高比,Qt::SmoothTransformation表示使用平滑缩放算法
        ui->label->setPixmap(pixmap.scaled(ui->label->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
        this->setWindowTitle(file.absoluteFilePath());
    }else
    {
    
    
        // 错误消息框
        QMessageBox::critical(this,tr("Error"),tr("The image file count not be read"));
    }
}
// 用于在窗口大小改变时处理事件
int i=0;
void ImageEye::resizeEvent(QResizeEvent *event)
{
    
    
    Q_UNUSED(event);//忽略编译器发出的警告,表明变量event未使用
    qDebug()<<"窗口大小改变:"<<i++;
    if(!pixmap.isNull())
    {
    
    
        ui->label->setPixmap(pixmap.scaled(ui->label->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
    }

}
//载入
void ImageEye::OnSetMediaFile()
{
    
    
    QFileDialog dialog(this);//文件选择窗口
    dialog.setNameFilter(tr("Images (*.jpg *.jpeg *.bmp *.png)"));// 过滤器
    dialog.setFileMode(QFileDialog::AnyFile);//设置文件模式(文件/文件夹):任意文件,无论是否存在
    QStringList fileNames;
    if (dialog.exec())
        fileNames = dialog.selectedFiles();// 存所有选择的文件

    if(!fileNames.isEmpty())
    {
    
    
        if(pixmap.load(fileNames[0]))
        {
    
    
            qDebug()<<"文件名:"<<fileNames[0];
            ui->label->setPixmap(pixmap.scaled(ui->label->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
            this->setWindowTitle(fileNames[0]);
        }
    }
}

void ImageEye::OnClean()
{
    
    
    ui->label->clear();
    this->setWindowTitle("图片浏览器");
}

imageeye.ui

insert image description here

Effect

  • start up
    insert image description here

  • run
    insert image description here

Guess you like

Origin blog.csdn.net/qq_47355554/article/details/129181887