首页 > 解决方案 > 使用自定义项从 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)

标签: pythonpyqtpyqt5qgraphicssceneqgraphicsitem

解决方案


推荐阅读