Question

I'm playing around with pyqt4. I want to create a custom widget, and draw some rectangles on it. I've already used similar stuff on QCanvas, but now I just want it to draw my rectangles if I create an object from my custom class...

self.IND = [] contains colors (QColor)

class labelBOX(QtGui.QWidget):
    def __init__(self, parent, X,Y, holes):
        super(labelBOX , self).__init__(parent)
        self.gridL = QtGui.QGridLayout(self)
        self.setGeometry(X,Y, 50, 100)
        self.setWindowTitle("LEGEND")
        self.HOLES = holes
        self.LBL = []
        self.setLayout(self.gridL)
        self.i = 0
        self.j = 0
        self.genLBL()
        self.IND = []
        self.qp = QtGui.QPainter()
        self.genIND(self.qp)

        self.show()


    """
    Generate labels
    """
    def genLBL(self):
        for k in range(len(self.HOLES)):
    self.LBL.append(QtGui.QLabel(QtCore.QString(self.HOLES[k].getNAME())))

for k in range(len(self.LBL)):
    self.gridL.addWidget(self.LBL[k])


    """
    Generate indicators
    """
    def genIND(self, qp):
        self.i = 0
        self.j = 1
        for k in range(len(self.HOLES)):
            self.IND.append(self.HOLES[k].getCOLOR())

        for k in range(len(self.IND)):
                    qp.setBrush(self.IND[k])
        self.gridL.addWidget(qp.fillRect(10,10,50,50, ))






class OTHERCLASS():
    ....
    self.WIDGET = labelBOX(self, 550, 350, dummyLOAD)
    ....
Was it helpful?

Solution

If you want to manually draw on the custom widget then you can override the paintEvent or use absolute positioning and place the rectangles where you want. The paintEvent might be better, but it is more complex. http://zetcode.com/gui/pyqt4/drawing/ example and http://pyqt.sourceforge.net/Docs/PyQt4/qpainter.html is the class reference. I wrote an example below.

def paintEvent(self, event):
    super().paintEvent(event)

    painter = QtGui.QPainter()
    painter.begin(self)

    rect = self.rect()

    gradient = QtGui.QRadialGradient(rect.center(), rect.width())
    gradient.setColorAt(0.0, QtGui.QColor(255, 255, 255, 10)
    gradient.setColorAt(0.90, QtGui.QColor(0, 0, 0, 255))
    gradient.setColorAt(0.98, QtGui.QColor(0, 0, 0, 100))

    painter.setPen(QtGui.QColor(0, 0, 0) # Pen works on the border
    painter.setBrush(grad) # Main color

    # Draw the rectangle
    painter.drawRect(rect) # Try to keep your rectangle within the widget area

    painter.end()
    event.accept()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top