1

我尝试创建一个程序来操作图像,我想要鼠标在 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()
4

1 回答 1

2

小部件仅在启用时才会接收鼠标移动事件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)
于 2020-07-05T17:31:14.430 回答