python - 使用自定义项从 QGraphicsScene 接收信号
问题描述
我正在使用 pyqt5 graphicsscene 对棋盘进行建模。
场景填充了 2 种类型的自定义 QGraphicsItem:Case(不可移动),Piece(可移动)
我覆盖了 Piece 对象的 mousepressevent、mousemoveevent 和 mousereleaseevent,以便它始终位于案例的中心。不确定这是否是最佳选择,因为我可以自定义场景。
现在我想从场景或 Piece 对象接收信号(关于源位置、目标位置的信息),有什么好的方法呢?
我是 Qt 新手,不了解 C++ 语法,因此很难遵循官方文档。
class Pawn(QGraphicsItem):
def __init__(self, x_coord, y_coord, color):
super().__init__()
self.x_coord = x_coord
self.y_coord = y_coord
self.color = color
self.setPos(x_coord*30 + 5, y_coord*30 + 5)
self.setFlag(QGraphicsItem.ItemIsMovable)
self.setZValue(2)
self.sourcePos = QPointF(x_coord*30 + 5, y_coord*30 + 5)
self.destinationPos = None
def paint(self, painter, option, widget):
painter.setBrush(QColor(self.color))
painter.drawEllipse(0, 0, 20, 20)
def boundingRect(self):
return QRectF(0, 0, 20, 20)
def mousePressEvent(self, event):
for item in self.scene().items():
if isinstance(item, Pawn) and item != self:
item.setZValue(2)
self.setZValue(3)
def mouseMoveEvent(self, event):
movePos = self.mapToScene(event.pos())
self.setPos(movePos.x() - 15, movePos.y() - 15)
def mouseReleaseEvent(self, event):
dropPos = self.mapToScene(event.pos())
dropCase = None
for item in self.scene().items(dropPos.x(), dropPos.y(), 0.0001, 0.0001,
Qt.IntersectsItemShape,
Qt.AscendingOrder):
if isinstance(item, Case):
dropCase = item
if dropCase:
newP = dropCase.scenePos()
self.setPos(newP.x()+5, newP.y()+5)
self.destinationPos = QPointF(newP.x()+5, newP.y()+5)
"""here i want to send the signal that the item changed position
from self.sourcePos to self.destinationPos"""
self.sourcePos = self.destinationPos
else:
self.setPos(self.sourcePos)
解决方案
推荐阅读
- perl - 在perl中用引号打印@
- json - JSON 模式中的选择元素
- r - R-如何根据向量是否包含值来创建 T/F 矩阵
- go - GoLang 附加到嵌套切片
- javascript - 如何在我的网站上集成 Adyen
- c# - 根据另一个对象的反射设置属性类型
- html - 如何从引导程序的下拉菜单中删除边框?
- microsoft-graph-api - 在图形资源管理器中放置共享点文件时出现 403 错误
- php - 如何使管理员可以将特定类型的用户(学生)与 laravel 中的另一种类型的用户(他们各自的导师)匹配
- function - 在 F# 中调用函数后,如何在 F# 中重复函数?