QT:实现图片选择器

一、效果图

QT:实现图片选择器_第1张图片

二、用到的类

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

三、代码

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;
}

你可能感兴趣的:(QT,qt,开发语言)