【发布时间】:2021-03-30 14:56:25
【问题描述】:
我是 Qt 的新手,尤其是 PyQt5。我正在尝试使用 QGraphicsView、QGraphicsScene 和 QGraphicsPixmapItem 开发一个 GUI。我的目标是在用户单击场景时向场景添加项目(使用 QGraphicsScene 子类中的 mousePressedEvent() 实现),并且使用 mouseMoveEvent(),我能够移动元素。
然后,我发现,通过我的实现,可以像从边界矩形外“推动”它们一样移动项目。所以,为了解决这个问题,经过一番搜索,我决定实现一个QGraphicsPixmapItem的子类来实现它自己的事件函数。
尽管如此,我发现我的项目无法识别 mousePressed 或 mouseMove 事件,而是来自 QGraphicsScene 的事件。我的问题是:
- 在不遇到我遇到的第一个问题的情况下移动元素的最有效方法是什么?
- 是否可以同时结合场景和项目事件处理程序?我还没有完全理解事件传播。
为了更清楚,我把我的代码留在下面,以解决移动问题:
#!/usr/bin/env python3
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class GraphicsScene(QGraphicsScene):
def __init__(self):
super(GraphicsScene, self).__init__()
self.image = 'car.png' # Image of your own
self.inserted = False
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton and not self.inserted:
img = QPixmap(self.image).scaled(50, 50, Qt.KeepAspectRatio)
pixmap = QGraphicsPixmapItem(img)
offset = pixmap.boundingRect().topLeft() - pixmap.boundingRect().center()
pixmap.setOffset(offset.x(), offset.y())
pixmap.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
pixmap.setFlag(QGraphicsItem.ItemIsSelectable, True)
pixmap.setPos(event.scenePos())
super().mousePressEvent(event)
self.addItem(pixmap)
self.inserted = True
else:
pass
def mouseMoveEvent(self, event):
super().mouseMoveEvent(event)
item = self.itemAt(event.scenePos(), QTransform())
if item is None:
return
orig_cursor_position = event.lastScenePos()
updated_cursor_position = event.scenePos()
orig_position = item.scenePos()
updated_cursor_x = updated_cursor_position.x() - orig_cursor_position.x() + orig_position.x()
updated_cursor_y = updated_cursor_position.y() - orig_cursor_position.y() + orig_position.y()
item.setPos(QPointF(updated_cursor_x, updated_cursor_y))
class MainWindow(QMainWindow):
def __init__(self):
super(QMainWindow, self).__init__()
self.resize(600, 600)
self.canvas = QGraphicsView()
self.scene = GraphicsScene()
self.setCentralWidget(self.canvas)
self.canvas.setScene(self.scene)
def showEvent(self, event):
self.canvas.setSceneRect(QRectF(self.canvas.viewport().rect()))
def resizeEvent(self, event):
self.canvas.setSceneRect(QRectF(self.canvas.viewport().rect()))
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
【问题讨论】:
-
@eyllanesc 我已经编辑了这个问题以便更好地理解。谢谢!
-
该代码不是 MRE,请阅读链接。尝试在
pixmap = QGraphicsPixmapItem(img)之前添加super().mousePressedEvent(event) -
@eyllanesc 我已经重写了代码,希望现在一切正常(这是我在这里的第一篇文章;感谢大家的帮助)。此外,我添加了您的线路,但仍然无法正常工作。
标签: python pyqt5 qgraphicsscene qgraphicsitem