QCustomPlot提供了四种常用的save接口,其格式如下:
saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit);
saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit);
savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit);
savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle);
首先在UI界面中创建一个按钮控件,其ObjectName为pbn_save,然后在mainwindow.cpp中写入如下代码:
bool MainWindow::on_pbn_save_clicked()
{
QString filename = QFileDialog::getSaveFileName();
if( filename == "" ){
QMessageBox::information(this,"fail","保存失败");
return false;
}
if( filename.endsWith(".png") ){
QMessageBox::information(this,"success","成功保存为png文件");
return ui->customPlot->savePng( filename, ui->customPlot->width(), ui->customPlot->height() );
}
if( filename.endsWith(".jpg")||filename.endsWith(".jpeg") ){
QMessageBox::information(this,"success","成功保存为jpg文件");
return ui->customPlot->saveJpg( filename, ui->customPlot->width(), ui->customPlot->height() );
}
if( filename.endsWith(".bmp") ){
QMessageBox::information(this,"success","成功保存为bmp文件");
return ui->customPlot->saveBmp( filename, ui->customPlot->width(), ui->customPlot->height() );
}
if( filename.endsWith(".pdf") ){
QMessageBox::information(this,"success","成功保存为pdf文件");
return ui->customPlot->savePdf( filename, ui->customPlot->width(), ui->customPlot->height() );
}
else{
//否则追加后缀名为.png保存文件
QMessageBox::information(this,"success","保存成功,已默认保存为png文件");
return ui->customPlot->savePng(filename.append(".png"), ui->customPlot->width(), ui->customPlot->height() );
}
}
对上述代码进行简单介绍,首先定义QString类型的filename存放用户想要保存的文件名称,然后检测文件名后缀,如果是png,jpg,jpeg,bmp,pdf结尾,则图像保存为该格式,否则默认图像保存为png格式文件,并弹出相应保存成功或保存失败的提示信息。
参考:https://vimsky.com/examples/detail/cpp-ex—QCustomPlot-savePdf-method.html