QT十字光标(QCustomPlot)

1、选择同层图例定位或切换曲线,并显示十字光标。

2、通过鼠标左右移动,将十字光标的横轴和纵轴交点定位到曲线上。

3、在十字光标的横轴和纵轴的交点处显示交点的纵坐标值。

十字光标的创建和设置

void Widget::SelectionSwitchChangedSlot()
{
    if(tracer)
    {
        //判断游标对象是否存在,如果存在则删除重画
        ui->customplot->removeItem(tracer);
        tracer = nullptr;
        ui->customplot->setMouseTracking(false);
        ui->customplot->replot(QCustomPlot::rpQueuedReplot);
    }
    for(int i = 0; i < ui->customplot->graphCount(); i++)
    {
        QCPPlottableLegendItem *item = ui->customplot->legend->itemWithPlottable(ui->customplot->graph(i));
        if(item->selected())
        {
            //创建游标对象
            tracer = new QCPItemTracer(ui->customplot);
            // //设置游标与图层相连接
            tracer->setGraph(ui->customplot->graph(i));
            //设置游标样式为十字光标
            tracer->setStyle(QCPItemTracer::tsCrosshair);
            //设置游标线的颜色为白色
            tracer->setPen(QPen(Qt::white, 1, Qt::DotLine));
            //设置游标可移动
            tracer->setInterpolating(true);
            //设置游标可见
            tracer->setVisible(true);
            //开启鼠标跟踪
            ui->customplot->setMouseTracking(true);
            //重绘
            ui->customplot->replot(QCustomPlot::rpQueuedReplot);

            connect(ui->customplot,SIGNAL(mouseMove(QMouseEvent *)),this,SLOT(mouseMoveEvent(QMouseEvent *)));

        }
    }
}

鼠标移动事件

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(tracer)
    {
        //获取鼠标在绘图区的像素坐标
        QPointF pos = event->pos();
        //将像素坐标转换为轴坐标
        double x = ui->customplot->xAxis->pixelToCoord(pos.x());
        double y = tracer->position->coords().y();
        //更新游标位置
        tracer->setGraphKey(x);
        tracer->updatePosition();
        //在游标位置添加方框以显示值
        textLabel->setPositionAlignment(Qt::AlignLeft | Qt::AlignBottom);
        textLabel->position->setType(QCPItemPosition::ptPlotCoords);
        textLabel->position->setCoords(tracer->position->coords());
        textLabel->setText(QString(" %2 ").arg(y));
        textLabel->setPen(QPen(Qt::white));
        textLabel->setBrush(QColor(0,55,79));
        textLabel->setFont(QFont(font().family(), 10));
        textLabel->setPen(QPen(Qt::white));
        textLabel->setColor(Qt::white);
        textLabel->setVisible(true);
        //重绘
        ui->customplot->replot(QCustomPlot::rpQueuedReplot);
    }
}

光标显示和隐藏

if(tracer)
    {
        //隐藏十字游标
        ui->customplot->removeItem(tracer);
        tracer = nullptr;
        ui->customplot->setMouseTracking(false);
        ui->customplot->replot(QCustomPlot::rpQueuedReplot);
        //隐藏显示y坐标值的方框
        textLabel->setVisible(false);
    }
    else
    {
        connect(ui->customplot, SIGNAL(selectionChangedByUser()), this, SLOT(SelectionSwitchChangedSlot()));
    }

你可能感兴趣的:(qt,开发语言,c++)