使用的控件
QLabel
QLineEdit
QPushButton
在Forms文件下进入ui文件
设置好三个控件
用法:
代码部分
先申明好函数,在Headers文件里面.h文件中申明
//先申明
private:
void open3picture();
private slots:
void on_btnOpen_clicked();
在.cpp文件中
/*打开目录选择文件
* : 图片路径(可更改)
*(*.png *.jpg) :图片格式
*注意:在创建函数的时候 用到控件时,必须与控件名字一模一样
*/
//使用智能指针
void Widget::open3picture(){
QString config_path = qApp->applicationDirPath() +"/config/setting.ini";
std::unique_ptr<QSettings> pIniSet(new QSettings(config_path,QSettings::IniFormat));
QString lastPath = pIniSet->value("/LastPath/path").toString();
if(lastPath.isEmpty()){
lastPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);//设置默认打开位置为C盘图片
}
QString filname = QFileDialog::getOpenFileName(this,"请选择图片",lastPath,"图片(*.png *.jpg);;");
if(filname.isEmpty()){
return ;
}
ui->lineEdit_path->setText(filname);
QPixmap *pix = new QPixmap(filname);
//缩放使图片自适应
pix->scaled(ui->labei_image->size(),Qt::KeepAspectRatio);
ui->labei_image->setScaledContents(true);
//获得路径
ui->labei_image->setPixmap(*pix);
delete (pix);
pix = nullptr;
int end = filname.lastIndexOf("/");
QString _path = filname.left(end);
pIniSet->setValue("/LastPath/path",_path);
}
void Widget::on_btnOpen_clicked(){
open3picture();
}
后面即可运行。