图像 PyQt 的坐标 [英] Coordinates of an image PyQt

查看:39
本文介绍了图像 PyQt 的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

推荐答案

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

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

这篇关于图像 PyQt 的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆