1. 程式人生 > 實用技巧 >Qt 讀取csv檔案並且繪製折線圖

Qt 讀取csv檔案並且繪製折線圖

 1 void MainWindow::readcsvfile() //讀取csv
 2 {
 3  QFile csvFile("C:/Users/Administrator/Desktop/Demo/0702.CSV");
 4  QStringList csvList;
 5  csvList.clear();
 6  if (csvFile.open(QIODevice::ReadWrite)) //對csv檔案進行讀寫操作
 7  {
 8   QTextStream stream(&csvFile);
 9   while (!stream.atEnd())
10  {
11  csvList.push_back(stream.readLine()); //
儲存到List當中 12 } 13 csvFile.close(); 14 } 15 else 16 { 17 QMessageBox::about(NULL, "csv檔案", "未開啟該檔案!"); 18 } 19 int i = 0; 20 Q_FOREACH(QString str, csvList) //遍歷List 21 { 22 i = i + 1; 23 QStringList valsplit = str.split(","); //分隔字串 24 if(i > 2) 25 { 26 //得到深度、聲速、溫度 27
QString depth = valsplit[0]; 28 QString sonicvelocity = valsplit[1]; 29 QString temperature = valsplit[2]; 30 double depthvalue = depth.toDouble(); 31 double sonicvalue = sonicvelocity.toDouble(); 32 double tempvalue = temperature.toDouble(); 33 //Q//MessageBox::warning(NULL, "dd", QString::number(tempvalue));
34 QPointF point; 35 point.setX(depthvalue); 36 point.setY(sonicvalue); 37 QPointF point2; 38 point2.setX(depthvalue); 39 point2.setY(tempvalue + 1510); 40 vectors.append(point); 41 vector2.append(point2); 42 } 43 } 44 } 45 46 void MainWindow::lineChart() //繪製圖 47 { 48 //設定X,Y標題 49 ui->qwtPlot->setAxisTitle(QwtPlot::xBottom, QString::fromLocal8Bit("深度(m)")); 50 ui->qwtPlot->setAxisTitle(QwtPlot::yLeft, QString::fromLocal8Bit("聲速(m/s)")); 51 ui->qwtPlot->setAxisTitle(QwtPlot::yRight, QString::fromLocal8Bit("溫度(°C)")); 52 ui->qwtPlot->enableAxis(QwtPlot::yRight,true); 53 ui->qwtPlot->setAxisScale(QwtPlot::yLeft,1538,1540,0.2); 54 ui->qwtPlot->setAxisScale(QwtPlot::xBottom,0,30,2); 55 ui->qwtPlot->setAxisScale(QwtPlot::yRight,28,30,0.2); 56 57 //ui->qwtPlot->set 58 //構造麴線資料 59 QwtPointSeriesData* series = new QwtPointSeriesData(vectors); 60 //設定網格 61 QwtPlotGrid* grid = new QwtPlotGrid(); 62 grid->setPen(QColor(222, 222, 222), 1); 63 grid->attach(ui->qwtPlot); 64 //create plot item 65 QwtPlotCurve* curve1 = new QwtPlotCurve(QString::fromLocal8Bit("聲速")); 66 //設定資料 67 curve1->setData(series); 68 //設定畫筆顏色==就是影象顏色 69 curve1->setPen(QColor(255, 0, 0), 2, Qt::SolidLine); 70 //使曲線更光滑 71 curve1->setCurveAttribute(QwtPlotCurve::Fitted, true); 72 //把曲線附加到qwtPlot上 73 curve1->attach(ui->qwtPlot); 74 //新增溫度-深度曲線 75 //構造麴線資料 76 QwtPointSeriesData* series2 = new QwtPointSeriesData(vector2); 77 //create plot item 78 QwtPlotCurve* curve2 = new QwtPlotCurve(QString::fromLocal8Bit("溫度")); 79 //設定資料 80 curve2->setData(series2); 81 //設定畫筆顏色=影象顏色 82 curve2->setPen(QColor(127, 222, 335), 2, Qt::SolidLine); 83 //使曲線更光滑 84 curve2->setCurveAttribute(QwtPlotCurve::Fitted, true); 85 //把曲線附加到qwtPlot上 86 curve2->attach(ui->qwtPlot); 87 88 //設定圖例 89 QwtLegend *legend = new QwtLegend; 90 legend->setDefaultItemMode(QwtLegendData::ReadOnly); 91 ui->qwtPlot->insertLegend(legend,QwtPlot::BottomLegend);//插入圖例 92 ui->qwtPlot->replot(); 93 ui->qwtPlot->show(); 94 }

需要第三方庫QWT

執行結果: