在QCustomplot

时间:2017-05-31 21:24:10

标签: c++ qt qt5 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&)));
    }
}

1 个答案:

答案 0 :(得分:2)

您可以创建pixelToCoord并放置文字并将其移至private: QCPItemText *textItem; private slots: void onMouseMove(QMouseEvent* event); 所带的位置。

<强> *的.h

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();
}

<强> *。CPP

{{1}}

下图显示了结果,但由于某种原因,我的捕获不会拍摄指针的图像。

enter image description here