def get_icon(path: str) -> QPicture: if path in _icons_loaded: return _icons_loaded[path] pic = QPicture() pic.load(path) _icons_loaded[path] = pic return pic
def generatePicture(self): ''' 每个小的K线 ''' self.picture = QPicture() p = QPainter(self.picture) p.setPen(pg.mkPen('w'))# 白色 w = (self.data[1][0] - self.data[0][0]) / 3.# 每个K线的宽度 for (t, date, close, open, high, low, price_change) in self.data: # t:每个汇率数据的序号 # date:日期 # close:收盘价 # open:开盘价 # high:最高价 # low:最低价 # price_change:价格变化 if open > close: p.setPen(pg.mkPen('g')) p.setBrush(pg.mkBrush('g')) else: p.setPen(pg.mkPen('r')) p.setBrush(pg.mkBrush('r')) # 如果收盘价高于开盘价,我们就用红色;如果收盘价低于开盘价,我们就用绿色 if low != high: p.drawLine(QPointF(t, low), QPointF(t, high)) # 当最高价和最低价不相同时,我们就画一条线,两点坐标是从最低价到最高价。 p.drawRect(QRectF(t - w, open, w * 2, close - open)) # 画出具体的收盘价、开盘价矩形图。这里注意下:要是close - open,矩形的方向是不一样的 p.end()
def createBottomToolbar(self): self.toolLayout = QHBoxLayout() self.toolLayout.addWidget(self.toolbar) self.loadingIndictator = QLabel() self.loadingMovie = QMovie('assets/loader.gif') self.emptyLoadingPicture = QPicture() self.emptyLoadingPicture.load('assets/empty_loader.png') self.stopLoadingIndicator() self.toolLayout.addWidget(self.loadingIndictator) self.toolLayout.addItem( QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)) # self.toolLayout.addWidget(QSpacerItem(150, 10, QSizePolicy.Expanding)) self.copyImagePushButton = QPushButton() # self.copyImagePushButton.setText("Copy") # self.copyImagePushButton.setMinimumWidth(1) # self.copyImagePushButton.style().standardIcon(QStyle.SP_DialogOpenButton) self.copyImagePushButton.setIcon(self.style().standardIcon( QStyle.SP_DialogSaveButton)) self.toolLayout.addWidget(self.copyImagePushButton) self.copyImagePushButton.clicked.connect(self.copyPlotToClipboard) downsampleLabel = QLabel() downsampleLabel.setText("DS") self.downSampleInput = QSpinBox() self.downSampleInput.setValue(self.downsample) self.toolLayout.addWidget(downsampleLabel) self.toolLayout.addWidget(self.downSampleInput) self.downSampleInput.valueChanged.connect(self.changeDownSample) self.statusLabel = QLabel() self.toolLayout.addWidget(self.statusLabel)
def generatePicture(self): prema5 = 0 prema10 = 0 prema20 = 0 self.picture = QPicture() # 实例化一个绘图设备 p = QPainter(self.picture) # 在picture上实例化QPainter用于绘图 w = (self.data[1][0] - self.data[0][0]) / 3 for (t, open, close, min, max, ma5, ma10, ma20) in self.data: p.setPen(pg.mkPen('w')) # 设置画笔颜色 # print(t, open, close, min, max) p.drawLine(QPointF(t, min), QPointF(t, max)) # 绘制线条 if open > close: # 开盘价大于收盘价 p.setBrush(pg.mkBrush('g')) # 设置画刷颜色为绿 else: p.setBrush(pg.mkBrush('r')) # 设置画刷颜色为红 p.drawRect(QRectF(t - w, open, w * 2, close - open)) # 绘制箱子 if prema5 != 0: p.setPen(pg.mkPen('r')) p.drawLine(QPointF(t - 1, prema5), QPointF(t, ma5)) prema5 = ma5 if prema10 != 0: p.setPen(pg.mkPen('c')) p.drawLine(QPointF(t - 1, prema10), QPointF(t, ma10)) prema10 = ma10 if prema20 != 0: p.setPen(pg.mkPen('m')) p.drawLine(QPointF(t - 1, prema20), QPointF(t, ma20)) prema20 = ma20 p.end()
def sizeHint(self): if not self.sizeHint_: pic = QPicture() painter = QPainter(pic) getModuleAttrDict(Client.gameObject.module)['paintGame'](painter) painter.end() self.sizeHint_ = pic.boundingRect().size() return self.sizeHint_
def generatePicture(self): # 实例化一个绘图设备 self.picture = QPicture() # 在picture上实例化QPainter用于绘图 self.p = QPainter(self.picture) # 设置画笔颜色 self.w = (self.data[1][0] - self.data[0][0]) / 3 pre_ama = 0 pre_ema12 = 0 pre_ema20 = 0 for (t, open, high, low, close, ama, ema12, ema20) in self.data: # 绘制线条 self.p.setPen(pg.mkPen('w')) self.p.drawLine(QPointF(t, low), QPointF(t, high)) # 开盘价大于收盘价 if close >= open: # 设置画刷颜色为绿 self.p.setPen(pg.mkPen('g')) self.p.setBrush(pg.mkBrush('g')) else: # 设置画刷颜色为红 self.p.setPen(pg.mkPen('r')) self.p.setBrush(pg.mkBrush('r')) # 绘制箱子 self.p.drawRect(QRectF(t - self.w, open, self.w * 2, close - open)) # 根据是否被选中画均线 if pre_ama != 0: if self.indicators_state[0]: self.p.setPen(pg.mkPen('w')) self.p.setBrush(pg.mkBrush('w')) self.p.drawLine(QPointF(t - 1, pre_ama), QPointF(t, ama)) pre_ama = ama if pre_ema12 != 0: if self.indicators_state[1]: self.p.setPen(pg.mkPen('c')) self.p.setBrush(pg.mkBrush('c')) self.p.drawLine(QPointF(t - 1, pre_ema12), QPointF(t, ema12)) pre_ema12 = ema12 if pre_ema20 != 0: if self.indicators_state[2]: self.p.setPen(pg.mkPen('m')) self.p.setBrush(pg.mkBrush('m')) self.p.drawLine(QPointF(t - 1, pre_ema20), QPointF(t, ema20)) pre_ema20 = ema20 self.p.end() self.last_t = t
def generatePicture(self): self.picture = QPicture() # 实例化一个绘图设备 p = QPainter(self.picture) # 在picture上实例化QPainter用于绘图 w = (self.data[1][0] - self.data[0][0]) / 3 for (t, open, close, trade) in self.data: p.setPen(pg.mkPen('w')) # 设置画笔颜色 p.drawLine(QPointF(t, 0), QPointF(t, trade / 10000)) # 绘制线条 if open > close: # 开盘价大于收盘价 p.setBrush(pg.mkBrush('g')) # 设置画刷颜色为绿 else: p.setBrush(pg.mkBrush('r')) # 设置画刷颜色为红 p.drawRect(QRectF(t - w, 0, w * 2, trade / 10000)) # 绘制箱子 p.end()
def render_from_z_mask(z_buf_mask, context): z_buf_mask = convert_deep_to_alpha(z_buf_mask) # рисовать qp = QPainter() picture = QPicture() qp.begin(picture) for x in range(len(z_buf_mask)): for y in range(len(z_buf_mask[0])): # a = color_mask[x][y] a = QColor(Qt.black) a.setAlpha(z_buf_mask[x][y]) qp.setPen(a) qp.drawPoint(x, y) qp.end() # painting done picture.save("drawing.pic") # save picture picture = QPicture() picture.load("drawing.pic") # load picture qp = QPainter() qp.begin(context) # paint in myImage qp.drawPicture(0, 0, picture) # draw the picture at (0,0) qp.end()
def render_avatar_image(image: QImage, size: float): if image.isNull(): return None aspect_ratio = image.width() / image.height() if aspect_ratio > 1: width = size height = size / aspect_ratio else: width = size * aspect_ratio height = size x0 = (size - width) / 2 y0 = (size - height) / 2 path = QPainterPath() path.addEllipse(QRectF(x0, y0, width, height)) picture = QPicture() painter = QPainter(picture) painter.setRenderHint(QPainter.Antialiasing, True) pen = QPen(Qt.black, 5) pen.setStyle(Qt.SolidLine) painter.setPen(pen) painter.setClipPath(path) painter.drawImage( QRectF(x0, y0, width, height), image, ) painter.end() return picture
def save_pdf(widget, filename, preview=False): # Creation du printer printer = QPrinter() file_names = filename printer.setOutputFileName(file_names) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageMargins(10, 10, 10, 10, QPrinter.Point) # Calcul le ratio de redimensionnement page_width = printer.pageRect().width() page_height = printer.pageRect().height() widget_width = widget.width() widget_height = widget.height() ratio = min(page_width / widget_width, page_height / widget_height) # Calcul du positionnement pos_x = max(0, (page_width - ratio * widget_width) / 2) pos_y = max(0, (page_height - ratio * widget_height) / 2) # Render le widget dans une image QPicture pour stocker # les directives de dessin picture = QPicture() widget_painter = QPainter(picture) widget_painter.scale(ratio, ratio) widget.render(widget_painter) widget_painter.end() # Render la QPicture en utilisant le QPrinter picture_painter = QPainter() picture_painter.begin(printer) picture_painter.drawPicture(QPointF(pos_x, pos_y), picture) picture_painter.end() if preview: affiche_pdf(file_names)
def generateCode(article, week, lot): #function returns QPicture object containing DataMatrix code with given article, week, lot toBeEncoded = 'S/N %s, Lot %s, Date %s' % (article, lot, week) bar = toBeEncoded.encode('utf-8') encoded_bar = dmtx.encode(bar) img = Image.frombytes('RGB', (encoded_bar.width, encoded_bar.height), encoded_bar.pixels) img = img.resize(qr_size) qimg = ImageQt(img) picture = QPicture() painter = QPainter() painter.begin(picture) if frame_options['pen-color'] != Qt.Qt.white: painter.setBrush(QBrush(Qt.Qt.white)) painter.setFont(QFont(font['family'], font['size'], font['weight'])) if frame_options['pen-color'] != Qt.Qt.white: old_pen = painter.pen() painter.setPen( QPen(frame_options['pen-color'], frame_options['pen-width'])) painter.drawRoundedRect(0, 0, *label_size, frame_options['radius'], frame_options['radius']) painter.setPen(old_pen) painter.drawText(*item_positions['article'], "S/N " + article) painter.drawText(*item_positions['week'], "Date " + week) painter.drawText(*item_positions['lot'], "Lot " + lot) painter.drawImage(*item_positions['code'], qimg) painter.end() return picture
def impression(self): # Creation du printer printer = QPrinter() dialog = QPrintDialog(printer, self) if dialog.exec_() != QDialog.Accepted: return printer.setPageMargins(10, 10, 10, 10, QPrinter.Point) # Calcul le ratio de redimensionnement page_width = printer.pageRect().width() page_height = printer.pageRect().height() widget_width = self.rapport.width() widget_height = self.rapport.height() ratio = min(page_width / widget_width, page_height / widget_height) # Calcul du positionnement pos_x = max(0, (page_width - ratio * widget_width) / 2) pos_y = max(0, (page_height - ratio * widget_height) / 2) # Render le widget dans une image QPicture pour stocker # les directives de dessin picture = QPicture() widget_painter = QPainter(picture) widget_painter.scale(ratio, ratio) self.rapport.render(widget_painter) widget_painter.end() # Render la QPicture en utilisant le QPrinter picture_painter = QPainter() picture_painter.begin(printer) picture_painter.drawPicture(QPointF(pos_x, pos_y), picture) picture_painter.end()
def __enter__(self) -> QPicture: """ Reset the current picture, size it to match the widget, and return it for rendering. """ self._picture = picture = QPicture() rect = QRect() rect.setSize(self.size()) picture.setBoundingRect(rect) return picture
def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. self.picture = QPicture() p = QPainter(self.picture) p.setPen(pg.mkPen('w')) w = 1 / 3. for (open, max, min, close, vol, ma10, ma20, ma30, t) in self.data.values: p.drawLine(QPointF(t, min), QPointF(t, max)) if open > close: p.setBrush(pg.mkBrush('g')) else: p.setBrush(pg.mkBrush('r')) p.drawRect(QRectF(t - w, open, w * 2, close - open)) p.end()
class CandlestickItem(pg.GraphicsObject): def __init__(self, data): pg.GraphicsObject.__init__(self) self.data = data ## data must have fields: time, open, close, min, max self.generatePicture() def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. self.picture = QPicture() painter = QPainter(self.picture) painter.setPen(pg.mkPen('w')) width = (self.data[1][0] - self.data[0][0]) / 3000. for (timestamp, open, high, low, close, _volume) in self.data: timestamp /= 1000 #print(t, open, high, low, close) painter.drawLine(QPointF(timestamp, low), QPointF(timestamp, high)) if open > close: painter.setBrush(pg.mkBrush('r')) else: painter.setBrush(pg.mkBrush('g')) painter.drawRect( QRectF(timestamp - width, open, width * 2, close - open)) painter.end() def paint(self, p, *args): p.drawPicture(0, 0, self.picture) def boundingRect(self): ## boundingRect _must_ indicate the entire area that will be drawn on ## or else we will get artifacts and possibly crashing. ## (in this case, QPicture does all the work of computing the bouning rect for us) return QRectF(self.picture.boundingRect())
class TradeItem(pg.GraphicsObject): def __init__(self, data): pg.GraphicsObject.__init__(self) self.data = data # data里面必须有以下字段: 时间, 开盘价, 收盘价, 交易量 self.generatePicture() # 绑定按钮点击信号 def generatePicture(self): self.picture = QPicture() # 实例化一个绘图设备 p = QPainter(self.picture) # 在picture上实例化QPainter用于绘图 w = (self.data[1][0] - self.data[0][0]) / 3 for (t, open, close, trade) in self.data: p.setPen(pg.mkPen('w')) # 设置画笔颜色 p.drawLine(QPointF(t, 0), QPointF(t, trade / 10000)) # 绘制线条 if open > close: # 开盘价大于收盘价 p.setBrush(pg.mkBrush('g')) # 设置画刷颜色为绿 else: p.setBrush(pg.mkBrush('r')) # 设置画刷颜色为红 p.drawRect(QRectF(t - w, 0, w * 2, trade / 10000)) # 绘制箱子 p.end() def paint(self, p, *args): p.drawPicture(0, 0, self.picture) def boundingRect(self): return QRectF(self.picture.boundingRect())
def generatePicture(self): if self.opts["lut"] is None: lut = np.empty((len(self.xData), 4), dtype=int) pen = self.opts["pen"] if isinstance(pen, QPen): color = pen.color().getRgb() elif len(pen) == 3: color = list(pen) + [255] else: color = pen lut[:, :] = color self.opts["lut"] = lut # generate picture self.picture = QPicture() p = QPainter(self.picture) # if "connect" == "all" if isinstance(self.opts["connect"], str): lut_array = self.adjustLUT(N_segment=len(self.xData)) # add to generated picture line by line for i, col_values in enumerate(lut_array[:-1]): p.setPen(pg.mkPen(col_values)) p.drawLine(QPointF(self.xData[i], self.yData[i]), QPointF(self.xData[i+1], self.yData[i+1])) else: lut_array = self.adjustLUT(N_segment=(self.opts["connect"] == 0).sum()) # add to generated picture with polyline polygonF = QPolygonF() idx = -1 for x, y, c in zip(self.xData, self.yData, self.opts["connect"]): polygonF.append(QPointF(x, y)) if c == 0: idx += 1 p.setPen(pg.mkPen(lut_array[idx])) p.drawPolyline(polygonF) polygonF = QPolygonF()
class VolItem(pg.GraphicsObject): """ 自定义Item """ def __init__(self, data: pd.DataFrame): super(VolItem, self).__init__() self._data = data self._pic = QPicture() self.generatePicture() def generatePicture(self): """ 绘图 """ p = QPainter(self._pic) p.setPen(pg.mkPen({'color': "CCCCCC"})) # 两个坐标点的1/3, 两个点的距离为横坐标的差 # 如果使用时间来,会出现间隔不连续,因为股票数据时间本身是不连续的 w = 1 / 3 for row in self._data.itertuples(): _t = getattr(row, 'Index') vol = getattr(row, 'vol') / 10000 o_price = getattr(row, 'open') c_price = getattr(row, 'close') if o_price > c_price: p.setBrush(pg.mkBrush('g')) else: p.setBrush(pg.mkBrush('r')) p.drawRect(QRectF(_t - w, 0, w * 2, vol)) p.end() def paint(self, p, *args): p.drawPicture(0, 0, self._pic) def boundingRect(self): return QRectF(self._pic.boundingRect())
class CandlestickItem(pg.GraphicsObject): def __init__(self, data): pg.GraphicsObject.__init__(self) self.data = data ## data must have fields: time, open, close, min, max self.generatePicture() def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. self.picture = QPicture() p = QPainter(self.picture) p.setPen(pg.mkPen('w')) w = 1 / 3. for (open, max, min, close, vol, ma10, ma20, ma30, t) in self.data.values: p.drawLine(QPointF(t, min), QPointF(t, max)) if open > close: p.setBrush(pg.mkBrush('g')) else: p.setBrush(pg.mkBrush('r')) p.drawRect(QRectF(t - w, open, w * 2, close - open)) p.end() def paint(self, p, *args): p.drawPicture(0, 0, self.picture) def boundingRect(self): ## boundingRect _must_ indicate the entire area that will be drawn on ## or else we will get artifacts and possibly crashing. ## (in this case, QPicture does all the work of computing the bouning rect for us) return QRectF(self.picture.boundingRect())
def paint_page(painter, page, page_rect): """ Given a `painter` and a `page` (a widget presumably created parsing a wreport), renders the widget on the painter and returns a QPicture. """ # make qwidget output vectorial, rendering directly on a printer # results in a raster image in the pdf page_pic = QPicture() wpainter = QPainter(page_pic) # set the BoundingRect of page_pic and the page size to page_rect page_pic.setBoundingRect(page_rect.toRect()) page.resize(page_rect.toRect().width(), page_rect.toRect().height()) page.render(wpainter, flags=QWidget.DrawChildren) wpainter.end() painter.drawPicture(0, 0, page_pic) return page_pic
def drawPicture(self): self._picture = QPicture() p = QPainter(self._picture) p.setPen(self._pen) p.setBrush(self._brush) # Now it works for bar plot with equalized gaps # TODO: extend it if len(self._x) > 1: width = self._width * (self._x[1] - self._x[0]) else: width = self._width for x, y in zip(self._x, self._y): p.drawRect(QRectF(x - width/2, 0, width, y)) p.end() self.prepareGeometryChange()
def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. self.picture = QPicture() painter = QPainter(self.picture) painter.setPen(pg.mkPen('w')) width = (self.data[1][0] - self.data[0][0]) / 3000. for (timestamp, open, high, low, close, _volume) in self.data: timestamp /= 1000 #print(t, open, high, low, close) painter.drawLine(QPointF(timestamp, low), QPointF(timestamp, high)) if open > close: painter.setBrush(pg.mkBrush('r')) else: painter.setBrush(pg.mkBrush('g')) painter.drawRect( QRectF(timestamp - width, open, width * 2, close - open)) painter.end()
def _prepareGraph(self): """Override.""" self._graph = QPicture() p = QPainter(self._graph) p.setPen(self._pen) p.setBrush(self._brush) x, y = self.transformedData() # Now it works for bar plot with equalized gaps # TODO: extend it if len(x) > 1: width = self._width * (x[1] - x[0]) else: width = self._width for px, py in zip(x, y): p.drawRect(QRectF(px - width / 2, 0, width, py)) p.end()
class CandlestickItem(pg.GraphicsObject): ''' K线图,自定义CandlestickItem类,这个类继承了pyqtgraph.GraphicsObject ''' def __init__(self, data): ''' 一些初始设置 ''' pg.GraphicsObject.__init__(self) self.data = data # 变量data表示我们需要带入的数据 self.generatePicture() def generatePicture(self): ''' 每个小的K线 ''' self.picture = QPicture() p = QPainter(self.picture) p.setPen(pg.mkPen('w'))# 白色 w = (self.data[1][0] - self.data[0][0]) / 3.# 每个K线的宽度 for (t, date, close, open, high, low, price_change) in self.data: # t:每个汇率数据的序号 # date:日期 # close:收盘价 # open:开盘价 # high:最高价 # low:最低价 # price_change:价格变化 if open > close: p.setPen(pg.mkPen('g')) p.setBrush(pg.mkBrush('g')) else: p.setPen(pg.mkPen('r')) p.setBrush(pg.mkBrush('r')) # 如果收盘价高于开盘价,我们就用红色;如果收盘价低于开盘价,我们就用绿色 if low != high: p.drawLine(QPointF(t, low), QPointF(t, high)) # 当最高价和最低价不相同时,我们就画一条线,两点坐标是从最低价到最高价。 p.drawRect(QRectF(t - w, open, w * 2, close - open)) # 画出具体的收盘价、开盘价矩形图。这里注意下:要是close - open,矩形的方向是不一样的 p.end() def paint(self, p, *args): ''' 绘图 ''' p.drawPicture(0, 0, self.picture) def boundingRect(self): ''' 所有绘画必须限制在图元的边界矩形内 ''' return QRectF(self.picture.boundingRect())
def paintEvent(self, QPaintEvent): pic = QPicture() painter = QPainter(pic) getModuleAttrDict(Client.gameObject.module)['paintGame'](painter) painter.end() painter.begin(self) bRect = pic.boundingRect() self.sizeHint_ = bRect.size() painter.setWindow(bRect) painter.setViewTransformEnabled(True) width = self.width() height = self.height() if width * bRect.height() < height * bRect.width(): pheight = (width * bRect.height()) / bRect.width() painter.setViewport(0, (height - pheight) / 2, width, pheight) else: pwidth = (height * bRect.width()) / bRect.height() painter.setViewport((width - pwidth) / 2, 0, pwidth, height) self.invTrafo = painter.combinedTransform().inverted()[0] pic.play(painter)
def renderSystem(self): self.picture = QPicture() qp = QPainter() # these offsets don't make sense anymore sz = self.size() self.xpos = sz.width() / 2 self.ypos = sz.height() / 2 qp.begin(self.picture) self.rendercurve(qp) qp.end() self.repaint()
class PictureWidget(QWidget): """ Generic widget using a QPicture as a paint buffer. """ def __init__(self, *args) -> None: super().__init__(*args) self._picture = QPicture() # Last saved picture rendering. def __enter__(self) -> QPicture: """ Reset the current picture, size it to match the widget, and return it for rendering. """ self._picture = picture = QPicture() rect = QRect() rect.setSize(self.size()) picture.setBoundingRect(rect) return picture def __exit__(self, *_) -> None: """ Repaint the widget after rendering is complete. """ self.update() def paintEvent(self, *_) -> None: """ Paint the saved picture on this widget when GUI repaint occurs. """ with QPainter(self) as p: self._picture.play(p) # should be inherited from a: """ Mixin to send a signal on a context menu request (right-click). """ contextMenuRequest = pyqtSignal([QPoint]) def contextMenuEvent(self, event:QContextMenuEvent) -> None: pos = event.globalPos() self.contextMenuRequest.emit(pos) # should be inherited from a: """ Mixin to send a signal on any widget size change. """ resized = pyqtSignal() def resizeEvent(self, *_) -> None: self.resized.emit()
def _drawPicture(self): """Override.""" self._picture = QPicture() p = QPainter(self._picture) p.setRenderHint(QPainter.Antialiasing) p.setPen(self._pen) p.setBrush(self._brush) c = QPointF(self._cx, self._cy) for r in self._radials: p.drawEllipse(c, r, r) p.end()
def render_from_color_mask(color_mask, context): qp = QPainter() picture = QPicture() qp.begin(picture) for x in range(len(color_mask)): for y in range(len(color_mask[0])): a = color_mask[x][y] qp.setPen(a) qp.drawPoint(x, y) qp.end() # painting done picture.save("drawing.pic") # save picture picture = QPicture() picture.load("drawing.pic") # load picture qp = QPainter() qp.begin(context) # paint in myImage qp.drawPicture(0, 0, picture) # draw the picture at (0,0) qp.end()
class CandlestickItem(pg.GraphicsObject): df: pd.DataFrame y_min: float y_max: float def __init__(self): super().__init__() self.picture = QPicture() def set_data(self, df: pd.DataFrame): self.df = df self.y_min = self.df['low'].min() self.y_max = self.df['high'].max() print(f'<CandlestickItem> received {self.df.shape[0]} rows, value min = {self.y_min}, max = {self.y_max}') self.generate() def generate(self): painter = QPainter(self.picture) painter.setPen(pg.mkPen('w')) w = 1.0 / 3.0 for i in range(self.df.shape[0]): if self.df.at[i, 'close'] > self.df.at[i, 'open']: painter.setPen(pg.mkPen('g')) painter.setBrush(pg.mkBrush('g')) elif self.df.at[i, 'close'] < self.df.at[i, 'open']: painter.setPen(pg.mkPen('r')) painter.setBrush(pg.mkBrush('r')) else: painter.setPen(pg.mkPen('w')) painter.setBrush(pg.mkBrush('w')) painter.drawLine( QPointF(i, self.df.at[i, 'low']), QPointF(i, self.df.at[i, 'high']) ) painter.drawRect( QRectF(i - w, self.df.at[i, 'open'], w * 2, self.df.at[i, 'close'] - self.df.at[i, 'open']) ) painter.end() def paint(self, p, *args): p.drawPicture(0, 0, self.picture) def boundingRect(self): return QRectF(self.picture.boundingRect())
from PyQt5.QtCore import QRect, QRectF, QSizeF, QPointF, Qt from PyQt5.QtGui import QPainter, QPicture, QFont, QColor from PyQt5.QtWidgets import QApplication, QLabel def drawNode(painter, angle, radius, text): size = 32767.0; painter.save(); painter.rotate(-angle); painter.translate(radius, 0); painter.drawText(QRectF(0, -size/2.0, size, size), Qt.AlignVCenter, text); painter.restore(); if __name__ == "__main__": app = QApplication(sys.argv) pic = QPicture() pic.setBoundingRect(QRect(-100, -100, 200, 200)) p = QPainter(pic) p.drawEllipse(0, 0, 3, 3) p.setFont(QFont("Helvetica", 25)) for angle in range(0, 359, 30): drawNode(p, angle, 50, str(angle)) p.end() l = QLabel() l.setPicture(pic); l.show(); sys.exit(app.exec_())