鼠标悬停时显示图表数值 - 检测散点

10

我试图显示QCustomPlot上不同点的绘图值,该图表使用线性样式lsLine。我知道我可以在QCustomPlot上设置鼠标悬停信号,但那并不能真正帮助我,因为我只需要知道当鼠标悬停在我的绘制线上时得到通知。我的问题是是否有任何方法可以找出鼠标是否悬停在我的散点上。是否有一个信号我可以连接来告诉我鼠标何时悬停在散点上?

3个回答

10

你可以轻松地将插槽连接到 QCustomPlot 发出的 mouseMove 信号。然后,你可以使用 QCPAxis::pixelToCoord 找到坐标:

connect(this, SIGNAL(mouseMove(QMouseEvent*)), this,SLOT(showPointToolTip(QMouseEvent*)));

void QCustomPlot::showPointToolTip(QMouseEvent *event)
{

    int x = this->xAxis->pixelToCoord(event->pos().x());
    int y = this->yAxis->pixelToCoord(event->pos().y());

    setToolTip(QString("%1 , %2").arg(x).arg(y));

}

如果我在UI上有两个图表,ui->widget_graph1ui->widget_graph2,我该如何为这两个图表都实现鼠标悬停时显示坐标的功能?我需要更改函数名称void CustomPlot::showPointToolTip(QMouseEvent *event){}以适应我的情况吗?谢谢。 - Wei
@Wei 如果你像我一样在QCustomPlot源代码中实现了插槽,那么工具提示将会显示在所有的图表上。你也可以将插槽放在另一个类中,并使用sender()来找出发出mouseMove信号的图表。 - Nejat
我只找到了 QCustomPlot::toolTip,并将您的 void QCustomPlot::showPointToolTip(QMouseEvent *event){} 更改为 void QCustomPlot::toolTip(QMouseEvent *event){}。这样做是否相同? - Wei

10
重新实现 QCustomPlot::mouseMoveEvent 或连接到 QCustomPlot::mouseMove。然后使用轴的 coordToPixel 将(光标)像素坐标转换为绘图坐标,并使用 QMap::lowerBound(cursorX) 在您的 QCPDataMap 中搜索最近的点。

@Rajeshwar coordToPixel 将绘图坐标转换为像素坐标。它是如何解决你的问题的? - Nejat

2
当您使用X轴的日期时间格式(包括每秒钟更多的小数点)时,像素到坐标的转换会失败。 如果您想要在数据点之间显示坐标,则这是最快的方法。 也许有用的是(与连接信号一起使用)。
void MainWindow::onMouseMoveGraph(QMouseEvent* evt)
    {
    int x = this->ui->customPlot->xAxis->pixelToCoord(evt->pos().x());
    int y = this->ui->customPlot->yAxis->pixelToCoord(evt->pos().y());
    qDebug()<<"pixelToCoord: "<<data.key<<data.value; //this is correct when step is greater 1 second

if (this->ui->customPlot->selectedGraphs().count()>0)
        {
        QCPGraph* graph = this->ui->customPlot->selectedGraphs().first();
        QCPData data = graph->data()->lowerBound(x).value();

        double dbottom = graph->valueAxis()->range().lower;        //Yaxis bottom value
        double dtop = graph->valueAxis()->range().upper;           //Yaxis top value
        long ptop = graph->valueAxis()->axisRect()->top();         //graph top margin
        long pbottom = graph->valueAxis()->axisRect()->bottom();   //graph bottom position
// result for Y axis
        double valueY = (evt->pos().y() - ptop) / (double)(pbottom - ptop)*(double)(dbottom - dtop) + dtop;

//or shortly for X-axis
        double valueX = (evt->pos().x() - graph->keyAxis()->axisRect()->left());  //graph width in pixels
        double ratio = (double)(graph->keyAxis()->axisRect()->right() - graph->keyAxis()->axisRect()->left()) / (double)(graph->keyAxis()->range().lower - graph->keyAxis()->range().upper);    //ratio px->graph width
//and result for X-axis
        valueX=-valueX / ratio + graph->keyAxis()->range().lower;


        qDebug()<<"calculated:"<<valueX<<valueY;
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接