簡體   English   中英

在QCustomplot中的圖形上顯示x和y坐標

[英]Display x and y coordinates on graph in QCustomplot

我想在圖形上的鼠標移動上顯示x和y坐標。 我計算了x和y坐標,但不確定如何在圖形上顯示該點(最好像(x,y)這樣)

connect(ui->customPlot, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseRelease(QMouseEvent*)));
connect(ui->customPlot, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress(QMouseEvent*)));


float MainWindow::findX(QCustomPlot* customPlot, QCPCursor* cursor1, QMouseEvent* event)
{

    double x = customPlot->xAxis->pixelToCoord(event->pos().x());
    double y = customPlot->yAxis->pixelToCoord(event->pos().y());

    // I think I need to write a function here which will display the text on the graph.
}

void MainWindow::mouseRelease(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        static QCPCursor cursor1;
        QCustomPlot* plot = (QCustomPlot*)sender();
        float x = findX(plot, &cursor1, event);
    }
}

void MainWindow::mousePressed(QMouseEvent* event)
{
    if (event->button() == Qt::RightButton) {
        QCustomPlot* plot = (QCustomPlot*)sender();
        plot->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(plot, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&)));
    }
}

您可以創建QCPItemText並放置文本,然后將其移動到與pixelToCoord對應的位置。

*。H

private:
    QCPItemText *textItem;

private slots:
    void onMouseMove(QMouseEvent* event);

* .cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    textItem = new QCPItemText(ui->customPlot);
    connect(ui->customPlot, &QCustomPlot::mouseMove, this, &MainWindow::onMouseMove);
}


void MainWindow::onMouseMove(QMouseEvent *event)
{
    QCustomPlot* customPlot = qobject_cast<QCustomPlot*>(sender());
    double x = customPlot->xAxis->pixelToCoord(event->pos().x());
    double y = customPlot->yAxis->pixelToCoord(event->pos().y());
    textItem->setText(QString("(%1, %2)").arg(x).arg(2));
    textItem->position->setCoords(QPointF(x, y));
    textItem->setFont(QFont(font().family(), 10));
    customPlot->replot();
}

下圖顯示了結果,但是由於某種原因,我的捕獲未獲取指針的圖像。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM