PyQt5의 QGraphics 010 QGraphicsItem 마우스 제어 프로세스 선택편

2593 단어 PyQt5의 QGraphics
모든 QGrphicsItem은 마우스와 키보드의 명령을 쉽게 받아들여 우리가 원하는 조작을 할 수 있다.
다음은 shift + 마우스 왼쪽 단추 선택 작업을 완료하는 것입니다.
주로 mousePressEvent(self, 이벤트) 함수를 다시 불러옵니다.
코드는 다음과 같습니다.
"""
PyQt AND OpenCV
By LiNYoUBiAo
2020/4/3 22:13
"""
from PyQt5.QtWidgets import (QApplication, QGraphicsItem, QGraphicsScene,
                             QGraphicsView)
from PyQt5.QtGui import (QBrush, QPen)
from PyQt5.QtCore import (QPoint, QPointF, QLine, QLineF,
                          QRect, QRectF, Qt)


class MyShape(QGraphicsItem):
    def __init__(self):
        super(MyShape, self).__init__()
        self.setFlag(QGraphicsItem.ItemIsSelectable)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.isCanMove = False
        self.blobColor = Qt.darkRed

    def boundingRect(self):
        return QRectF(0, 0, 80, 80)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            if event.modifiers() == Qt.ShiftModifier:
                self.isCanMove = True
                self.blobColor = Qt.red
                self.update()
            else:
                super(MyShape, self).mousePressEvent(event)
                event.accept()
        else:
            event.ignore()

    def mouseMoveEvent(self, event):
        if self.isCanMove:
            self.update()
            super(MyShape, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        self.isCanMove = False
        self.blobColor = Qt.darkRed
        self.update()
        super(MyShape, self).mouseReleaseEvent(event)

    def paint(self, painter, option, widget=None):
        painter.setBrush(self.blobColor)
        painter.drawRect(QRectF(1, 1, 70, 70))


class MyScene(QGraphicsScene):
    def __init__(self):
        super(MyScene, self).__init__()

    def mousePressEvent(self, event):
        super(MyScene, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        super(MyScene, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        super(MyScene, self).mouseReleaseEvent(event)


class MyView(QGraphicsView):
    def __init__(self):
        super(MyView, self).__init__()


if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)

    shape = MyShape()
    scene = MyScene()
    scene.addItem(shape)
    view = MyView()
    view.setScene(scene)
    view.show()

    sys.exit(app.exec_())


그 중에서 아래 함수를 통해 물체를 선택하고 이동할 수 있다.
self.setFlag(QGraphicsItem.ItemIsSelectable)
self.setFlag(QGraphicsItem.ItemIsMovable)

좋은 웹페이지 즐겨찾기