I'm making an application for which I need to extract the coordinates of the image on mouse click. The images have a resolution of 1920x1080 and the resolution of my laptop screen is 1366x768.
I'm facing two problems here. 1) The images shows up in a cropped manner on my laptop. 2) Whenever I click the mouse button it gives me the coordinate of my laptop screen not of the image.
I strictly don't have to resize the image and secondly, in my final project the image would not occupy the entire screen, it will be occupying only a portion of the screen. I'm looking for a way to show the entire image as well getting the coordinates with respect to the image.
from PyQt4 import QtGui, QtCore
import sys
class Window(QtGui.QLabel):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setPixmap(QtGui.QPixmap('image.jpg'))
self.mousePressEvent = self.getPos
def getPos(self , event):
x = event.pos().x()
y = event.pos().y()
self.point = (x, y)
print(self.point)
if __name__ == "__main__":
app = QtGui.QApplication([])
w = Window()
w.showMaximized()
sys.exit(app.exec_())
Here is an image which will give you an idea about my final project.
Instead of using QLabel you should use QGraphicsView as it has the advantage of easy scaling and easy handling of coordinates
from PyQt5 import QtCore, QtGui, QtWidgets
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
scene = QtWidgets.QGraphicsScene(self)
self.setScene(scene)
self._pixmap_item = QtWidgets.QGraphicsPixmapItem()
scene.addItem(self.pixmap_item)
@property
def pixmap_item(self):
return self._pixmap_item
def setPixmap(self, pixmap):
self.pixmap_item.setPixmap(pixmap)
def resizeEvent(self, event):
self.fitInView(self.pixmap_item, QtCore.Qt.KeepAspectRatio)
super().resizeEvent(event)
def mousePressEvent(self, event):
if self.pixmap_item is self.itemAt(event.pos()):
sp = self.mapToScene(event.pos())
lp = self.pixmap_item.mapFromScene(sp).toPoint()
print(lp)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = GraphicsView()
w.setPixmap(QtGui.QPixmap("image.jpg"))
w.showMaximized()
sys.exit(app.exec_())