def paintEvent(self, event): 'Paint semi-transparent background, animated pattern, background text' QWidget.paintEvent(self, event) # make a painter p = QPainter(self) p.setRenderHint(QPainter.TextAntialiasing) p.setRenderHint(QPainter.HighQualityAntialiasing) # fill a rectangle with transparent painting p.fillRect(event.rect(), Qt.transparent) # animated random dots background pattern for i in range(4096): x = randint(9, self.size().width() - 9) y = randint(9, self.size().height() - 9) p.setPen(QPen(QColor(randint(200, 255), randint(200, 255), 255), 1)) p.drawPoint(x, y) # set pen to use white color p.setPen(QPen(QColor(randint(9, 255), randint(9, 255), 255), 1)) # Rotate painter 45 Degree p.rotate(35) # Set painter Font for text p.setFont(QFont('Ubuntu', 300)) # draw the background text, with antialiasing p.drawText(99, 199, "Radio") # Rotate -45 the QPen back ! p.rotate(-35) # set the pen to no pen p.setPen(Qt.NoPen) # Background Color p.setBrush(QColor(0, 0, 0)) # Background Opacity p.setOpacity(0.75) # Background Rounded Borders p.drawRoundedRect(self.rect(), 50, 50) # finalize the painter p.end()
def draw_pts(self): painter = QPainter(self.field) painter.setPen(QPen(Qt.red, 4)) painter.translate(self.field.width() / 2, self.field.height() / 2) for p in self.path.poses: pt = QPointF(p.x, p.y) painter.drawPoint(pt)
def updateSlice(self): if self.ctslice_rgba is None: return img = self.ctslice_rgba.copy() # if self.seeds is not None: # if self.mode_draw: # if self.contour_mode == 'fill': # self.composeRgba(img, self.seeds, # self.seeds_colortable) # elif self.contour_mode == 'contours': # self.get_contours(img, self.seeds) # else: # self.overRgba(img, self.seeds, # self.seeds_colortable) if self.contours is not None: # if self.contour_mode == 'fill': if self.contours_mode_is_fill: self.composeRgba(img, self.contours.transpose().ravel(order="F"), CONTOURS_COLORTABLE) # elif self.contour_mode == 'contours': else: self.get_contours(img, self.contours) # masking out pixels under circle # for i in self.circle_m: # img[i, :] = [0, 0, 255, 255] image = QImage(img.flatten(), self.slice_size[0], self.slice_size[1], QImage.Format_ARGB32).scaled( self.imagesize ) painter = QPainter(self.image) painter.drawImage(0, 0, image) if self.show_mode == self.SHOW_CONTOURS: # and self.centers is not None: if self.centers is not None: pts = self.centers.nonzero() pen = QPen(Qt.red, 3) painter.setPen(pen) for i in range(len(pts[0])): painter.drawPoint(pts[1][i] * self.grid[0], pts[0][i] * self.grid[1]) if self.circle_active: pen = QPen(Qt.red, 3) painter.setPen(pen) center_offset = 0 # 0.5 radius_offset = 0 # 0.5 painter.drawEllipse( QPoint( (self.mouse_cursor[0] + center_offset) * self.grid[0], (self.mouse_cursor[1] + center_offset) * self.grid[1], ), (self.circle_r + radius_offset) * self.grid[0], (self.circle_r + radius_offset) * self.grid[1], ) painter.end() self.update()
def updateSlice(self): if self.ctslice_rgba is None: return img = self.ctslice_rgba.copy() # if self.seeds is not None: # if self.mode_draw: # if self.contour_mode == 'fill': # self.composeRgba(img, self.seeds, # self.seeds_colortable) # elif self.contour_mode == 'contours': # self.get_contours(img, self.seeds) # else: # self.overRgba(img, self.seeds, # self.seeds_colortable) if self.contours is not None: # if self.contour_mode == 'fill': if self.contours_mode_is_fill: self.composeRgba(img, self.contours.transpose().ravel(order='F'), CONTOURS_COLORTABLE) # elif self.contour_mode == 'contours': else: self.get_contours(img, self.contours) # masking out pixels under circle # for i in self.circle_m: # img[i, :] = [0, 0, 255, 255] image = QImage(img.flatten(), self.slice_size[0], self.slice_size[1], QImage.Format_ARGB32).scaled(self.imagesize) painter = QPainter(self.image) painter.drawImage(0, 0, image) if self.show_mode == self.SHOW_CONTOURS: # and self.centers is not None: if self.centers is not None: pts = self.centers.nonzero() pen = QPen(Qt.red, 3) painter.setPen(pen) for i in range(len(pts[0])): painter.drawPoint(pts[1][i] * self.grid[0], pts[0][i] * self.grid[1]) if self.circle_active: pen = QPen(Qt.red, 3) painter.setPen(pen) center_offset = 0 #0.5 radius_offset = 0 #0.5 painter.drawEllipse( QPoint((self.mouse_cursor[0] + center_offset) * self.grid[0], (self.mouse_cursor[1] + center_offset) * self.grid[1]), (self.circle_r + radius_offset) * self.grid[0], (self.circle_r + radius_offset) * self.grid[1]) painter.end() self.update()
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue): print perpAxisLabel, perpAxisValue img = QImage(width, height, QImage.Format_ARGB32) img.fill(0) p = QPainter(img) p.setPen(QColor(255, 255, 255)) p.setBrush(QBrush(QColor(255, 255, 255))) def arrow(p, From, To, label): p.drawLine(From, To) p.drawText(To, label) offset = 10 arrow(p, QPoint(offset, offset), QPoint(offset, height - offset), axisLabels[1]) arrow(p, QPoint(offset, offset), QPoint(width - offset, offset), axisLabels[0]) p.drawText(2 * offset, 2 * offset, "%s=%d" % (perpAxisLabel, perpAxisValue)) fm = p.fontMetrics() size = fm.size(Qt.TextSingleLine, "updown") p.drawText(numpy.random.randint(offset, width - offset - size.width()), numpy.random.randint(offset, height - offset - size.height()), "updown") dots = [] numPixels = 0 while numPixels < 30: r = numpy.random.randint(1, 255) rx, ry = numpy.random.randint(offset, width - offset), numpy.random.randint( offset, height - offset) if img.pixel(rx, ry) != 0: continue p.setPen(QPen(QColor(r, r, r))) p.drawPoint(rx, ry) dots.append(((rx, ry), r)) numPixels += 1 p.end() img.save('test.png') a = qimage2ndarray.rgb_view(img) a = a[:, :, 0].squeeze().swapaxes(0, 1) for (rx, ry), r in dots: assert QColor.fromRgba(img.pixel(rx, ry)).red( ) == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % ( QColor.fromRgba(img.pixel(rx, ry)).red(), r) assert (a[rx, ry] == r), "a[%d,%d] == %d != %d)" % (rx, ry, a[rx, ry], r) return (a, dots)
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue): print perpAxisLabel, perpAxisValue img = QImage(width, height, QImage.Format_ARGB32) img.fill(0) p = QPainter(img) p.setPen(QColor(255, 255, 255)) p.setBrush(QBrush(QColor(255, 255, 255))) def arrow(p, From, To, label): p.drawLine(From, To) p.drawText(To, label) offset = 10 arrow(p, QPoint(offset, offset), QPoint(offset, height - offset), axisLabels[1]) arrow(p, QPoint(offset, offset), QPoint(width - offset, offset), axisLabels[0]) p.drawText(2 * offset, 2 * offset, "%s=%d" % (perpAxisLabel, perpAxisValue)) fm = p.fontMetrics() size = fm.size(Qt.TextSingleLine, "updown") p.drawText( numpy.random.randint(offset, width - offset - size.width()), numpy.random.randint(offset, height - offset - size.height()), "updown", ) dots = [] numPixels = 0 while numPixels < 30: r = numpy.random.randint(1, 255) rx, ry = numpy.random.randint(offset, width - offset), numpy.random.randint(offset, height - offset) if img.pixel(rx, ry) != 0: continue p.setPen(QPen(QColor(r, r, r))) p.drawPoint(rx, ry) dots.append(((rx, ry), r)) numPixels += 1 p.end() img.save("test.png") a = qimage2ndarray.rgb_view(img) a = a[:, :, 0].squeeze().swapaxes(0, 1) for (rx, ry), r in dots: assert QColor.fromRgba(img.pixel(rx, ry)).red() == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % ( QColor.fromRgba(img.pixel(rx, ry)).red(), r, ) assert a[rx, ry] == r, "a[%d,%d] == %d != %d)" % (rx, ry, a[rx, ry], r) return (a, dots)
def paintEvent(self, e): qpainter = QPainter() qpainter.begin(self) #Draw background qpainter.setBrush(self.backgroundBrush) qpainter.drawRect(QRect(0, 0, self.width(), self.height())) for p in self.points: qpainter.setPen(p.color) #To make points bigger, draw 9 pixel stencil around that point for dx in range(-1,2): for dy in range(-1,2): qpainter.drawPoint(p.x + dx, p.y + dy) qpainter.end()
def paintEvent(self, event): """Paint semi-transparent background,animated pattern,background text""" if not A11Y: p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setRenderHint(QPainter.HighQualityAntialiasing) p.fillRect(event.rect(), Qt.transparent) # animated random dots background pattern for i in range(4096): x = randint(25, self.size().width() - 25) y = randint(25, self.size().height() - 25) # p.setPen(QPen(QColor(randint(9, 255), 255, 255), 1)) p.drawPoint(x, y) p.setPen(QPen(Qt.white, 1)) p.rotate(40) p.setFont(QFont('Ubuntu', 250)) p.drawText(200, 99, "Nuitka") p.rotate(-40) p.setPen(Qt.NoPen) p.setBrush(QColor(0, 0, 0)) p.setOpacity(0.8) p.drawRoundedRect(self.rect(), 9, 9) p.end()
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, canvas): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, canvas) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1, -1) self._painter.translate(0, -canvas.height()) Renderer.set_canvas(self, canvas) def _get_canvas_size(self, pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" # FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" # FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs, ys = zip( transform.map(0.0, 0.0), transform.map(0.0, float(self.size[1])), transform.map(float(self.size[0]), float(self.size[1])), transform.map(float(self.size[0]), 0.0) ) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin // self._grid_spacing), int(xmax // self._grid_spacing + 1)) y_ticks = (int(ymin // self._grid_spacing), int(ymax // self._grid_spacing + 1)) self._painter.drawLines( [QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks)]) self._painter.drawLines( [QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks)]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor, factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx, dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0, 0, self.size[0], self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self, color=0, thickness=0): """Sets the line color and thickness. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(QPen(self.__qcolor(color), thickness)) def set_brush(self, color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self, points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon( QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb=None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx - ra, cy - ra, 2 * ra, 2 * rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x, y, w, h)) def draw_text(self, x, y, text, bgcolor=0): """Draws a text string at the defined position.""" # self.scale(0.1) self._painter.scale(0.1, -0.1) self.set_pen(0x000000) font = QFont('Decorative') font.setPointSize(1) self._painter.setFont(font) self._painter.drawText(x, y, QString(text)) def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1, y1, x2, y2)) def draw_point(self, x, y): """Draw a single point using the current pen at (x,y)""" self._painter.drawPoint(QPointF(x, y)) def draw_points(self, points): """Draw a set of points, given as [(x,y)], using the current pen""" self._painter.drawPoints(QPolygonF([QPointF(x, y) for x, y in points]))
class Example(QWidget): """Our oscilloscope view Display the module PCM data in a oscilloscope-style graph """ def __init__(self): super(Example, self).__init__() self.resize(480, 360) self.setWindowTitle('Player') self._qp = QPainter() self._thread = AnimationThread() self.connect(self._thread, SIGNAL("update_request"), self.update) self._thread.start() self.show() def paintEvent(self, event): """Draw the oscilloscope.""" self.lock.acquire() if (self.end_flag): self._thread.stop() app.quit() else: self._qp.begin(self) #self._qp.setPen(Qt.red) width = self.size().width() height = self.size().height() / 2 for i in range(width): pos = i * 4 left = struct.unpack('=h', self.data[pos:pos + 2])[0] right = struct.unpack('=h', self.data[pos + 2:pos + 4])[0] self._qp.drawPoint(i, height + height * (left + right) / 65536) self._qp.end() self.lock.release() def callback(self, in_data, frame_count, time_info, status): """Pyaudio callback function.""" size = frame_count * CHANNELS * WORD_SIZE self.lock.acquire() self.data = self.player.play_buffer(size) if self.data == None: self.end_flag = True self.lock.release() return (self.data, pyaudio.paContinue) def play(self, filename): """Load and play the module file.""" self.lock = Lock() self.end_flag = False self.player = Player() try: self.mod = Module(filename, self.player) except IOError, error: sys.stderr.write('{0}: {1}\n'.format(filename, error.strerror)) sys.exit(1) # Display module info print 'Name: {0.name}\nType: {0.type}'.format(self.mod) self._audio = pyaudio.PyAudio() self._stream = self._audio.open( format = self._audio.get_format_from_width(WORD_SIZE), channels = CHANNELS, rate = SAMPLE_RATE, output = True, stream_callback = self.callback) self.player.start(SAMPLE_RATE) self._stream.start_stream()
def paintEvent(self, e): global polygons, currentMatrix, lights, ka, kd, ks, ksp qpainter = QPainter() qpainter.begin(self) z_buffer = {} #Draw background qpainter.setBrush(self.backgroundBrush) qpainter.drawRect(QRect(0, 0, self.width(), self.height())) if self.displayFunct is not None: self.displayFunct(self) polyIndex = 1 for poly in polygons: points = {} lastPoint = None normal = self.cameraPosition.getNormal() if len(poly) > 2: v1 = poly[1] - poly[0] v2 = poly[2] - poly[0] normal = v1.vectorProduct(v2).normalize() otherNormal = v1.vectorProduct(v2).normalize() otherNormal.multMatrix(self.worldToCameraMatrix) p0temp = arcPoint(poly[0].x, poly[0].y, poly[0].z) p1temp = arcPoint(poly[1].x, poly[1].y, poly[1].z) p2temp = arcPoint(poly[2].x, poly[2].y, poly[2].z) p0temp.multMatrix(self.worldToCameraMatrix) p1temp.multMatrix(self.worldToCameraMatrix) p2temp.multMatrix(self.worldToCameraMatrix) v1temp = p1temp - p0temp v2temp = p2temp - p0temp transformedNormal = v1temp.vectorProduct(v2temp).normalize() if transformedNormal.z < 0: continue poly.append(arcPoint(poly[0])) firstPointAdded = False for p in poly: I = 1.0 if len(lights) > 0: I = 0.0 for l in lights: lv = l - p spec = self.cameraPosition.getNormal().dotProduct(l.getNormal())**ksp #ln = l.getNormal() #h = 2*normal.dotProduct(ln)*normal - ln #spec = self.cameraPosition.getNormal().dotProduct(h)**ksp I += (ka + kd*normal.dotProduct(lv.getNormal()) + ks*spec)/3 I = I/len(lights) if I <= 0: p.color.setRed(0) p.color.setGreen(0) p.color.setBlue(0) else: r = p.color.red()*I g = p.color.green()*I b = p.color.blue()*I p.color.setRed(r) p.color.setGreen(g) p.color.setBlue(b) p.multMatrix(self.worldToCameraMatrix) p.multMatrix(self.projectionMatrix) p.x = int(round(self.widthRatio*p.x + self.widthRatio*(-self.minX))) p.y = int(round(self.height() - 1 - (self.heightRatio*p.y + self.heightRatio*(-self.minY)))) if lastPoint is not None and p.y != lastPoint.y: mx = p.x - lastPoint.x my = p.y - lastPoint.y mz = p.z - lastPoint.z mRed = p.color.red() - lastPoint.color.red() mGreen = p.color.green() - lastPoint.color.green() mBlue = p.color.blue() - lastPoint.color.blue() s = max(abs(mx), abs(my)) if s == 0: continue dx = 1.0*mx/s dy = 1.0*my/s dz = 1.0*mz/s dRed = 1.0*mRed/s dGreen = 1.0*mGreen/s dBlue = 1.0*mBlue/s for i in range(1, s): x = int(lastPoint.x + dx*i) y = int(lastPoint.y + dy*i) z = lastPoint.z + dz*i r = lastPoint.color.red() + dRed*i g = lastPoint.color.green() + dGreen*i b = lastPoint.color.blue() + dBlue*i if y in points: points[y].append(arcPoint(x, y, z, QColor(r, g, b))) else: points[y] = [arcPoint(x, y, z, QColor(r, g, b))] lastPoint = p if p == poly[0] and firstPointAdded: continue firstPointAdded = True if p.y in points: points[p.y].append(p) else: points[p.y] = [p] for y in points.keys(): p1 = points[y][0] if len(points[y]) == 1: qpainter.setPen(p1.color) if y in z_buffer: if p1.x in z_buffer[y]: if p1.z > z_buffer[y][p1.x]: qpainter.drawPoint(p1.x, y) z_buffer[y][p1.x] = p1.z else: qpainter.drawPoint(p1.x, y) z_buffer[y][p1.x] = p1.z else: z_buffer[y] = {p1.x: p1.z} qpainter.drawPoint(p1.x, y) continue for index in range(1, len(points[y])): p1 = points[y][index-1] p2 = points[y][index] mx = p2.x - p1.x mz = p2.z - p1.z mRed = p2.color.red() - p1.color.red() mGreen = p2.color.green() - p1.color.green() mBlue = p2.color.blue() - p1.color.blue() s = abs(mx) if s == 0: continue dx = 1.0*mx/s dz = 1.0*mz/s dRed = 1.0*mRed/s dGreen = 1.0*mGreen/s dBlue = 1.0*mBlue/s if y not in z_buffer: z_buffer[y] = {} for i in range(0, s+1): x = int(p1.x + dx*i) z = p1.z + dz*i r = p1.color.red() + dRed*i g = p1.color.green() + dGreen*i b = p1.color.blue() + dBlue*i qpainter.setPen(QColor(r, g, b)) if x in z_buffer[y]: if z > z_buffer[y][x]: qpainter.drawPoint(x, y) z_buffer[y][x] = z else: z_buffer[y][x] = z qpainter.drawPoint(x, y) polyIndex += 1 arcClearScreen() qpainter.end()
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1, -1) self._painter.translate(0, -canvas.height()) Renderer.set_canvas(self, canvas) def _get_canvas_size(self, pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs, ys = zip(transform.map(0.0, 0.0), transform.map(0.0, float(self.size[1])), transform.map(float(self.size[0]), float(self.size[1])), transform.map(float(self.size[0]), 0.0)) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin // self._grid_spacing), int(xmax // self._grid_spacing + 1)) y_ticks = (int(ymin // self._grid_spacing), int(ymax // self._grid_spacing + 1)) self._painter.drawLines([ QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks) ]) self._painter.drawLines([ QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks) ]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor, factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx, dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0, 0, self.size[0], self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self, color=0, thickness=0): """Sets the line color and thickness. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(QPen(self.__qcolor(color), thickness)) def set_brush(self, color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self, points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon( QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb=None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx - ra, cy - ra, 2 * ra, 2 * rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x, y, w, h)) def draw_text(self, text, x, y, bgcolor=0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1, y1, x2, y2)) def draw_point(self, x, y): """Draw a single point using the current pen at (x,y)""" self._painter.drawPoint(QPointF(x, y)) def draw_points(self, points): """Draw a set of points, given as [(x,y)], using the current pen""" self._painter.drawPoints(QPolygonF([QPointF(x, y) for x, y in points]))
def paintEvent(self, event): painter = QPainter(self) width = self.width() height = self.height() if DEBUG: painter.fillRect(0, 0, width, height, Qt.blue) else: painter.fillRect(event.rect(), self.plot.canvas_color) y_min_scale = self.plot.y_scale.value_min y_max_scale = self.plot.y_scale.value_max factor_x = float(width) / self.plot.x_diff factor_y = float(height - 1) / max( y_max_scale - y_min_scale, EPSILON) # -1 to accommodate the 1px width of the curve if self.plot.x_min != None and self.plot.x_max != None: x_min = self.plot.x_min x_max = self.plot.x_max if self.plot.curve_start == 'left': curve_x_offset = 0 else: curve_x_offset = round( (self.plot.x_diff - (x_max - x_min)) * factor_x) transform = QTransform() transform.translate( curve_x_offset, height - 1 + self.plot.curve_y_offset ) # -1 to accommodate the 1px width of the curve transform.scale(factor_x, -factor_y) transform.translate(-x_min, -y_min_scale) if self.plot.curve_motion_granularity > 1: self.plot.partial_update_width = math.ceil( transform.map(QLineF(0, 0, 1.5, 0)).length()) inverted_event_rect = transform.inverted()[0].mapRect( QRectF(event.rect())) painter.save() painter.setTransform(transform) if False and self.plot.curves_visible[0]: # Currently unused support for bar graphs. # If we need this later on we should add an option to the # PlotWidget for it. # I tested this for the Sound Pressure Level Bricklet and it works, # but it didnt't look good. curve_x = self.plot.curves_x[0] curve_y = self.plot.curves_y[0] t = time.time() if self.max_points == None: self.max_points = [] for y in curve_y: self.max_points.append((t, y)) else: for i in range(len(curve_y)): if (curve_y[i] > self.max_points[i][1]) or ( (t - self.max_points[i][0]) > 5): self.max_points[i] = (t, curve_y[i]) for i in range(len(self.plot.curves_x[0])): painter.setPen(self.plot.curve_configs[0].color) painter.drawLine(QPoint(curve_x[i], 0), QPoint(curve_x[i], curve_y[i])) painter.setPen(Qt.white) painter.drawLine(QPoint(curve_x[i], curve_y[i]), QPoint(curve_x[i], y_max_scale)) painter.setPen(Qt.darkGreen) painter.drawPoint(QPoint(curve_x[i], self.max_points[i][1])) else: for c in range(len(self.plot.curves_x)): if not self.plot.curves_visible[c]: continue curve_x = self.plot.curves_x[c] curve_y = self.plot.curves_y[c] path = QPainterPath() lineTo = path.lineTo if self.plot.curve_motion_granularity > 1: start = max( min( bisect.bisect_left(curve_x, inverted_event_rect.left()), len(curve_x) - 1) - 1, 0) else: start = 0 path.moveTo(curve_x[start], curve_y[start]) for i in xrange(start + 1, len(curve_x)): lineTo(curve_x[i], curve_y[i]) painter.setPen(self.plot.curve_configs[c].color) painter.drawPath(path) painter.restore()
def paintEvent(self, event): QWidget.paintEvent(self, event) width, height = self.width(), self.height() polygon = QPolygon() for i, rate in enumerate(self.loads): x = width - i * self.pointDistance y = height - rate * height if x < self.boxWidth: break polygon.append(QPoint(x, y)) painter = QPainter(self) pen = QPen() pen.setColor(Qt.darkGreen) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing, True) #画网格 painter.setOpacity(0.5) gridSize = self.pointDistance * 4 deltaX = (width - self.boxWidth) % gridSize + self.boxWidth deltaY = height % gridSize for i in range(int(width / gridSize)): x = deltaX + gridSize * i painter.drawLine(x, 0, x, height) for j in range(int(height / gridSize)): y = j * gridSize + deltaY painter.drawLine(self.boxWidth, y, width, y) #画折线 pen.setColor(Qt.darkCyan) pen.setWidth(2) painter.setPen(pen) painter.setOpacity(1) painter.drawPolyline(polygon) #画展示框 if len(self.loads) > 0: rate = self.loads[0] else: rate = 1.0 rect1 = QRect(4, height * 0.05, self.boxWidth - 9, height * 0.7) rect2 = QRect(4, height * 0.8, self.boxWidth - 9, height * 0.2) centerX = int(rect1.width() / 2) + 1 pen.setWidth(1) for i in range(rect1.height()): if i % 4 == 0: continue if (rect1.height() - i) / rect1.height() > rate: pen.setColor(Qt.darkGreen) else: pen.setColor(Qt.green) painter.setPen(pen) for j in range(rect1.width()): if centerX - 1 <= j <= centerX + 1: continue painter.drawPoint(rect1.x() + j, rect1.y() + i) pen.setColor(Qt.black) painter.setPen(pen) painter.drawText(rect2, Qt.AlignHCenter | Qt.AlignVCenter, str(int(rate * 100)) + "%")