c++qtqt5qcustomplot

How to get global coord in pixel from local graphic coord (Qt, QCustomPlot)


I want to convert local coords to global in pixels relative of window.

I saw examples how to make from global to local. It`s use

ui->customPlot->xAxis->pixelToCord(0)

But

ui->customPlot->xAxis->coordToPixel(0)

Don't work.

Here I use button to debug result. Red it's were button have to be. Blue it's were button it is.

image link

void MainWindow::makePlot(){
    // generate some data:
    QVector<double> x(101), y(101); // initialize with entries 0..100
    for (int i=0; i<101; ++i)
    {
      x[i] = i/50.0 - 1; // x goes from -1 to 1
      y[i] = x[i]*x[i]; // let's plot a quadratic function
    }
    // create graph and assign data to it:
    ui->customPlot->addGraph();
    ui->customPlot->graph(0)->setData(x, y);
    // give the axes some labels:
    ui->customPlot->xAxis->setLabel("x");
    ui->customPlot->yAxis->setLabel("y");
    // set axes ranges, so we see all data:
    ui->customPlot->xAxis->setRange(-1, 1);
    ui->customPlot->yAxis->setRange(0, 1);
    ui->customPlot->replot();


    double real_x = ui->customPlot->xAxis->coordToPixel(0) + ui->customPlot->x();
    double real_y = ui->customPlot->yAxis->coordToPixel(0) + ui->customPlot->y();

    QPoint real_cord(real_x, real_y);

    button->setGeometry(QRect(real_cord, QSize(20,20)));

}

Solution

  • The position of a widget is relative to the parent widget, if it does not have a parent it is relative to the screen. So it is important to establish a suitable parent, in this case a good option is to use as a parent to ui->customPlot.

    On the other hand, the coordToPixel() method requires that the widget be displayed, so a good option is to use showEvent(), also when changing the size of the window it would also change those coordinates so it will also use the resizeEvent().

    *.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        button = new QPushButton("test", ui->customPlot);
        ...
        ui->customPlot->replot();
    }
    
    void MainWindow::moveButtonFromCoord()
    {
        double real_x = ui->customPlot->xAxis->coordToPixel(0);
        double real_y = ui->customPlot->yAxis->coordToPixel(0);
        QRect geo = button->geometry();
        geo.moveCenter(QPoint(real_x, real_y));
        button->setGeometry(geo);
    }
    
    void MainWindow::resizeEvent(QResizeEvent *event)
    {
        moveButtonFromCoord();
        QMainWindow::resizeEvent(event);
    }
    
    void MainWindow::showEvent(QShowEvent *event)
    {
        moveButtonFromCoord();
        QMainWindow::showEvent(event);
    }
    ...
    

    The complete example can be found in the following link.