图像PyQt的坐标

问题描述

我正在制作一个应用程序,我需要在该应用程序上单击鼠标来提取图像的坐标。 图像的分辨率为 1920x1080 ,我的笔记本电脑屏幕的分辨率为 1366x768

在这里面临两个问题。 1)图像以裁剪的方式显示在我的笔记本电脑上。 2)每当我单击鼠标按钮时,它都会为我提供笔记本电脑屏幕的坐标,而不是图像的坐标。

我严格不必调整图像的大小,其次,在我的最终项目中,图像将不会占据整个屏幕,它将仅占据屏幕的一部分。我正在寻找一种显示整个图像以及获取相对于图像的坐标的方法

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_())

这是一张图片,可以使您对我的最终项目有所了解。

enter image description here

解决方法

应该使用QGraphicsView而不是使用QLabel,因为它具有易于缩放和易于处理坐标的优点

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_())