QT:实现图片选择器

一、效果图

二、用到的类

qApp :可以快速获取到项目目录位置。
QSettings :编写config文件,记录上次打开图片的位置,下次打开图片会从上次的位置查找图片。
QPixmap:用于图片的缩放,防止图片过小,显示区域不能完全覆盖。

三、代码

cpp 复制代码
void Widget::on_btnOpen_clicked()
{
    //找到配置文件路径
    QString config_path = qApp->applicationDirPath() + "/config/setting.ini";
    QSettings *pIniset = new QSettings(config_path,QSettings::IniFormat);

    //设置上次路径(没有就默认)
    QString last_path = pIniset->value("/LastPath/path").toString();
    if(last_path.isEmpty())
    {
        //图片标准路径
        last_path = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
    }

    QString fileName = QFileDialog::getOpenFileName(this,"打开图片",last_path,"图片(*.jpg *png)");
    if(fileName.isEmpty())
   {
       return;
   }

   //记录图片目录位置
   int end = fileName.lastIndexOf("/");
   QString _path = fileName.left(end);
   pIniset->setValue("/LastPath/path",_path);

   //改变图片大小格式
   ui->line_filepath->setText(fileName);
   QPixmap *pix = new QPixmap(fileName);
   pix->scaled(ui->lable_showpic->size(),Qt::KeepAspectRatio);
   ui->lable_showpic->setScaledContents(true);
   ui->lable_showpic->setPixmap(*pix);
   
   //释放资源
   delete pIniset;
   pIniset = nullptr;
   delete pix;
   pix = nullptr;
}
相关推荐
用户8055336980314 小时前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner14 小时前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner9 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner10 天前
DicomViewer (目录调整) 2
qt
xcyxiner10 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00612 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术12 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript