QT讀取csv檔案並且繪製折線圖
阿新 • • 發佈:2018-12-17
void MainWindow::readcsvfile() //讀取csv { QFile csvFile("C:/Users/Administrator/Desktop/Demo/0702.CSV"); QStringList csvList; csvList.clear(); if (csvFile.open(QIODevice::ReadWrite)) //對csv檔案進行讀寫操作 { QTextStream stream(&csvFile); while (!stream.atEnd()) { csvList.push_back(stream.readLine()); //儲存到List當中 } csvFile.close(); } else { QMessageBox::about(NULL, "csv檔案", "未開啟該檔案!"); } int i = 0; Q_FOREACH(QString str, csvList) //遍歷List { i = i + 1; QStringList valsplit = str.split(","); //分隔字串 if(i > 2) { //得到深度、聲速、溫度 QString depth = valsplit[0]; QString sonicvelocity = valsplit[1]; QString temperature = valsplit[2]; double depthvalue = depth.toDouble(); double sonicvalue = sonicvelocity.toDouble(); double tempvalue = temperature.toDouble(); //Q//MessageBox::warning(NULL, "dd", QString::number(tempvalue)); QPointF point; point.setX(depthvalue); point.setY(sonicvalue); QPointF point2; point2.setX(depthvalue); point2.setY(tempvalue + 1510); vectors.append(point); vector2.append(point2); } } } void MainWindow::lineChart() //繪製圖 { //設定X,Y標題 ui->qwtPlot->setAxisTitle(QwtPlot::xBottom, QString::fromLocal8Bit("深度(m)")); ui->qwtPlot->setAxisTitle(QwtPlot::yLeft, QString::fromLocal8Bit("聲速(m/s)")); ui->qwtPlot->setAxisTitle(QwtPlot::yRight, QString::fromLocal8Bit("溫度(°C)")); ui->qwtPlot->enableAxis(QwtPlot::yRight,true); ui->qwtPlot->setAxisScale(QwtPlot::yLeft,1538,1540,0.2); ui->qwtPlot->setAxisScale(QwtPlot::xBottom,0,30,2); ui->qwtPlot->setAxisScale(QwtPlot::yRight,28,30,0.2); //ui->qwtPlot->set //構造麴線資料 QwtPointSeriesData* series = new QwtPointSeriesData(vectors); //設定網格 QwtPlotGrid* grid = new QwtPlotGrid(); grid->setPen(QColor(222, 222, 222), 1); grid->attach(ui->qwtPlot); //create plot item QwtPlotCurve* curve1 = new QwtPlotCurve(QString::fromLocal8Bit("聲速")); //設定資料 curve1->setData(series); //設定畫筆顏色==就是影象顏色 curve1->setPen(QColor(255, 0, 0), 2, Qt::SolidLine); //使曲線更光滑 curve1->setCurveAttribute(QwtPlotCurve::Fitted, true); //把曲線附加到qwtPlot上 curve1->attach(ui->qwtPlot); //新增溫度-深度曲線 //構造麴線資料 QwtPointSeriesData* series2 = new QwtPointSeriesData(vector2); //create plot item QwtPlotCurve* curve2 = new QwtPlotCurve(QString::fromLocal8Bit("溫度")); //設定資料 curve2->setData(series2); //設定畫筆顏色=影象顏色 curve2->setPen(QColor(127, 222, 335), 2, Qt::SolidLine); //使曲線更光滑 curve2->setCurveAttribute(QwtPlotCurve::Fitted, true); //把曲線附加到qwtPlot上 curve2->attach(ui->qwtPlot); //設定圖例 QwtLegend *legend = new QwtLegend; legend->setDefaultItemMode(QwtLegendData::ReadOnly); ui->qwtPlot->insertLegend(legend,QwtPlot::BottomLegend);//插入圖例 ui->qwtPlot->replot(); ui->qwtPlot->show(); }
需要第三方庫QWT