This article will use QT to implement a simple dynamic real-time curve . In the future, the data can be collected and made into a visualized curve.
renderings
1. After creating the project, add charts to the .Pro file
2. In the design, drag a Graphics View , and then promote it to QChartView
3. Add header files and namespaces
4. Create table
//创建表 void MainWindow::CreatCharts(){ QChart *qchart = new QChart; //把chart放到容器里 ui->graphicsView->setChart(qchart); //设置抗锯齿 ui->graphicsView->setRenderHint(QPainter::Antialiasing); //创建两条线 QLineSeries *ser0 = new QLineSeries; QLineSeries *ser1 = new QLineSeries; //设置名字 ser0->setName("ser0"); ser1->setName("ser1"); //放入charts里 qchart->addSeries(ser0); qchart->addSeries(ser1); //创建x坐标 QDateTimeAxis *QaX = new QDateTimeAxis; //格式 QaX->setFormat("hh:mm:ss"); QaX->setTickCount(10); QaX->setTitleText("time"); //创建y坐标 QValueAxis *QaY = new QValueAxis; //设置范围 QaY->setRange(-1,1); QaY->setTickCount(6); //将线条放入表中 qchart->setAxisX(QaX,ser0); qchart->setAxisY(QaY,ser0); qchart->setAxisX(QaX,ser1); qchart->setAxisY(QaY,ser1); }
5. Current effect
6. Next, draw the curve and create the QTimer class
7. Create a timer and slot function, and refresh the data once every 1s
8. Data update
//数据更新 void MainWindow::RefreshTime_Slot(){ //获取当前时间 QDateTime currentTime = QDateTime::currentDateTime(); //获取随机数 qsrand(QTime::currentTime().second()); int rand = qrand()%100;//获取0~10之间的数 //获取初始化的qchart QChart *qchart =(QChart *)ui->graphicsView->chart(); //获取之前的ser QLineSeries *ser0 = (QLineSeries *)ui->graphicsView->chart()->series().at(0); QLineSeries *ser1 = (QLineSeries *)ui->graphicsView->chart()->series().at(1); //更新数据 ser0->append(currentTime.toMSecsSinceEpoch(),cos(rand)); ser1->append(currentTime.toMSecsSinceEpoch(),sin(rand)); qchart->axisX()->setMin(QDateTime::currentDateTime().addSecs(-1*30)); qchart->axisX()->setMax(QDateTime::currentDateTime().addSecs(1*30)); ui->label->setText(QTime::currentTime().toString("hh:mm:ss")); }