python - 图像 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_())
这是一张图片,可以让您了解我的最终项目。
解决方案
您应该使用 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_())
推荐阅读
- c++ - 如何检查 std::filesystem::copy 是否结束?
- mysql - 从表中获取最新日期的最新值
- kotlin - 在 for 循环中等待所有凌空请求
- multithreading - 在主线程中调用委托
- python - 在 Python 中为我的 Slack 机器人引发 KeyError
- html - 应用行间距(row-gap)网格容器高度后的CSS Grid小于网格本身
- python - 选择类别时,同时显示类别的元素和所有子类别的元素
- javascript - 减少来自 YouTube 的网络请求
- java - 如何切换到新窗口并在 selenium webdriver 中打印标题(没有窗口句柄)
- python - 标准偏差和平均值计算的移动窗口