PyQt5之QGraphics 010 QGraphicsItem之鼠标控制流程选择篇

每个QGrphicsItem可以方便接受鼠标和键盘的指令,从而产生我们要的操作。

以下是完成shift+鼠标左键选择操作。

主要是重载 mousePressEvent(self, event) 函数。

代码如下:

"""
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)

 

你可能感兴趣的:(PyQt5之QGraphics)