Reputation: 313
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.
Upvotes: 0
Views: 1605
Reputation: 252
I know it's been a while but i found a solution that works without having to resize the QLabel
.
The solution is in Python
.
label = QLabel(...)
img_pix = QPixmap(...)
label.setPixmap(img_pix)
# now you can get mouse click coordinates on the label by overriding `label.mousePressEvent`
# assuming we have the mouse click coordinates
coord_x = ...
coord_y = ...
# calculating the mouse click coordinates relative to the QPixmap (img_pix)
img_pix_width = img_pix.width()
img_pix_heigth = img_pix.height()
label_width = label.width()
label_height = label.height()
scale_factor_width = label_width / img_pix_width
scale_factor_height = label_height / img_pix_heigth
relative_width_in_img_pix = coord_x / scale_factor_width
relative_height_in_img_pix = coord_y / scale_factor_height
relative_coordinates_in_img_pix = QPoint(relative_width_in_img_pix, relative_height_in_img_pix)
Upvotes: 0
Reputation: 313
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.
Upvotes: 2