【问题标题】:get mouse position in the QGraphicScene with pixels coordinate使用像素坐标获取 QGraphicScene 中的鼠标位置
【发布时间】:2020-10-25 18:29:21
【问题描述】:

我尝试创建一个程序来操作图像,我想要鼠标在Qgraphicscene中时的位置,但是除非我在Qgraphicview之外启动,否则不会触发鼠标事件, 我怎样才能用图像的坐标(像素)得到这个位置 并感谢您的帮助

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.uic import *
from PIL import Image,ImageFilter,ImageQt



import sys
MainUI, _ = loadUiType('app.ui')


class MainApp(QMainWindow, MainUI):
    def __init__(self):
        super(MainApp, self).__init__()
        QMainWindow.__init__(self)
        self.setupUi(self)
  

    def open_image(self):
        img = QFileDialog.getOpenFileName(self, 'Open file',
                                                  'c:\\')
        pixmap = QtGui.QPixmap(img[0])
        self.scene = QtWidgets.QGraphicsScene()
        self.item = QtWidgets.QGraphicsPixmapItem(pixmap)
        self.scene.addItem(self.item)
        self.graphicsView.setScene(self.scene)
        self.image =Image.open(img[0])
       
    def mouseMoveEvent(self,e):
        print(e.pos())

def main():
    app = QApplication(sys.argv)
    windows = MainApp()
    windows.show()
    app.exec_()


if __name__ == '__main__':
    main()

【问题讨论】:

  • 我添加了 MRE
  • 您好像忘记提供app.ui

标签: python pyqt qgraphicsscene qgraphicsitem qmouseevent


【解决方案1】:

小部件仅在启用mouseTracking 时接收鼠标移动事件(大多数小部件默认禁用)。

另外,如果您想在图形场景中跟踪鼠标事件,您必须覆盖场景的 mouseMoveEvent 安装事件过滤器。

请注意,我删除了__init__ 中的以下行:

QMainWindow.__init__(self)

您已经在第一行调用了super().__init()__,无需再次调用。

class MainApp(QMainWindow, MainUI):
    def __init__(self):
        super(MainApp, self).__init__()
        self.setupUi(self)

        # you could set this in QDesigner instead
        self.graphicsView.setMouseTracking(True)

    def open_image(self):
        # ...
        self.scene.installEventFilter(self)

    def eventFilter(self, source, event):
        if event.type() == QEvent.GraphicsSceneMouseMove:
            item = self.scene.itemAt(event.scenePos(), QTransform())
            if isinstance(item, QGraphicsPixmapItem):
                # map the scene position to item coordinates
                map = item.mapFromScene(event.scenePos())
                print('mouse is on pixmap at coordinates {}, {}'.format(
                    map.x(), map.y()))
        return super().eventFilter(source, event)

【讨论】:

  • 请你给我解释一下这个解决方案,它工作得很好,但我想了解它是如何工作的,如果你能给我一个更进一步的来源,非常感谢
  • 您可以在官方文档中阅读更多关于event filters 的信息(它是面向 C++ 的,但对于 PyQt,99% 的概念和函数/类名是相同的)。基本上,事件过滤器“拦截”将由安装它的对象(在本例中为图形场景)处理的事件,通过实现它,您可以检查特定事件并采取相应措施:在这种情况下,我' m 检测到 GraphicsSceneMouseMove,所以我可以得到它的坐标,并将它们映射到项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
相关资源
最近更新 更多