在qt中我們常常會使用數據來繪制曲線,常用的的繪制方法用QCutomPlot、QChart和QPrinter。有時我們會根據需要在曲線進行二次繪制,包括對曲線打標簽,顯示某個點的值等功能。本文主要為大家介紹在QCustomPlot中使用QCPItemTracer和QCPItemText繪制跟隨鼠標移動標簽和鼠標雙擊標簽線條。
在圖表中常使用到自動跟隨鼠標顯示曲線當前的值。?
1、下面將介紹說明使用QCustomPlot繪制標簽跟隨鼠標移動標簽。
第一步:創建一個空白的Qwidget并提升為QCustomPlot,并按照個人喜好初始化QCustomPlot設置對應的繪制樣式。
第二步:初始化需要顯示到QCustomPlot上標簽對象,本文主要使用QCPItemTracer繪制標簽和使用QCPItemText繪制標簽文本。
第三步:準備一組曲線數據,并將數據繪制到QCustomPlot中。
第四步:綁定鼠標移動事件,移動鼠標,觀察效果。
說太多,也懶得寫了,老規則,直接上代碼(代碼只提供主要函數哦,有問題請私聊我喲)。
QCPItemTracer *tracer = nullptr;QCPItemText *tracerLabel = nullptr;QCPGraph *tracerGraph;/*************************************************** * @brief: QCustomPlot初始化* @param: customPlot-指定對象* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void QCustomPlotWidgetInit(QCustomPlot* customPlot){//設置默認追蹤鼠標,否則在觸發鼠標移動時,必須先點一下才有效this->setMouseTracking(true);customPlot->setMouseTracking(true);//信號-槽連接語句bool ret1 = connect(customPlot, SIGNAL(mouseDoubleClick(QMouseEvent*)), this, SLOT(mouseDoubleClick(QMouseEvent*)));//信號-槽連接語句bool ret = connect(customPlot, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoveEventSlot(QMouseEvent*)));customPlot->clearGraphs();QLinearGradient plotGradient;plotGradient.setColorAt(0, QColor(241, 245, 252));customPlot->setBackground(plotGradient); // 設置背景顏色QList<QPen> str = { QPen(QColor(22,192,130)), QPen(QColor(50,90,208)), QPen(QColor(6,190,244)) ,QPen(QColor(136,122,242)), QPen(Qt::yellow) };QList<QBrush> strColor = { QBrush(QColor(0, 0, 255, 150)), QBrush(QColor(255, 255, 0, 150)), QBrush(QColor(255, 150, 0, 150)) };customPlot->addGraph();customPlot->graph(0)->setPen(str[0]); // 第一個圖的線條顏色為藍色customPlot->graph(0)->setSmooth(true);//添加平滑曲線customPlot->legend->setVisible(true);//顯示圖標customPlot->legend->setBorderPen(Qt::NoPen);//隱藏圖標邊框customPlot->legend->setBrush(QColor(255, 255, 255, 150));//設置圖標灰色透明customPlot->legend->setTextColor(Qt::black);//設置圖例文字顏色customPlot->legend->setFont(QFont("Helvetica", 10));//設置圖標字體customPlot->legend->setMargins(QMargins(0, 0, 0, 0));//設置圖標中圖形與文字到邊框距離customPlot->axisRect(0)->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);//設置圖列居中customPlot->axisRect(0)->setBackground(QColor(255, 255, 255));//設置背景為黑色customPlot->xAxis->setTickLabelColor(Qt::black);//設置x軸文本顏色customPlot->xAxis->setBasePen(QPen(Qt::black));//設置x軸顏色customPlot->xAxis->setTickPen(QPen(Qt::black));customPlot->xAxis->setSubTickPen(QPen(Qt::black));customPlot->xAxis->grid()->setVisible(true);customPlot->xAxis->setSubTickLengthIn(0); // 軸線內子刻度的長度customPlot->yAxis->setTickLabelColor(Qt::black);//設置y軸文本顏色customPlot->yAxis->setBasePen(QPen(Qt::black));//設置y軸顏色customPlot->yAxis->setTickPen(QPen(Qt::black));customPlot->yAxis->setSubTickPen(QPen(Qt::black));customPlot->yAxis->grid()->setVisible(true);// 使左軸和底軸的范圍始終轉移到右軸和頂軸connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));//設置橫坐標為時間格式QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);timeTicker->setTimeFormat("%h:%m:%s");timeTicker->setTickCount(10);customPlot->xAxis->setTicker(timeTicker);customPlot->xAxis->setTickLabelRotation(0);//設置x軸時間旋轉角度為30度customPlot->xAxis->setVisible(true);customPlot->graph(0)->rescaleAxes(true);customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);customPlot->setStyleSheet("background:#f1f5fc;");customPlot->replot();customPlot->layout()->update();customPlot->show();}/*************************************************** * @brief: QCustomPlotLabel初始化* @param: customPlot-指定對象* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void QCustomPloLabelInit(QCustomPlot* customPlot){//生成游標if (tracer){tracer = nullptr;}tracer = new QCPItemTracer(customPlot); //生成游標tracer->setPen(QPen(Qt::red));//圓圈輪廓顏色tracer->setBrush(QBrush(Qt::red));//圓圈圈內顏色tracer->setStyle(QCPItemTracer::tsCircle);//圓圈tracer->setSize(10);//設置大小tracer->setVisible(false);//游標說明if (tracerLabel){tracerLabel = nullptr;}tracerLabel = new QCPItemText(customPlot); //生成游標說明tracerLabel->setLayer("overlay");//設置圖層為overlay,因為需要頻繁刷新//tracerLabel->setPen(QPen(Qt::red, Qt::NoPen));//設置游標說明顏色tracerLabel->setColor(Qt::red);tracerLabel->setBrush(Qt::NoBrush);tracerLabel->setPositionAlignment(Qt::AlignLeft | Qt::AlignTop);//左上tracerLabel->position->setParentAnchor(tracer->position);//將游標說明錨固在tracer位置處,實現自動跟隨tracerLabel->setVisible(false);}/*************************************************** * @brief: QCustomPlot繪制曲線* @param: customPlot-指定對象;data-數據;key-關鍵字* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void QCustomPlotWidgetShow(QCustomPlot* customPlot, QMap<int, QStringList> data, QString key){if (!customPlot || data.isEmpty()) return;QVector<double> x1, y1;double min = -10, max = 10;int index = -1;for (int i = 0; i < data.first().size(); i++){if (data.first()[i] == key){index = i; break;}}if (index == -1) return; // 未找到keyfor (int i = 1; i < data.size(); i++){x1.push_back(i);y1.push_back(data[i][index].toDouble());max = qMax(max, y1.last());min = qMin(min, y1.last());}if (min == 0) { min = -max; }if (x1.isEmpty() || y1.isEmpty()) return;customPlot->xAxis->setRange(x1.first(), x1.last());customPlot->yAxis->setRange(min*1.5, max*1.5);customPlot->graph(0)->setData(x1, y1);customPlot->graph(0)->setName(key);customPlot->replot();}/*************************************************** * @brief: 鼠標移動事件函數* @param: event-鼠標對象* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void mouseMoveEventSlot(QMouseEvent *event){if (ui.widget_alarmData->underMouse()){tracer->setVisible(true);tracerLabel->setVisible(true);}else{tracer->setVisible(false);tracerLabel->setVisible(false);}if (ui.widget_alarmData->graphCount() <= 0){return;}else{tracerGraph = ui.widget_alarmData->graph(0);tracer->setGraph(tracerGraph);}if (tracer == nullptr){return;}if (tracer->graph() == nullptr){return;}if (tracer->visible()){if (tracerGraph){double x = ui.widget_alarmData->xAxis->pixelToCoord(event->pos().x());tracer->setGraphKey(x); //將游標橫坐標設置成剛獲得的橫坐標數據xtracer->setInterpolating(true); //自動計算y值,若只想看已有點,不需要這個tracer->updatePosition(); //使得剛設置游標的橫縱坐標位置生效tracerLabel->setText(QString("time-%1\nvalue-%2").arg(QTime(0, 0, 0).addSecs(int(tracer->position->key())).toString(QString::fromLatin1("HH:mm:ss"))).arg(tracer->position->value()));ui.widget_alarmData->replot(QCustomPlot::rpQueuedReplot);}}}
鼠標跟蹤自動顯示效果圖如下所示:
2、下面再提供在QCustomPlot上雙擊鼠標進行打標簽的方法:
大致步驟和上面跟隨鼠標移動打標簽差不多,還是話不多說,直接上代碼(代碼只提供主要函數哦,有問題請私聊我喲)
QCPItemStraightLine *vline_start = nullptr, *vline_end = nullptr;QCPItemText *m_currentLabel_start = nullptr,*m_currentLabel_end = nullptr;QTime startTime, stopTime;/*************************************************** * @brief: QCustomPlot初始化* @param: customPlot-指定對象* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void QCustomPlotWidgetInit(QCustomPlot* customPlot){//設置默認追蹤鼠標,否則在觸發鼠標移動時,必須先點一下才有效this->setMouseTracking(true);customPlot->setMouseTracking(true);//信號-槽連接語句bool ret1 = connect(customPlot, SIGNAL(mouseDoubleClick(QMouseEvent*)), this, SLOT(mouseDoubleClick(QMouseEvent*)));//信號-槽連接語句bool ret = connect(customPlot, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoveEventSlot(QMouseEvent*)));customPlot->clearGraphs();QLinearGradient plotGradient;plotGradient.setColorAt(0, QColor(241, 245, 252));customPlot->setBackground(plotGradient); // 設置背景顏色QList<QPen> str = { QPen(QColor(22,192,130)), QPen(QColor(50,90,208)), QPen(QColor(6,190,244)) ,QPen(QColor(136,122,242)), QPen(Qt::yellow) };QList<QBrush> strColor = { QBrush(QColor(0, 0, 255, 150)), QBrush(QColor(255, 255, 0, 150)), QBrush(QColor(255, 150, 0, 150)) };customPlot->addGraph();customPlot->graph(0)->setPen(str[0]); // 第一個圖的線條顏色為藍色customPlot->graph(0)->setSmooth(true);//添加平滑曲線customPlot->legend->setVisible(true);//顯示圖標customPlot->legend->setBorderPen(Qt::NoPen);//隱藏圖標邊框customPlot->legend->setBrush(QColor(255, 255, 255, 150));//設置圖標灰色透明customPlot->legend->setTextColor(Qt::black);//設置圖例文字顏色customPlot->legend->setFont(QFont("Helvetica", 10));//設置圖標字體customPlot->legend->setMargins(QMargins(0, 0, 0, 0));//設置圖標中圖形與文字到邊框距離customPlot->axisRect(0)->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);//設置圖列居中customPlot->axisRect(0)->setBackground(QColor(255, 255, 255));//設置背景為黑色customPlot->xAxis->setTickLabelColor(Qt::black);//設置x軸文本顏色customPlot->xAxis->setBasePen(QPen(Qt::black));//設置x軸顏色customPlot->xAxis->setTickPen(QPen(Qt::black));customPlot->xAxis->setSubTickPen(QPen(Qt::black));customPlot->xAxis->grid()->setVisible(true);customPlot->xAxis->setSubTickLengthIn(0); // 軸線內子刻度的長度customPlot->yAxis->setTickLabelColor(Qt::black);//設置y軸文本顏色customPlot->yAxis->setBasePen(QPen(Qt::black));//設置y軸顏色customPlot->yAxis->setTickPen(QPen(Qt::black));customPlot->yAxis->setSubTickPen(QPen(Qt::black));customPlot->yAxis->grid()->setVisible(true);// 使左軸和底軸的范圍始終轉移到右軸和頂軸connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));//設置橫坐標為時間格式QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);timeTicker->setTimeFormat("%h:%m:%s");timeTicker->setTickCount(10);customPlot->xAxis->setTicker(timeTicker);customPlot->xAxis->setTickLabelRotation(0);//設置x軸時間旋轉角度為30度customPlot->xAxis->setVisible(true);customPlot->graph(0)->rescaleAxes(true);customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);customPlot->setStyleSheet("background:#f1f5fc;");customPlot->replot();customPlot->layout()->update();customPlot->show();}/*************************************************** * @brief: QCustomPlotLabel初始化* @param: customPlot-指定對象* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void QCustomPlotMarkLineInit(QCustomPlot* customPlot){if (vline_start){vline_start = nullptr;}// 設置游標垂直線vline_start = new QCPItemStraightLine(customPlot);vline_start->setLayer("overlay");// 超出坐標軸范圍則不顯示游標線vline_start->setClipToAxisRect(false);// 顏色隨機vline_start->setPen(QPen(Qt::green, 1, Qt::DashLine));vline_start->setVisible(false);if (vline_end){vline_end = nullptr;}// 設置游標垂直線vline_end = new QCPItemStraightLine(customPlot);vline_end->setLayer("overlay");// 超出坐標軸范圍則不顯示游標線vline_end->setClipToAxisRect(false);// 顏色隨機vline_end->setPen(QPen(Qt::blue, 1, Qt::DashLine));vline_end->setVisible(false);if (m_currentLabel_start){m_currentLabel_start = nullptr;}// 設置文本框m_currentLabel_start = new QCPItemText(customPlot);m_currentLabel_start->setLayer("overlay");// 超出坐標軸范圍則不顯示標簽m_currentLabel_start->setClipToAxisRect(true);m_currentLabel_start->setPadding(QMargins(3, 3, 3, 3));m_currentLabel_start->setPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));m_currentLabel_start->setBrush(Qt::NoBrush);m_currentLabel_start->setFont(QFont("Arial", 8));m_currentLabel_start->setColor(Qt::green);m_currentLabel_start->setVisible(false);if (m_currentLabel_end){m_currentLabel_end = nullptr;}// 設置文本框m_currentLabel_end = new QCPItemText(customPlot);m_currentLabel_end->setLayer("overlay");// 超出坐標軸范圍則不顯示標簽m_currentLabel_end->setClipToAxisRect(true);m_currentLabel_end->setPadding(QMargins(3, 3, 3, 3));m_currentLabel_end->setPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));m_currentLabel_end->setBrush(Qt::NoBrush);m_currentLabel_end->setFont(QFont("Arial", 8));m_currentLabel_end->setColor(Qt::blue);m_currentLabel_end->setVisible(false);}/*************************************************** * @brief: QCustomPlot繪制曲線* @param: customPlot-指定對象;data-數據;key-關鍵字* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void QCustomPlotWidgetShow(QCustomPlot* customPlot, QMap<int, QStringList> data, QString key){if (!customPlot || data.isEmpty()) return;QVector<double> x1, y1;double min = -10, max = 10;int index = -1;for (int i = 0; i < data.first().size(); i++){if (data.first()[i] == key){index = i; break;}}if (index == -1) return; // 未找到keyfor (int i = 1; i < data.size(); i++){x1.push_back(i);y1.push_back(data[i][index].toDouble());max = qMax(max, y1.last());min = qMin(min, y1.last());}if (min == 0) { min = -max; }if (x1.isEmpty() || y1.isEmpty()) return;customPlot->xAxis->setRange(x1.first(), x1.last());customPlot->yAxis->setRange(min*1.5, max*1.5);customPlot->graph(0)->setData(x1, y1);customPlot->graph(0)->setName(key);customPlot->replot();}/*************************************************** * @brief: 鼠標移動事件函數* @param: event-鼠標對象* @return : 無* @author :鬼魅* @date :2025-7-29 9:48:38***************************************************/void mouseDoubleClick(QMouseEvent *event){if (ui.widget_alarmData->underMouse()){if (vline_start == nullptr || vline_end == nullptr || m_currentLabel_start == nullptr || m_currentLabel_end == nullptr){return;}}double x = ui.widget_alarmData->xAxis->pixelToCoord(event->pos().x());double y = ui.widget_alarmData->yAxis->pixelToCoord(event->pos().y());if (event->button() == Qt::RightButton){// 畫豎線,x為curtime,y只要0和1即可繪制直線了vline_end->point1->setCoords(x, 0);vline_end->point2->setCoords(x, 1);vline_end->setVisible(true);m_currentLabel_end->setVisible(false);// 可以設置顯示位置跟隨錨點的位置,此次我設置的是絕對位置,添加TAG用的m_currentLabel_end->position->setCoords(x, y);m_currentLabel_end->setText(QStringLiteral("結束時間"));stopTime = QTime(0, 0, 0).addSecs(quint64(x));if (startTime > stopTime){QMessageBox::information(this, tr("提示"), tr("結束時間必須大于開始時間!"));return;}m_currentLabel_end->setVisible(true);}else{// 畫豎線,x為curtime,y只要0和1即可繪制直線了vline_start->point1->setCoords(x, 0);vline_start->point2->setCoords(x, 1);vline_start->setVisible(true);m_currentLabel_start->setVisible(false);// 可以設置顯示位置跟隨錨點的位置,此次我設置的是絕對位置,添加TAG用的m_currentLabel_start->position->setCoords(x, y);m_currentLabel_start->setText(QStringLiteral("開始時間"));startTime = QTime(0, 0, 0).addSecs(quint64(x));m_currentLabel_start->setVisible(true);}}
鼠標雙擊打標簽顯示效果圖如下所示:
注:如果本文章對您有所幫助,請點贊收藏支持一下,謝謝。^_^
版權聲明:本文為博主原創文章,轉載請附上博文鏈接。