Qt World Summit: Submit your Presentation

QCustomplot: Coords by Mouseclick

  • Hi everybody,

    I'm new to Qt and I'm using QCustomPlot to create a plot out of some informations. Now I want to click with the left mousebutton into the graph and want to get the coordinates of the position I clicked at. I couldn't find any solution for it yet, but I can't believe I'm the only one who wants to do this :). It seems like I'm missing something obvious. Can someone give me a hint?


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You can either overload the mouse related events or use one of the "mouse signals":http://www.workslikeclockwork.com/other/qcustomplot-doc/classQCustomPlot.html#aca75bf9afb5dd19349c375de2a87a051 from QCustomplot

  • Hi,

    just to complete this for the next newbie who trips over this little stone. I hoped there's a simpler way to do this but I solved the problem as follows:

    somewhere in the widgets .cpp file:
    @connect(plot_, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(clickedGraph()));@
    ^^thanks for the hint with the mouseEvents

    in the .h file of course:
    @public slots:
    void clickedGraph()@

    and clickedGraph() does:
    @void FVolumePlayerWidget::clickedGraph()
    QPoint p = this->mapFromGlobal(QCursor::pos()); //get mouse position
    QRect plotPos = plot_->axisRect(); //get origin of axis
    int x = p.x() - 44; //calc coordinate at clicked position
    //TODO: get Position of stuff to calc the value 44

    //Mark selected position
    QCPItemLine *arrow = new QCPItemLine(plot_);
    arrow->start->setCoords(x, 99);
    arrow->end->setCoords(x, ecgValueArray[x]); //ecgValues is th y-data I build the graph with earlier

    so this works out for me so far for fixed graph sizes and because of the amount of data I'm plotting... but maybe it helps someone somehow.

  • Lifetime Qt Champion

    You don't need the call to QCursor::pos() nor to map if you use the QMouseEvent that is send by the signal.

  • okay thanks,

    I will remind that for later...gotta get forward. If I remember this post after optimizing my program I will post an update.

  • Lifetime Qt Champion

    connect(plot_, SIGNAL(mousePress(QMouseEvent*)), SLOT(clickedGraph(QMouseEvent*)));

    void FVolumePlayerWidget::clickedGraph(QMouseEvent *event)
    QPoint p = event->pos();

Log in to reply