PDA

View Full Version : How to get mouse click position of QLabel which is a child of QMainWindow in PyQt5



AshishGupta
18th June 2018, 14:52
Hi, I am new to PyQt. I am designing an paint interface using PyQt5. For that, I made a class gui(QMainWindow). Then I added a QLabel through qtDesigner and named it imageLabel. So far so good. But now I need the position of mouse click relative to the QLabel (imageLabel).

I know that in order to get the mouse click position from the QMainWindow i need to call this:
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.lastPoint= event.pos()

This gives me the position that is indexed from the top of the QMainWindow, I don't need that. I need mouse position starting relative to my QLabel. This is needed because, I am creating a dynamic label, so upon resizing the window, the position of QLabel will change (hence I can't hard code anything)

12866 See, the white window is where I would like to paint.

How do I get the position of mouse from this QLabel/QImage.
Thanks.

Ginsengelf
18th June 2018, 15:27
Hi, have a lot at the different coordinate mapping functions like QWidget::mapFromGlobal(), QWidget::mapFromParent(), etc.

Ginsengelf

AshishGupta
19th June 2018, 06:09
Thanks @Ginsengelf. Yes, the function you suggested worked. Thanks a ton.

Here is the code for others to refer:

def mousePressEvent(self, event):
if event.button() == Qt.LeftButton & self.globalDrawing==True:
self.drawing=True
self.lastPoint= event.pos()
self.lastPoint=self.imageLabel.mapFromParent(event .pos()) #this is working fine now
self.imageLabel.setPixmap(QPixmap.fromImage(self.i mage))

def mouseMoveEvent(self,event):
if (event.buttons() & Qt.LeftButton) & self.drawing &self.globalDrawing:
painter=QPainter(self.image)
painter.setPen(QPen(self.brushColor,self.brushSize ,Qt.SolidLine,Qt.RoundCap,Qt.RoundJoin))
painter.drawLine(self.imageLabel.mapFromParent(eve nt.pos()),self.lastPoint)
self.lastPoint=self.imageLabel.mapFromParent(event .pos()) #this is working fine now
self.imageLabel.setPixmap(QPixmap.fromImage(self.i mage))
def mouseReleaseEvent(self,event):
if event.button == Qt.LeftButton & self.globalDrawing:
self.drawing = False
self.imageLabel.setPixmap(QPixmap.fromImage(self.i mage))