Home > Net >  Unable to click, select or move QGraphicsEllipseItem
Unable to click, select or move QGraphicsEllipseItem

Time:09-07

A small snippet I am using to understand QGraphicsEllipseItem. From my understanding , based on the flags set I should be able to move and capture mouse events but am unable to do so. Any help or guidance ?

import sys

from PySide6.QtCore import QPoint, QRectF
from PySide6.QtGui import QPainter, QPainterPath
from PySide6.QtWidgets import (
    QApplication,
    QGraphicsEllipseItem,
    QGraphicsScene,
    QGraphicsSceneMouseEvent,
    QGraphicsView,
    QStyleOptionGraphicsItem,
    QGraphicsItem,
    QWidget,
)


class Icon(QGraphicsEllipseItem):
    def __init__(self) -> None:
        super().__init__(None)

        self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable)

    def rect(self) -> QRectF:
        return QRectF(QPoint(0, 0), QPoint(48, 48))

    def boundingRect(self) -> QRectF:
        return QRectF(QPoint(0, 0), QPoint(48, 48))

    def mousePressEvent(self, event: QGraphicsSceneMouseEvent) -> None:
        print("mousePressEvent")
        return super().mousePressEvent(event)

    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget) -> None:
        outlinePath = QPainterPath()
        outlinePath.addEllipse(self.boundingRect())
        painter.drawPath(outlinePath.simplified())
        return super().paint(painter, option, widget)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = QGraphicsView()
    scene = QGraphicsScene(0, 0, 400, 200)

    c1 = Icon()
    scene.addItem(c1)
    c1.setPos(200, 100)

    view.setScene(scene)
    view.show()
    app.exec()


Thank you in advance...

CodePudding user response:

You are overwriting the rect method making the position static and unmovable.

Just set the rect using setRect and don't overwrite those methods and you should receive the mouse events and be able to move it then.


class Icon(QGraphicsEllipseItem):

    def __init__(self) -> None:
        super().__init__(None)
        self.setRect(QRectF(QPoint(0, 0), QPoint(48, 48)))
        self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable)

    def boundingRect(self) -> QRectF:
        return QRectF(QPoint(0, 0), QPoint(48, 48))

    def mousePressEvent(self, event: QGraphicsSceneMouseEvent) -> None:
        print("mousePressEvent")
        return super().mousePressEvent(event)

    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget) -> None:
        outlinePath = QPainterPath()
        outlinePath.addEllipse(self.boundingRect())
        painter.drawPath(outlinePath.simplified())
        return super().paint(painter, option, widget)
  • Related