我正在玩pyqt4
。我想在其上创建custom widget
和draw
一些矩形。我已经在QCanvas
上使用了类似的内容,但现在我只想让它在我的自定义类中创建一个对象时绘制我的rectangles
...
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)
....
答案 0 :(得分:0)
如果要在自定义小部件上手动绘制,则可以覆盖paintEvent或使用绝对定位并将矩形放置在所需的位置。 paintEvent可能会更好,但它更复杂。 http://zetcode.com/gui/pyqt4/drawing/示例和http://pyqt.sourceforge.net/Docs/PyQt4/qpainter.html是类引用。我在下面写了一个例子。
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()