从QGraphicscene接收带有自定义项的信号

2024-09-29 21:45:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pyqt5 Graphicscene为一个棋盘建模

场景中填充了两种类型的自定义QGraphicsItem:箱子(不可移动)、工件(可移动)

我覆盖了Piece对象的mousepressevent mousemoveevent和mousereleaseevent,使其始终位于案例的中心。我不确定这是否是最好的选择,因为我可以定制场景

现在我想从场景或工件对象接收信号(关于源位置、目标位置的信息),有什么好方法

<>我对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)

Tags: selfeventdef场景itemcolorpaintercoord

热门问题