一、QCustomPlot介紹
QCustomPlot是用於繪製圖表的Qt C++繪圖庫。它提供了多種基本繪圖元素,如曲線、數據點、坐標軸、網格、標籤等,並支持實時數據可視化。它還支持豐富的交互,如縮放、平移、選擇區域、響應滑鼠事件等。
QCustomPlot的安裝也很容易,在Qt中實現安裝只需要兩步:首先,下載並解壓縮源代碼包;其次,在Qt項目中包含所需的頭文件和鏈接到共享庫。
二、繪製曲線
QCustomPlot可以很容易地繪製多個曲線。以下示例顯示如何繪製兩個簡單的曲線。
QCustomPlot customPlot;
customPlot.addGraph();
customPlot.graph(0)->setData(x, y); // x和y是數據集
customPlot.addGraph();
customPlot.graph(1)->setData(x, z); // z是第二組數據集
customPlot.replot();
要為曲線設置樣式和繪製屬性,可以使用QPen。例如,以下代碼將設置第一條曲線的顏色為紅色:
customPlot.graph(0)->setPen(QPen(Qt::red));
三、坐標軸和標籤
QCustomPlot提供了兩個主坐標軸和兩個次坐標軸。以下代碼創建了一個簡單的圖形,並在其上方添加了一個標題和標題:
QCustomPlot customPlot;
customPlot.plotLayout()->insertRow(0); // 添加一個行以放置標題
customPlot.plotLayout()->addElement(0, 0, new QCPTextElement(customPlot,
"My Plot Title", QFont("sans", 12, QFont::Bold)));
customPlot.xAxis->setLabel("x Axis Label");
customPlot.yAxis->setLabel("y Axis Label");
customPlot.addGraph();
//設置x,y坐標軸範圍
customPlot.xAxis->setRange(0, 10);
customPlot.yAxis->setRange(0, 1);
customPlot.graph(0)->setData(x, y);
customPlot.replot();
四、實時數據顯示
QCustomPlot支持實時數據可視化,即當新數據點可用時,可以將它們添加到已繪製的曲線上。以下示例顯示了如何使用QTimer添加新數據點。
// 創建定時器
QTimer dataTimer;
// 連接定時器的timeout()信號到槽函數,每個周期發射一次timeout()信號
connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
dataTimer.start(0); // 參數為0可儘可能快地執行定時器任務
數據槽函數(realtimeDataSlot())將生成新數據點並將它們添加到圖形中:
void MainWindow::realtimeDataSlot()
{
// 計算新的數據點
double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
static double lastPointKey = 0;
if (key-lastPointKey > 0.01) // 為了使數據點之間不相互重疊
{
// 生成新的x,y數據
double value0 = qSin(key*1.6)*qCos(key*1.4)*10 + qSin(key*0.6)*5;
double value1 = qSin(key*1.2)*qCos(key*0.9)*10 + qSin(key*0.2)*7.5;
// 將新數據點添加到曲線中
ui->customPlot->graph(0)->addData(key, value0);
ui->customPlot->graph(1)->addData(key, value1);
// 移動坐標軸範圍(使其保持滑動窗口效果)
ui->customPlot->xAxis->setRange(key, 8, Qt::AlignRight);
ui->customPlot->replot();
lastPointKey = key;
}
}
五、交互和事件
QCustomPlot提供了許多交互功能,例如放大、縮小、選擇區域、平移等,可以通過setInteractions函數設置。例如,以下代碼顯示如何啟用縮放和平移功能:
customPlot.setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
可以利用事件處理函數綁定一些響應滑鼠事件的操作。例如,以下代碼顯示如何按下滑鼠左鍵縮放y軸:
// 聲明一個double值,記錄滑鼠按下時y坐標軸的範圍下限
double yMin = 0;
// 重寫mousePress事件,該事件在滑鼠按下時調用
void MainWindow::mousePress(QMouseEvent *event)
{
// 如果事件是滑鼠左鍵按下
if (event->button() == Qt::LeftButton)
{
// 記錄當前y坐標軸範圍下限
yMin = ui->customPlot->yAxis->range().lower;
}
}
// 重寫mouseMove事件,該事件在滑鼠移動時調用
void MainWindow::mouseMove(QMouseEvent *event)
{
// 如果事件是滑鼠左鍵拖動
if (event->buttons() == Qt::LeftButton)
{
// 計算當前縮放因子
double zoomFactor = 1.0 + (event->pos().y() - event->lastPos().y()) / 100.0;
// 計算當前的y坐標軸範圍
QCPRange newRange(yMin*zoomFactor, ui->customPlot->yAxis->range().upper*zoomFactor);
// 將新的範圍設置給y坐標軸
ui->customPlot->yAxis->setRange(newRange);
ui->customPlot->replot();
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/295391.html