Qt: How to Find the Position of the Mouseclick Relative to an Image

I would like to implement an image editor. I have a QPixmap in a QLabel in a QHBoxLayout. I have overriden the mousePressEvent in the parent widget. When the mousePressedEvent occurs, the

 event->pos() = QPoint(271,115)

points to a place which is displaced relative to the pointer (mouse). The displacement is the distance of the QLabel from the QWidget's corner. It gets bigger when I resize the window. How do I find this displacement vector? I want to draw a pixel on the QPixmap exactly where the mouse is. Note that the following methods give no remedy:

qDebug() << "event->pos()" << event->pos();
qDebug() << "this->pos() = " << this->pos();
qDebug() << "pm_imageLabel->pos() =" << pm_imageLabel->pos();
qDebug() << "pos = " << mapFromGlobal(QCursor::pos());

These give all different positions. No searching on the internet or in Qt's documentation brought me closer to the answer. Thank You in advance.

1 answer

  • answered 2018-11-08 15:15 user1396055

    Finally I have figured it out partially with the help of vahancho. The the position of the QPixmap withing QLabel is difficult to determine, but I can forbid QLabel to resize. So I set the size of QLabel to the image size.

    pm_imageLabel->setPixmap(m_pixmap);
    pm_imageLabel->setFixedSize(m_pixmap.size());
    

    and I override the mousePressed even inside QLabel class. This way the event->pos is correct.

    Thanks.