我已经编写了我的第一个自定义窗口小部件 - 一个用于显示后台任务进度的小状态指示灯。我做错了,因为当鼠标结束时,我反复继续发出以下错误,或者与包含自定义小部件的Qt窗口进行交互:
QPainter::begin: Paint device returned engine == 0, type: 2
应用程序不会崩溃,但会继续将此错误转储到std out。我对Qt相当新,并且已经四处寻找,试图找出如何解决这个问题无济于事。我希望有更多Qt经验的人能够通过正确的方式指导我使用paintEvent()实现自定义小部件。我附上了以下代码:
from PySide import QtGui, QtCore
class LightWidget(QtGui.QLabel):
def __init__(self,parent=None):
super(LightWidget,self).__init__(parent)
self.setPixmap(QtGui.QPixmap())
self.setMinimumSize(15,15)
self.setMaximumSize(15,15)
self.set_fill_color(.6,.6,.6)
self.set_line_color(0,0,0)
self.set_line_width(1)
def set_fill_color(self,r,b,g,a=1.0,hsv=False):
ncolor=QtGui.QColor()
if hsv:
ncolor.setHsvF(r,g,b,a)
else:
ncolor.setRgbF(r,g,b,a)
self._fill_color=ncolor
def set_line_color(self,r,g,b,a=1.0,hsv=False):
ncolor=QtGui.QColor()
if hsv:
ncolor.setHsvF(r,g,b,a)
else:
ncolor.setRgbF(r,g,b,a)
self._line_color=(ncolor)
def set_line_width(self,width):
self._line_width=width
def paintEvent(self,e):
painter=QtGui.QPainter(self.pixmap())
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
radx=self.width()*0.5
rady=self.height()*0.5
offset=self._line_width
center=QtCore.QPoint(radx,rady)
gradient = QtGui.QRadialGradient(center
,radx
,QtCore.QPointF(radx*0.5, rady*0.5))
c_color = QtGui.QColor(0,0,0,0)
c_color.setHsvF(self._fill_color.hueF()
,self._fill_color.saturationF()
,max(min(self._fill_color.valueF()*1.5,1.0),0) )
o_color = QtGui.QColor(0,0,0,0)
o_color.setHsvF(self._fill_color.hueF()
,self._fill_color.saturationF()
,max(min(self._fill_color.valueF()*.5,1),0))
gradient.setColorAt(0, c_color)
gradient.setColorAt(0.25, self._fill_color)
gradient.setColorAt(1, o_color)
pen=QtGui.QPen()
pen.setColor(self._line_color)
pen.setWidthF(self._line_width)
brush = QtGui.QBrush(gradient)
painter.setPen(pen)
painter.setBrush(gradient)
painter.drawEllipse(center,radx-offset,rady-offset)
painter.end()
def test():
form = QtGui.QWidget()
wid = LightWidget(form)
form.setWindowTitle('Status Light Widget')
form.show()
return form
def main():
import sys
app = QtGui.QApplication(sys.argv)
window =test()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
答案 0 :(得分:0)
你将你画的内容混为一谈:
def paintEvent(self,e):
# Here you start the painter on the pixmap
painter=QtGui.QPainter(self.pixmap())
# But here you start it on the widget proper
painter.begin(self)
...
事实是,您不需要任何像素图,并且您不需要从QLabel
派生。从QWidget
派生,直接在小部件上绘画:
def paintEvent(self,e):
painter=QtGui.QPainter(self)
# The begin() is redundant. Don't invoke it.
...