Skip to content Skip to sidebar Skip to footer

Drawing A Rectangle In Pyqtgraph

I am trying to draw rectangles in pyqtgraph to show data in a 2D array, it is inside a window created in designer. Is there a way to draw a rectangle and save the object to a 2D ar

Solution 1:

The addItem method expects a graphics item as the docs points out:

addItem(item, *args, **kargs)

Add a graphics item to the view box. If the item has plot data (PlotDataItem, PlotCurveItem, ScatterPlotItem), it may be included in analysis performed by the PlotItem.

But you are passing a QRectF that is not. You could use a QGraphicsRectItem but the coordinates of the scene do not match the coordinates of the viewbox so you will have to implement a custom graphics item based on a GraphicsObject (as the basis I have taken the official example):

import sys

from PyQt5 import QtCore, QtGui, QtWidgets, uic

import pyqtgraph as pg


classRectItem(pg.GraphicsObject):
    def__init__(self, rect, parent=None):
        super().__init__(parent)
        self._rect = rect
        self.picture = QtGui.QPicture()
        self._generate_picture()

    @propertydefrect(self):
        return self._rect

    def_generate_picture(self):
        painter = QtGui.QPainter(self.picture)
        painter.setPen(pg.mkPen("w"))
        painter.setBrush(pg.mkBrush("g"))
        painter.drawRect(self.rect)
        painter.end()

    defpaint(self, painter, option, widget=None):
        painter.drawPicture(0, 0, self.picture)

    defboundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


classMainWindow(QtWidgets.QMainWindow):
    def__init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # Load the UI Page
        uic.loadUi("help.ui", self)
        self.showMaximized()
        self.draw_2d_square()

    defdraw_2d_square(self):
        rect_item = RectItem(QtCore.QRectF(0, 0, 4.5, 4.5))
        self.graphWidget_2D.addItem(rect_item)


defmain():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

enter image description here

Post a Comment for "Drawing A Rectangle In Pyqtgraph"