图片浏览器逻辑
实现图片浏览器用到了前面几乎所有的知识,包括窗口部件、布局、事件、对象模型与容器类、图形视图、模型/视图编程以及多线程等。大致流程为:首先定义一个图片类,该类包含图片的路径、文件名、文件id以及获取这些变量的函数。然后定义了一个图片数组类,主要包含添加图像以及获取所有图像以及新加入图像的函数。最后通过将图片名字加入到界面左侧QDockWidget部件中的QTreeView中,通过线程将图片的预览加入界面下侧的窗口部件中。最后通过双击可查看完整图片,以及通过滚轮和鼠标等事件来对图片进行一些操作。
效果图

具体实现
utils.h
#ifndef UTILS_H
#define UTILS_H
#include<QString>
#include<string>
//string to QString
inline QString str2qstr(const std::string& str)
{
return QString::fromLocal8Bit(str.data());
}
//QString to string
inline std::string qstr2str(const QString& qstr)
{
QByteArray cdata = qstr.toLocal8Bit();
return std::string(cdata);
}
#endif // UTILS_H
image.h
#ifndef IMAGE_H
#define IMAGE_H
#include<string>
#include<vector>
using std::vector;
using std::string;
class Image
{
public:
Image() = default;
~Image() = default;
Image(const string& _path,const unsigned& _id):path_(_path),id_(_id){
//从路径中获取图像名称
auto pos = path_.find_last_of('\\') +1;
if(pos == 0)
{
pos = path_.find_last_of('/')+1;
}
name_ = path_.substr(pos,path_.length() - pos);
pos = name_.find_last_of('.');
name_ = name_.substr(0,pos);
}
//设置相机所属的id
void set_cam_id(const unsigned& _id){
cam_id_ = _id;
}
//获取路径
const string& get_path(){
return path_;
}
//获取文件名
const string& get_name(){
return name_;
}
const unsigned &get_id(){
return id_;
}
//获取相机id
const unsigned& get_cam_id(){
return cam_id_;
}
private:
string path_;
string name_;
unsigned id_;
unsigned cam_id_;
};
#endif // IMAGE_H
image_group.h
#ifndef IMAGE_GROUP_H
#define IMAGE_GROUP_H
#include"image.h"
class image_group
{
public:
image_group();
~image_group();
public:
bool addImages(const vector<string>& img_paths);
const vector<Image>& GetAllImages();
const vector<Image>& GetNewAddingImages();
private:
//所有图片数组
vector<Image> all_images_;
//新加入的图片数组
vector<Image> new_images_;
};
#endif // IMAGE_GROUP_H
image_group.cpp
#include "image_group.h"
image_group::image_group()
{
}
image_group::~image_group()
{
}
bool image_group::addImages(const vector<std::string> &img_paths)
{
new_images_.clear();
for(auto& path: img_paths)
{
all_images_.emplace_back(path,all_images_.size());
new_images_.emplace_back(path,all_images_.size());
}
return true;
}
const vector<Image> &image_group::GetAllImages()
{
return all_images_;
}
const vector<Image> &image_group::GetNewAddingImages()
{
return new_images_;
}
qimgviewwidget.h
#ifndef QIMGVIEWWIDGET_H
#define QIMGVIEWWIDGET_H
#include <QWidget>
#include<QImage>
//用于显示2D图像的窗口部件
class QImgViewWidget : public QWidget
{
Q_OBJECT
public:
explicit QImgViewWidget(QWidget *parent = nullptr);
~QImgViewWidget() = default;
//从文件路径加载图片
void SetImage(const QString& img_path);
void ResetTransform();
private:
//用来展示的image信息
QImage img_display_;
//原始pixmap信息
QPixmap pix_ori_;
//用来展示的pixmap信息
QPixmap pix_display_

本文介绍了如何使用C++和Qt库实现一个图片浏览器应用,涉及窗口部件、布局、事件、对象模型、图形视图、多线程等技术。图片浏览器通过QDockWidget和QTreeView展示图片列表,并利用线程异步加载预览图,支持双击查看全图和滚轮缩放。
最低0.47元/天 解锁文章
2054

被折叠的 条评论
为什么被折叠?



