def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.TextAntialiasing) f = painter.font() f.setBold(True) f.setPixelSize(self.height() - 1) painter.setFont(f) painter.setPen(QColor('red' if self.is_enabled else 'green')) painter.drawText(self.rect(), Qt.AlignCenter, 'Z') painter.end()
def paintEvent(self, ev): if self.mouse_over: p = QPainter(self) tool = QStyleOption() tool.rect = self.rect() tool.state = QStyle.State_Raised | QStyle.State_Active | QStyle.State_MouseOver s = self.style() s.drawPrimitive(QStyle.PE_PanelButtonTool, tool, p, self) p.end() QWidget.paintEvent(self, ev)
def _updateCountour(self): """Update countour.""" ppath = self._contour() bmp = QBitmap(self.size()) bmp.fill(Qt.color0) painter = QPainter(bmp) painter.fillPath(ppath, Qt.color1) painter.end() self.setMask(bmp)
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) try: self.paint_background(painter) except Exception: pass finally: painter.end() QWidget.paintEvent(self, ev)
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) try: self.do_paint(painter) except Exception: import traceback traceback.print_exc() finally: painter.end()
def paintEvent(self, ev): if self.timer.isActive(): if not self.errored_out: try: draw_snake_spinner(QPainter(self), self.rect(), self.angle, self.light, self.dark) except Exception: import traceback traceback.print_exc() self.errored_out = True else: r = self.rect() painter = QPainter(self) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) icon = downloads_icon() pmap = icon.pixmap(r.width(), r.height()) x = (r.width() - int(pmap.width() / pmap.devicePixelRatio())) // 2 y = (r.height() - int(pmap.height() / pmap.devicePixelRatio())) // 2 + 1 painter.drawPixmap(x, y, pmap)
def setup_printer(self, outpath): self.printer = self.painter = None printer = get_pdf_printer(self.opts, output_file_name=outpath) painter = QPainter(printer) zoomx = printer.logicalDpiX() / self.view.logicalDpiX() zoomy = printer.logicalDpiY() / self.view.logicalDpiY() painter.scale(zoomx, zoomy) pr = printer.pageRect() self.printer, self.painter = printer, painter self.viewport_size = QSize(pr.width() / zoomx, pr.height() / zoomy) self.page.setViewportSize(self.viewport_size)
def paintEvent(self, ev): p = QPainter(self) p.setClipRect(ev.rect()) bg = self.palette().color(QPalette.AlternateBase) if self.hovering: bg = bg.lighter(115) p.fillRect(self.rect(), bg) try: p.drawText(self.rect(), Qt.AlignLeft|Qt.AlignVCenter|Qt.TextSingleLine, self.rendered_text) finally: p.end()
def __call__(self, canvas): if canvas.has_selection and canvas.selection_state.rect is not None: pimg = self.after_image img = self.after_image = QImage(canvas.current_image) rect = QRectF(*get_selection_rect(img, canvas.selection_state.rect, canvas.target)) p = QPainter(img) p.setRenderHint(p.SmoothPixmapTransform, True) p.drawImage(rect, pimg, QRectF(pimg.rect())) p.end() return self.after_image
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) try: if self.rendered_pixmap is None: self.paint_background(painter) else: self.animated_paint(painter) finally: painter.end()
def makeQPixmap(self, width, height): data = numpy.zeros((width, height), float) data[...] = (numpy.arange(width) / (width - 1.))[:, numpy.newaxis] # make brush image -- diag background, with colormap on top img = QPixmap(width, height) painter = QPainter(img) painter.fillRect(0, 0, width, height, QBrush(QColor("white"))) painter.fillRect(0, 0, width, height, QBrush(Qt.BDiagPattern)) painter.drawImage(0, 0, self.colorize(data)) painter.end() return img
def paintEvent(self, ev): br = ev.region().boundingRect() p = QPainter(self) p.setOpacity(0.2) p.fillRect(br, QBrush(self.palette().text())) p.end() QWidget.paintEvent(self, ev) p = QPainter(self) p.setClipRect(br) f = p.font() f.setBold(True) f.setPointSize(20) p.setFont(f) p.setPen(Qt.SolidLine) r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150) p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text) p.end()
def __init__(self, parent=None): super().__init__(parent) self.board_jpg = QtGui.QPixmap('images\\IMAGES_X\\WOOD.JPG') self.oos_gif = QtGui.QPixmap('images\\IMAGES_X\\COMIC\\OOS.GIF') self.painter = QPainter() self.agent = None self.is_flipped = False # self.game_state = None self.sq_selected = (-1, -1) self.mv_cur = (-1, -1, -1, -1) self.mv_last = (-1, -1, -1, -1)
def paintEvent(self, e): """ receive paint events :param e: QPaintEvent :return: """ if self.scaled_img: painter = QPainter() painter.begin(self) painter.scale(self.scale, self.scale) painter.drawPixmap(self.point, self.scaled_img) painter.end()
def paintEvent(self, pevent): """ Paint event handler. Reimplemented for drawing rule group frames. """ super(ParameterItemHilighter, self).paintEvent(pevent) painter = QPainter(self) rect = QRect(0, 0, self.width(), self.height()) rect.adjust(1, 1, -1, -1) painter.setPen(Qt.red) painter.drawRect(rect)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setPen(QPen(Qt.red, 3)) painter.setBrush(Qt.transparent) painter.translate(self.width() / 2, self.height() / 2) painter.drawEllipse(QPoint(0, 0), self.outer_circle, self.outer_circle) painter.drawEllipse(QPoint(self.ball.x, self.ball.y), self.ball.r, self.ball.r)
def run(dev, func): p = QPainter(dev) if isinstance(dev, PdfDevice): dev.init_page() xmax, ymax = p.viewport().width(), p.viewport().height() try: func(p, xmax, ymax) finally: p.end() if isinstance(dev, PdfDevice): if dev.engine.errors_occurred: raise SystemExit(1)
def paintEvent(self, event): ''' @param: event QPaintEvent ''' super(NavigationContainer, self).paintEvent(event) # Draw line at the bottom of navigation bar if tabs are on top # To visually distinguish navigation bar from the page if gVar.qzSettings.tabsOnTop: p = QPainter(self) lineRect = QRect(0, self.height() - 1, self.width(), 1) color = self.palette().window().color().darker(125) p.fillRect(lineRect, color)
def message_image(text, width=500, height=400, font_size=20): init_environment() img = QImage(width, height, QImage.Format_ARGB32) img.fill(Qt.white) p = QPainter(img) f = QFont() f.setPixelSize(font_size) p.setFont(f) r = img.rect().adjusted(10, 10, -10, -10) p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text) p.end() return pixmap_to_data(img)
def do_print(self, printer): painter = QPainter(printer) zoomx = printer.logicalDpiX() / self.view.logicalDpiX() zoomy = printer.logicalDpiY() / self.view.logicalDpiY() painter.scale(zoomx, zoomy) pr = printer.pageRect() self.view.page().setViewportSize( QSize(pr.width() / zoomx, pr.height() / zoomy)) evaljs = self.mf.evaluateJavaScript loop = QEventLoop(self) pagenum = 0 from_, to = printer.fromPage(), printer.toPage() first = True for path in self.iterator.spine: self.loaded_ok = None load_html(path, self.view, codec=getattr(path, 'encoding', 'utf-8'), mime_type=getattr(path, 'mime_type', None)) while self.loaded_ok is None: loop.processEvents(loop.ExcludeUserInputEvents) if not self.loaded_ok: return error_dialog(self.parent(), _('Failed to render'), _('Failed to render document %s') % path, show=True) evaljs(self.paged_js) evaljs(''' document.body.style.backgroundColor = "white"; paged_display.set_geometry(1, 0, 0, 0); paged_display.layout(); paged_display.fit_images(); ''') while True: pagenum += 1 if (pagenum >= from_ and (to == 0 or pagenum <= to)): if not first: printer.newPage() first = False self.mf.render(painter) try: nsl = int(evaljs('paged_display.next_screen_location()')) except (TypeError, ValueError): break if nsl <= 0: break evaljs('window.scrollTo(%d, 0)' % nsl) painter.end()
def __InitData(self): self.__size = QSize(420, 420) # 新建QPixmap作为画板,尺寸为__size self.__board = QPixmap(self.__size) self.__board.fill(Qt.black) # 用黑色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__painter = QPainter() # 新建绘图工具 self.__thickness = 35 # 默认画笔粗细为35px self.__penColor = QColor("white") # 设置默认画笔颜色为白色 self.__colorList = QColor.colorNames() # 获取颜色列表
def paintEvent(self, event): contents_y = self.edit.verticalScrollBar().value() page_bottom = contents_y + self.edit.viewport().height() font_metrics = self.fontMetrics() current_block = self.edit.document().findBlock( self.edit.textCursor().position()) painter = QPainter(self) line_count = 0 # Iterate over all text blocks in the document. block = self.edit.document().begin() while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.document().documentLayout( ).blockBoundingRect(block).topLeft() # Check if the position of the block is out side of the visible # area. if position.y() > page_bottom: break # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). painter.drawText( self.width() - font_metrics.width(str(line_count)) - 3, round(position.y()) - contents_y + font_metrics.ascent(), str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) block = block.next() self.highest_line = line_count painter.end() QWidget.paintEvent(self, event)
def _get_scaled_icon(self, icon): if icon.isNull(): return self.blank_icon # We need the icon scaled to 16x16 src = icon.pixmap(ICON_SIZE, ICON_SIZE) if src.width() == ICON_SIZE and src.height() == ICON_SIZE: return icon # Need a new version of the icon pm = QPixmap(ICON_SIZE, ICON_SIZE) pm.fill(Qt.transparent) p = QPainter(pm) p.drawPixmap(QPoint((ICON_SIZE - src.width()) / 2, (ICON_SIZE - src.height()) / 2), src) p.end() return QIcon(pm)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.drawPixmap(0, 0, self._pixmap) painter.fillRect(self.rect(), self.palette().midlight().color()) round_path = QPainterPath() round_path.addRoundedRect(0, 0, self.width(), self.height(), 5, 5) sq_path = QPainterPath() sq_path.addRect(0, 0, 10, self.height()) draw_path = sq_path - round_path painter.setPen(Qt.NoPen) painter.setBrush(self.palette().dark().color()) painter.drawPath(draw_path)
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): view_box = elem.get('viewBox', elem.get('viewbox', None)) sizes = None logger = self.oeb.logger if view_box is not None: try: box = [ float(x) for x in [_f for _f in re.split('[, ]', view_box) if _f] ] sizes = [box[2] - box[0], box[3] - box[1]] except (TypeError, ValueError, IndexError): logger.warn( 'SVG image has invalid viewBox="%s", ignoring the viewBox' % view_box) else: for image in elem.xpath( 'descendant::*[local-name()="image" and ' '@height and contains(@height, "%")]'): logger.info( 'Found SVG image height in %, trying to convert...') try: h = float(image.get('height').replace('%', '')) / 100. image.set('height', str(h * sizes[1])) except: logger.exception( 'Failed to convert percentage height:', image.get('height')) data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() if size.width() == 100 and size.height() == 100 and sizes: size.setWidth(sizes[0]) size.setHeight(sizes[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)
def create_icon(text, palette=None, sz=32, divider=2): if palette is None: palette = QApplication.palette() img = QImage(sz, sz, QImage.Format_ARGB32) img.fill(Qt.transparent) p = QPainter(img) p.setRenderHints(p.TextAntialiasing | p.Antialiasing) qDrawShadeRect(p, img.rect(), palette, fill=QColor('#ffffff'), lineWidth=1, midLineWidth=1) f = p.font() f.setFamily('Liberation Sans'), f.setPixelSize(sz // divider), f.setBold(True) p.setFont(f), p.setPen(Qt.black) p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text) p.end() return QIcon(QPixmap.fromImage(img))
def missing_icon(): global _missing_icon if _missing_icon is None: p = QPixmap(ICON_SIZE, ICON_SIZE) p.fill(Qt.transparent) painter = QPainter(p) pal = QApplication.instance().palette() painter.setPen(QPen(pal.color(pal.Text), 0, Qt.DashLine)) margin = 3 r = p.rect().adjusted(margin, margin, -margin, -margin) painter.drawRect(r) painter.end() _missing_icon = QIcon(p) return _missing_icon
def paintEvent(self, event): ''' @param: event QPaintEvent ''' p = QPainter(self) currentIndex = self.currentIndex() for idx in range(self.count()): if idx != currentIndex: self.paintTab(p, idx) # paint active tab last, since it overlaps the neighbors if currentIndex != -1: self.paintTab(p, currentIndex)
def __InitData(self): # self.__size = QSize(480,460) # self.__size = QSize(280, 280) self.__size = QSize(600, 600) self.__board = QPixmap(self.__size) # 新建QPixmap作为画板,宽350px,高250px self.__board.fill(Qt.black) # 用白色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) self.__currentPos = QPoint(0, 0) self.__painter = QPainter() self.__painter.setRenderHints(QPainter.Antialiasing, True) self.__thickness = 60 # 默认画笔粗细为20px self.__penColor = QColor("white") # 设置默认画笔颜色为黑色 self.__colorList = QColor.colorNames() # 获取颜色列表
def draw_sized_text(img, dw, line, top, left_margin, right_margin, auto_reduce_font): from PyQt5.Qt import QPainter, Qt, QRect, QColor total_margin = left_margin + right_margin if img.size[0] - total_margin <= 0: total_margin = 0 left_margin = 0 right_margin = 0 p = QPainter(img.img) p.setRenderHint(p.TextAntialiasing) pen = p.pen() pen.setColor(QColor(dw.fill_color)) p.setPen(pen) flags = line._align try: if auto_reduce_font: line_width = img.size[0] - total_margin initial_font_size = line.font.pixelSize() text = line.text while True: f = line.font p.setFont(f) br = p.boundingRect( 0, 0, line_width, 100, flags | Qt.TextSingleLine, text) if br.width() < line_width: break oversize_factor = br.width() / line_width if oversize_factor > 10: f.setPixelSize(f.pixelSize() - 8) elif oversize_factor > 5: f.setPixelSize(f.pixelSize() - 4) elif oversize_factor > 3: f.setPixelSize(f.pixelSize() - 2) else: f.setPixelSize(f.pixelSize() - 1) if f.pixelSize() < 6: # Enough is enough, clearly cannot fit on one line! # Abort the font reduction process f.setPixelSize(initial_font_size) line.text = '*** TEXT TOO LARGE TO AUTO-FIT ***' break p.setFont(line.font) br = p.drawText(QRect( left_margin, top, img.size[0] - left_margin - right_margin, img.size[1] - top), flags | Qt.TextWordWrap, line.text) return br.bottom() finally: p.end()