#include "draglinehandler.h" DragLineHandler::DragLineHandler(QCustomPlot *plot, QCPItemStraightLine *line1, QCPItemStraightLine *line2, QCPGraph*graph, QObject *parent) : QObject(parent), mPlot(plot), mLine1(line1), mLine2(line2),mGraph(graph) ,_enableFlag(false) { mPlot->setInteractions(QCP::iSelectItems); } bool DragLineHandler::eventFilter(QObject *obj, QEvent *event) { if(!_enableFlag){ qDebug()<<"_enableFlag false."; return false; } if (obj == mPlot) { if (event->type() == QEvent::MouseMove) { qDebug()<<"mouse move..."; QMouseEvent *mouseEvent = static_cast(event); QPoint mousePos = mouseEvent->pos(); qDebug()<<"x:"<setCursor(Qt::SplitHCursor); qDebug()<<"mIconLabel visiable."; } else { qDebug()<<"mIconLabel not visiable."; mPlot->setCursor(Qt::ArrowCursor); } if (mDraggingLine) { double x = mPlot->xAxis->pixelToCoord(mousePos.x()); if(mDraggingLine == mLine1){ emit sigSendLineXCoord(1,x); }else{ emit sigSendLineXCoord(2,x); } mDraggingLine->point1->setCoords(x, mPlot->yAxis->range().lower); mDraggingLine->point2->setCoords(x, mPlot->yAxis->range().upper); mPlot->replot(); updateSelectedRegion(); } } else if (event->type() == QEvent::MouseButtonPress) { qDebug()<<"mouse press..."; QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::LeftButton) { QPoint mousePos = mouseEvent->pos(); if (isNearLine(mLine1, mousePos)) { mDraggingLine = mLine1; mLine1->setSelected(true); } else if (isNearLine(mLine2, mousePos)) { mDraggingLine = mLine2; mLine2->setSelected(true); } } } else if (event->type() == QEvent::MouseButtonRelease) { if (mDraggingLine) { mDraggingLine->setSelected(false); mDraggingLine = nullptr; } } } return QObject::eventFilter(obj, event); } bool DragLineHandler::isNearLine(QCPItemStraightLine *line, const QPoint &pos) { double lineX = line->point1->coords().x(); int linePixelX = mPlot->xAxis->coordToPixel(lineX); return qAbs(pos.x() - linePixelX) < 5; } void DragLineHandler::updateSelectedRegion() { double x1 = mLine1->point1->coords().x(); double x2 = mLine2->point1->coords().x(); if (x1 > x2) std::swap(x1, x2); // 获取曲线数据 QVector xData, yData; // mGraph->data()->data(xData, yData); auto dataContainer = mGraph->data(); for (auto it = dataContainer->begin(); it != dataContainer->end(); ++it) { xData.append(it->key); yData.append(it->value); } // 查找对应x位置 int index1 = findClosestIndex(xData, x1); int index2 = findClosestIndex(xData, x2); qDebug() << "Selected region: [" << xData[index1] << ", " << xData[index2] << "]"; } int DragLineHandler::findClosestIndex(const QVector &data, double target) { auto it = std::min_element(data.begin(), data.end(), [target](double a, double b) { return qAbs(a - target) < qAbs(b - target); }); return std::distance(data.begin(), it); }