1.关键代码:
1 QChart *QcharWidget::createLineChart() const 2 { 3 QChart *chart = new QChart(); 4 chart->setTitle("Line chart"); 5 6 DataTable::const_iterator it = m_dataTable.constBegin(); 7 while (it != m_dataTable.constEnd()) { 8 QLineSeries *series = new QLineSeries(); 9 series->setName(it.key()); 10 foreach(auto it_data,it.value()){ 11 series->append(it_data.first, it_data.second); 12 } 13 chart->addSeries(series); 14 ++it; 15 } 16 createCommonAxis(chart); 17 return chart; 18 } 19 20 void QcharWidget::createCommonAxis(QChart *chart, QStringList *categories) const 21 { 22 //X 23 QAbstractAxis* axisX = nullptr; 24 if(categories!=nullptr) 25 { 26 axisX = new QBarCategoryAxis(); 27 qobject_cast<QBarCategoryAxis*>(axisX)->append(*categories); 28 }else{ 29 axisX = new QDateTimeAxis(); 30 qobject_cast<QDateTimeAxis*>(axisX)->setFormat("MM-dd"); 31 } 32 chart->addAxis(axisX, Qt::AlignBottom); 33 34 //Y 35 QValueAxis *axisY = new QValueAxis; 36 axisY->setRange(0,100000); 37 axisY->setLabelFormat("%d"); 38 chart->addAxis(axisY,Qt::AlignLeft); 39 40 // 41 foreach(auto serier,chart->series()){ 42 serier->attachAxis(axisX); 43 serier->attachAxis(axisY); 44 } 45 }
2.效果
GIF:
3.数据来源
4.完整源代码:
https://github.com/SanSuiWanTong/QT_ToolBox