自定义QGraphicsItem无法正常移动

问题描述 投票:0回答:1

我试图自定义QGraphicsItem来制作一个可移动但可以放置在箱子上居中的典当项目(为棋盘或国际象棋棋盘建模)

我一开始就遇到了问题,因为我的自定义图形项无法正确移动,在拖动时它留下了痕迹,对象消失了

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
                         QGraphicsView, QGraphicsScene, QGraphicsItem)
from PyQt5.QtGui import QPen, QBrush, QTransform
from PyQt5.QtCore import Qt, QRectF, QPointF

class Pawn(QGraphicsItem):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setFlag(QGraphicsItem.ItemIsMovable)

    def paint(self, painter, options, widget):
        painter.drawEllipse(0, 0, 30, 30)

    def boundingRect(self):
        return QRectF(self.x() - 10, self.y() - 10, 50, 50)


class MainWin(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        scene = QGraphicsScene()
        view = QGraphicsView(scene, self)
        view.setGeometry(0, 0, 290, 290)

        ellipse = scene.addEllipse(200, 200, 20, 20, QPen(Qt.yellow), QBrush(Qt.yellow))
        custom = Pawn()
        scene.addItem(custom)

        ellipse.setFlag(QGraphicsItem.ItemIsMovable)

        self.setWindowTitle('doodling')
        self.setGeometry(200, 200, 300, 300)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWin()
    sys.exit(app.exec_())
python pyqt pyqt5 qgraphicsscene qgraphicsitem
1个回答
0
投票

boundingRect()是一个矩形,用于指示应该绘制的区域,该区域是相对于项目的坐标系,而不是场景的坐标系,因此,您不应使用boundingRect()x()

y()
© www.soinside.com 2019 - 2024. All rights reserved.