PyQt5之QGraphics 005 GraphicsItem的动态波纹线

我们做选择框,希望边框线是动态波纹线的,这样更加使人注意力在要选择的图形上。

如下:

主要是用一个计数器,使线移动。这个想法是从Tiled上看到的,代码也是从上面借鉴来的。

"""
QGraphicsItem 的动态波纹线
By Linyoubiao
2020-03-21
"""

from PyQt5.QtWidgets import (QApplication, QGraphicsItem, QGraphicsScene, QGraphicsView)
from PyQt5.QtCore import (QLine, QLineF, QPoint, QPointF, QRect, QRectF, QTimer, QTime, Qt)
from PyQt5.QtGui import (QBrush, QPen, QImage, QPicture, QPixmap,
                         QPainter, QPainterPath, QColor)


class Shape(QGraphicsItem):
    shape_rect = QRectF(QPointF(0, 0), QPointF(100, 100))

    def __init__(self):
        super(Shape, self).__init__()
        self.timer = QTimer()
        self.timer.timeout.connect(self.timerEvent)
        self.timer.start(100)
        self.line_offset = 0

        self.setFlag(QGraphicsItem.ItemIsMovable)

    def timerEvent(self):
        self.line_offset += 1
        self.prepareGeometryChange()

    def boundingRect(self):
        return QRectF(QPointF(0, 0), QPointF(500, 500))

    def paint(self, painter, option, widget):
        pen = QPen(Qt.black, 2.0, Qt.SolidLine)
        pen.setCosmetic(False)
        painter.setPen(pen)
        painter.drawRect(Shape.shape_rect)

        pen.setColor(Qt.white)
        pen.setCapStyle(Qt.FlatCap)
        pen.setDashPattern((5, 5))
        pen.setDashOffset(self.line_offset)
        painter.setPen(pen)
        painter.drawRect(Shape.shape_rect)


class Shape_Scene(QGraphicsScene):
    def __init__(self):
        super(Shape_Scene, self).__init__()
        self.shape = Shape()
        self.addItem(self.shape)


class Shape_View(QGraphicsView):
    def __init__(self, parent=None):
        super(Shape_View, self).__init__(parent)
        self.shape_scene = Shape_Scene()
        self.setScene(self.shape_scene)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)

    mainView = Shape_View()
    mainView.show()

    sys.exit(app.exec_())

 

多谢。

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