def _get_composer_image(self, width, height, dpi): image = QImage(QSize(width, height), self._TestMapSettings.outputImageFormat()) image.fill(QColor(152, 219, 249).rgb()) image.setDotsPerMeterX(dpi / 25.4 * 1000) image.setDotsPerMeterY(dpi / 25.4 * 1000) p = QPainter(image) p.setRenderHint( QPainter.Antialiasing, self._TestMapSettings.testFlag(QgsMapSettings.Antialiasing) ) self._c.renderPage(p, 0) p.end() # image = self._c.printPageAsRaster(0) # """:type: QImage""" if image.isNull(): return False, '' filepath = getTempfilePath('png') res = image.save(filepath, 'png') if not res: os.unlink(filepath) filepath = '' return res, filepath
def _renderedImage2(self, width, height, extent, transp_background=False, layerids=None): antialias = True if self._renderer is None: self._initRenderer() canvas = self.context.canvas if layerids is None: layerids = [mapLayer.id() for mapLayer in canvas.layers()] renderer = self._renderer renderer.setLayerSet(layerids) image = QImage(width, height, QImage.Format_ARGB32_Premultiplied) if transp_background: image.fill(QColor(Qt.transparent).rgba()) # else: image.fill(canvas.canvasColor().rgba()) # renderer.setOutputSize(image.size(), image.logicalDpiX()) renderer.setExtent(extent.unrotatedRect()) painter = QPainter() painter.begin(image) if antialias: painter.setRenderHint(QPainter.Antialiasing) renderer.render(painter) painter.end() return tools.base64image(image)
def snapshot(self, box=None, format=QImage.Format_ARGB32): """ Take an image snapshot of the current frame. @param box: 4-element tuple containing box to capture (x1, y1, x2, y2). If None, capture the whole page. @param format: QImage format (see QImage::Format_*). @return: A QImage image. Typical usage: >>> browser.load(url) >>> browser.snapshot().save("webpage.png") """ if box: x1, y1, x2, y2 = box w, h = (x2 - x1), (y2 - y1) image0 = QImage(QSize(x2, y2), format) painter = QPainter(image0) self.webpage.mainFrame().render(painter) painter.end() image = image0.copy(x1, y1, w, h) else: image = QImage(self.webpage.viewportSize(), format) painter = QPainter(image) self.webpage.mainFrame().render(painter) painter.end() return image
def draw_image(name, q): image = QSvgGenerator() image.setSize(QSize(IMAGE_SIZE, IMAGE_SIZE)) image.setFileName(name + ".svg") painter = QPainter() painter.begin(image) painter.setBrush(Qt.white) painter.setPen(Qt.NoPen) painter.drawEllipse(QPointF(IMAGE_SIZE/2, IMAGE_SIZE/2), IMAGE_SIZE/2, IMAGE_SIZE/2) painter.setBrush(QBrush()) painter.setPen(QPen()) draw_defect(painter, q) draw_circle(painter, q) pen = QPen() pen.setWidth(7) pen.setColor(Qt.red) painter.setPen(pen) painter.drawLine(IMAGE_SIZE/2 - ARROW_SIZE, IMAGE_SIZE/2, IMAGE_SIZE/2 + ARROW_SIZE, IMAGE_SIZE/2) painter.drawLine(IMAGE_SIZE/2 + ARROW_SIZE, IMAGE_SIZE/2, IMAGE_SIZE/2 + ARROW_SIZE - 30, IMAGE_SIZE/2 + 20) painter.drawLine(IMAGE_SIZE/2 + ARROW_SIZE, IMAGE_SIZE/2, IMAGE_SIZE/2 + ARROW_SIZE - 30, IMAGE_SIZE/2 - 20) font = painter.font() font.setPixelSize(40) font.setBold(True) painter.setFont(font) painter.drawText(QPointF(IMAGE_SIZE/2 + ARROW_SIZE - 30, IMAGE_SIZE/2 - 30), "E") painter.end()
def testComposition(self, page=0, pixelDiff=0 ): if self.mComposition is None: myMessage = "Composition not valid" return False, myMessage #load expected image self.setControlName("expected_"+self.mTestName) # get width/height, create image and render the composition to it outputImage = QImage( self.mSize, QImage.Format_RGB32 ) self.mComposition.setPlotStyle( QgsComposition.Print ) outputImage.setDotsPerMeterX( self.mDotsPerMeter ) outputImage.setDotsPerMeterY( self.mDotsPerMeter ) QgsMultiRenderChecker.drawBackground( outputImage ) p = QPainter( outputImage ) self.mComposition.renderPage( p, page ) p.end() renderedFilePath = QDir.tempPath() + QDir.separator() + QFileInfo(self.mTestName).baseName() + "_rendered.png" outputImage.save( renderedFilePath, "PNG" ) self.setRenderedImage( renderedFilePath ) testResult = self.runTest( self.mTestName, pixelDiff ) return testResult, self.report()
def paintEvent(self, event): """ Overloads the paint event to handle painting pointers for the popup \ mode. :param event | <QPaintEvent> """ # use the base technique for the dialog mode if self.currentMode() == XPopupWidget.Mode.Dialog: super(XPopupWidget, self).paintEvent(event) return # setup the coloring options palette = self.palette() painter = QPainter() painter.begin(self) pen = QPen(palette.color(palette.Window).darker(130)) pen.setWidthF(1.75) painter.setPen(pen) painter.setRenderHint(painter.Antialiasing) painter.setBrush(palette.color(palette.Window)) painter.drawPath(self.borderPath()) painter.end()
def setNameAndBrush(self, sigma, color=Qt.black): self.sigma = sigma self.setText( decode_to_qstring("σ=%.1fpx" % self.sigma, "utf-8") ) # This file is encoded as utf-8, so this string should be decoded as such. total_window = 1 + 2 * int(self.sigma * self.window_size + 0.5) self.setToolTip("sigma = {:.1f} pixels, window diameter = {:.1f}".format(self.sigma, total_window)) font = QFont() font.setPointSize(10) font.setBold(True) self.setFont(font) self.setForeground(color) pixmap = QPixmap(self.pixmapSize) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.setPen(color) brush = QBrush(color) painter.setBrush(brush) painter.drawEllipse( QRect( self.pixmapSize.width() / 2 - self.brushSize / 2, self.pixmapSize.height() / 2 - self.brushSize / 2, self.brushSize, self.brushSize, ) ) painter.end() self.setIcon(QIcon(pixmap)) self.setTextAlignment(Qt.AlignVCenter)
def paintEvent(self, event): if not self.tenant: return paint = QPainter(self) for e in self.tenant.edges: if e == self.selectedEdge: paint.setPen(self.colors["selected"]) else: paint.setPen(self.colors["line"]) self.drawArrow(paint, self.vertices[e.e1].x() + self.size / 2, self.vertices[e.e1].y() + self.size / 2, self.vertices[e.e2].x() + self.size / 2, self.vertices[e.e2].y() + self.size / 2) for v in self.vertices.keys(): pen = paint.pen() paint.setPen(Qt.red) if self.selectedVertex == self.vertices[v]: paint.drawRect(self.vertices[v]) if isinstance(v, VM): paint.drawImage(self.vertices[v], self.computericon) elif isinstance(v, Storage): paint.drawImage(self.vertices[v], self.storageicon) elif isinstance(v, NetElement): if v.router: paint.drawImage(self.vertices[v], self.routericon) else: paint.drawImage(self.vertices[v], self.switchicon) elif isinstance(v, Vnf): paint.drawImage(self.vertices[v], self.serviceicon) elif isinstance(v, Domain): paint.drawImage(self.vertices[v], self.domainicon) paint.setPen(self.colors["line"]) if self.edgeDraw: self.drawArrow(paint, self.curEdge[0].x() + self.size / 2, self.curEdge[0].y() + self.size / 2, QCursor.pos().x() - self.mapToGlobal(self.geometry().topLeft()).x(), QCursor.pos().y() - self.mapToGlobal(self.geometry().topLeft()).y()) paint.end()
def paintEvent(self, e): painter = QPainter(self) painter.setPen(QColor(self._backgroundColor)) painter.setBrush(QColor(self._backgroundColor)) painter.drawRect(0, 0, self.width(), self.height()) painter.end() QFrame.paintEvent(self, e)
def paintEvent( self, event ): """ Overloads the paint event to draw rounded edges on this widget. :param event | <QPaintEvent> """ super(XRolloutItem, self).paintEvent(event) painter = QPainter() painter.begin(self) w = self.width() - 3 h = self.height() - 3 color = self.palette().color(QPalette.Midlight) color = color.darker(180) pen = QPen(color) pen.setWidthF(0.5) painter.setPen(pen) painter.setBrush(self.palette().color(QPalette.Midlight)) painter.setRenderHint(QPainter.Antialiasing) painter.drawRoundedRect(1, 1, w, h, 10, 10) painter.end()
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setOpacity(self.pixmap_opacity) painter.drawPixmap(0, 0, self.old_pixmap) painter.end()
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 127))) painter.setPen(QPen(Qt.NoPen)) for i in xrange(6): x_pos = self.width() / 2 + 30 * \ math.cos(2 * math.pi * i / 6.0) - 10 y_pos = self.height() / 2 + 30 * \ math.sin(2 * math.pi * i / 6.0) - 10 if (self.counter / 5) % 6 == i: linear_gradient = QLinearGradient( x_pos + 10, x_pos, y_pos + 10, y_pos) linear_gradient.setColorAt(0, QColor(135, 206, 250)) linear_gradient.setColorAt(1, QColor(0, 0, 128)) painter.setBrush(QBrush(linear_gradient)) else: linear_gradient = QLinearGradient( x_pos - 10, x_pos, y_pos + 10, y_pos) linear_gradient.setColorAt(0, QColor(105, 105, 105)) linear_gradient.setColorAt(1, QColor(0, 0, 0)) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( x_pos, y_pos, 20, 20) painter.end()
def render(self): painter = QPainter(self.printer) for page in self.layoutPages[:-1]: page.render(painter) self.printer.newPage() self.layoutPages[-1].render(painter) painter.end()
def exportAsImage(self): filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save Model As Image'), '', self.tr('PNG files (*.png *.PNG)'))) if not filename: return if not filename.lower().endswith('.png'): filename += '.png' totalRect = QRectF(0, 0, 1, 1) for item in self.scene.items(): totalRect = totalRect.united(item.sceneBoundingRect()) totalRect.adjust(-10, -10, 10, 10) img = QImage(totalRect.width(), totalRect.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) painter.begin(img) self.scene.render(painter, totalRect, totalRect) painter.end() img.save(filename)
def decorate_welcome_icon(icon, background_color): """Return a `QIcon` with a circle shaped background. """ welcome_icon = QIcon() sizes = [32, 48, 64, 80] background_color = NAMED_COLORS.get(background_color, background_color) background_color = QColor(background_color) grad = radial_gradient(background_color) for size in sizes: icon_pixmap = icon.pixmap(5 * size / 8, 5 * size / 8) icon_size = icon_pixmap.size() icon_rect = QRect(QPoint(0, 0), icon_size) pixmap = QPixmap(size, size) pixmap.fill(QColor(0, 0, 0, 0)) p = QPainter(pixmap) p.setRenderHint(QPainter.Antialiasing, True) p.setBrush(QBrush(grad)) p.setPen(Qt.NoPen) ellipse_rect = QRect(0, 0, size, size) p.drawEllipse(ellipse_rect) icon_rect.moveCenter(ellipse_rect.center()) p.drawPixmap(icon_rect.topLeft(), icon_pixmap) p.end() welcome_icon.addPixmap(pixmap) return welcome_icon
def splash_screen(): """ """ pm = QPixmap( pkg_resources.resource_filename( __name__, "icons/orange-splash-screen.png") ) version = QCoreApplication.applicationVersion() size = 21 if len(version) < 5 else 16 font = QFont("Helvetica") font.setPixelSize(size) font.setBold(True) font.setItalic(True) font.setLetterSpacing(QFont.AbsoluteSpacing, 2) metrics = QFontMetrics(font) br = metrics.boundingRect(version).adjusted(-5, 0, 5, 0) br.moveCenter(QPoint(436, 224)) p = QPainter(pm) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setFont(font) p.setPen(QColor("#231F20")) p.drawText(br, Qt.AlignCenter, version) p.end() return pm, QRect(88, 193, 200, 20)
def drawROIBoxes(self, image): #print(self.frame_data) if not isinstance(self.frame_data, pd.DataFrame) or len(self.frame_data) == 0 \ or not self.label_type in self.frame_data: return self.img_h_ratio = image.height()/self.image_height; self.img_w_ratio = image.width()/self.image_width; painter = QPainter() painter.begin(image) for row_id, row_data in self.frame_data.iterrows(): x = row_data['coord_x']*self.img_h_ratio y = row_data['coord_y']*self.img_w_ratio #check if the coordinates are nan if not (x == x) or not (y == y): continue x = int(x) y = int(y) c = self.wlabC[int(row_data[self.label_type])] painter.setPen(c) painter.setFont(QFont('Decorative', 10)) painter.drawText(x, y, str(int(row_data[self.worm_index_type]))) bb = row_data['roi_size']*self.img_w_ratio painter.drawRect(x-bb/2, y-bb/2, bb, bb); painter.end()
def getProtoStatusIcon(name, proto_int=None): """Creates a nice little overlay of the status and the protocol icon. Returns QIcon""" status_icon = getIcon(name) if not proto_int: return status_icon else: ret = _status_icon_cache.get((name, proto_int), None) if ret: return ret proto_name, _ = proto_name_int(proto_int, _PROTO_INT) status_pixmap = status_icon.pixmap(QSize(16,16)) proto_pixmap = getIcon(proto_name).pixmap(QSize(16,16)) combined_pixmap = QImage(28,20, QImage.Format_ARGB32_Premultiplied) painter = QPainter(combined_pixmap) painter.setCompositionMode(painter.CompositionMode_Source) painter.fillRect(combined_pixmap.rect(), Qt.transparent) painter.setCompositionMode(painter.CompositionMode_Source) painter.drawPixmap(QPoint(0,0), status_pixmap) painter.setCompositionMode(painter.CompositionMode_SourceOver) painter.drawPixmap(QPoint(12,4), proto_pixmap) painter.end() #add cache _status_icon_cache[(name, proto_int)] = QIcon(QPixmap.fromImage(combined_pixmap)) return _status_icon_cache[(name, proto_int)]
def _render_qwebpage_full(self, web_rect, render_rect, canvas_size): """Render web page in one step.""" if self._qpainter_needs_tiling(render_rect, canvas_size): # If this condition is true, this function may get stuck. raise ValueError("Rendering region is too large to be drawn" " in one step, use tile-by-tile renderer instead") canvas = QImage(canvas_size, self.qt_image_format) if self.is_jpeg(): # White background for JPEG images, same as we have in all browsers. canvas.fill(Qt.white) else: # Preserve old behaviour for PNG format. canvas.fill(0) painter = QPainter(canvas) try: painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.setWindow(web_rect) painter.setViewport(render_rect) painter.setClipRect(web_rect) self.web_page.mainFrame().render(painter) finally: painter.end() return WrappedQImage(canvas)
def paintEvent( self, event): painter = QPainter( ) painter.begin(self) [S.draw(painter) for S in self.spriteList] self.boundary.draw(painter) painter.end( )
def rerender_pdf_image(self): if self.ratio > RATIO_MIN: self.pdf_image = self.page1.renderToImage(PDF_BASE_RESOLUTION / self.ratio, PDF_BASE_RESOLUTION / self.ratio, self.x, self.y, self.w, self.h) else: # image1 = self.page1.renderToImage(PDF_BASE_RESOLUTION / self.ratio, # PDF_BASE_RESOLUTION / self.ratio, # self.x, self.y, self.w, self.h) # image2 = self.page2.renderToImage(PDF_BASE_RESOLUTION, # / self.ratio, # PDF_BASE_RESOLUTION # / self.ratio, # ) # # self.x, self.y, self.w, self.h) self.pdf_image = QImage(self.w, self.h, self.image1.format()) self.pdf_image.fill(QtCore.Qt.white) painter = QPainter() painter.begin(self.pdf_image) painter.drawImage(self.pdf_image.rect(), self.image1, QRect(self.x * self.ratio/self.begin_ratio, self.y * self.ratio/self.begin_ratio, self.w * self.ratio/self.begin_ratio, self.h * self.ratio/self.begin_ratio)) painter.end() x1 = MAGIC_RECT.x() / self.ratio - self.x y1 = MAGIC_RECT.y() / self.ratio - self.y h1 = MAGIC_RECT.height() / self.ratio w1 = MAGIC_RECT.width() / self.ratio
def endDrawing(self, pos): has_moved = self._hasMoved # _hasMoved will change after calling moveTo if has_moved: self.moveTo(pos) else: assert(self.pos == pos) self.moveTo(QPointF(pos.x()+0.0001, pos.y()+0.0001)) # move a little tempi = QImage(QSize(self.bb.width(), self.bb.height()), QImage.Format_ARGB32_Premultiplied) #TODO: format tempi.fill(0) painter = QPainter(tempi) self.scene.render(painter, target=QRectF(), source=QRectF(QPointF(self.bb.x(), self.bb.y()), QSizeF(self.bb.width(), self.bb.height()))) painter.end() ndarr = qimage2ndarray.rgb_view(tempi)[:,:,0] labels = numpy.where(ndarr>0,numpy.uint8(self.drawnNumber),numpy.uint8(0)) labels = labels.swapaxes(0,1) assert labels.shape[0] == self.bb.width() assert labels.shape[1] == self.bb.height() ## ## ensure that at least one pixel is label when the brush size is 1 ## ## this happens when the user just clicked without moving ## in that case the lineitem will be so tiny, that it won't be rendered ## into a single pixel by the code above if not has_moved and self.brushSize <= 1 and numpy.count_nonzero(labels) == 0: labels[labels.shape[0]//2, labels.shape[1]//2] = self.drawnNumber self.brushStrokeAvailable.emit(QPointF(self.bb.x(), self.bb.y()), labels)
def screenshot(self): logging.debug('screenshot() invoked') frame = self.page().mainFrame() size = frame.contentsSize() if (self.screenWidth): size.setWidth(self.screenWidth) if (self.screenHeight): size.setHeight(self.screenHeight) if (self.minWidth and self.minWidth > self.screenWidth): size.setWidth(self.minWidth) if (self.minHeight and self.minHeight > self.screenHeight): size.setHeight(self.minHeight) self.page().setViewportSize(size) image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() buffer = QBuffer() buffer.open(QIODevice.ReadWrite) image.save(buffer, self.format, self.quality) logging.debug('screenshot() returned image of type ' + self.content_type + ' of length ' + str(buffer.data().length())) return { 'content': buffer.data(), 'content_type': self.content_type }
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': self.composeRgba(img, self.contours, CONTOURS_COLORTABLE) elif self.contour_mode == 'contours': self.get_contours(img, self.contours) 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) painter.end() self.update()
def paintEvent(self, event): p = QPainter(self) p.fillRect(event.rect(), Qt.white) start = self.m_offset / self.m_height y = start * self.m_height - self.m_offset if self.m_offset <= 0: start = 0 y = -self.m_offset end = start + self.height() / self.m_height + 1 if end > len(self.m_colorNames) - 1: end = len(self.m_colorNames) - 1 for i in range(start, end): p.setBrush(Qt.NoBrush) p.setPen(Qt.black) if i == self.m_highlight: p.fillRect(0, y, self.width(), self.m_height, QColor(0, 64, 128)) p.setPen(Qt.white) if i == self.m_selected: p.fillRect(0, y, self.width(), self.m_height, QColor(0, 128, 240)) p.setPen(Qt.white) p.drawText(self.m_height + 2, y, self.width(), self.m_height, Qt.AlignVCenter, self.m_colorNames[i]) p.setPen(Qt.NoPen) p.setBrush(QBrush(self.m_firstColor[i])) p.drawRect(1, y + 1, self.m_height - 2, self.m_height - 2) p.setBrush(QBrush(self.m_secondColor[i])) p.drawRect(5, y + 5, self.m_height - 11, self.m_height - 11) y += self.m_height p.end()
def capture(self, region=None, selector=None, format=QImage.Format_ARGB32_Premultiplied): """Returns snapshot as QImage. :param region: An optional tupple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.main_frame.render(painter) painter.end() image = image.copy(x1, y1, w, h) else: image = QImage(self.page.viewportSize(), format) painter = QPainter(image) self.main_frame.render(painter) painter.end() return image
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def renderedImage(self, width, height, extent, transp_background=False, layerids=None): if QGis.QGIS_VERSION_INT < 20700: return self._renderedImage2(width, height, extent, transp_background, layerids) from qgis.core import QgsMapRendererCustomPainterJob antialias = True # render map image with QgsMapRendererCustomPainterJob settings = self.context.canvas.mapSettings() settings.setOutputSize(QSize(width, height)) settings.setExtent(extent.unrotatedRect()) settings.setRotation(extent.rotation()) if layerids: settings.setLayers(layerids) if transp_background: settings.setBackgroundColor(QColor(Qt.transparent)) #else: #TODO: remove #settings.setBackgroundColor(self.context.canvas.canvasColor()) image = QImage(width, height, QImage.Format_ARGB32_Premultiplied) painter = QPainter() painter.begin(image) if antialias: painter.setRenderHint(QPainter.Antialiasing) job = QgsMapRendererCustomPainterJob(settings, painter) job.start() job.waitForFinished() painter.end() return tools.base64image(image)
def __init__(self, parent, delegate): QWidget.__init__(self, parent) self.delegate = delegate self.emitted = False self.ui = Ui_AskVerdict() self.ui.setupUi(self) # build verdict icons if not AskVerdict.icons_cache: for text in VERDICTS: color = VERDICT_TO_ROW_COLORS.get(text[0]) pixmap = QPixmap(16, 16) pixmap.fill(Qt.transparent) if color: painter = QPainter(pixmap) painter.setPen(Qt.black) painter.setBrush(color) painter.drawEllipse(0, 0, 15, 15) painter.end() AskVerdict.icons_cache[text] = QIcon(pixmap) # set combo verdict for text in ('other...', 'skip', 'retry'): self.ui.comboVerdict.addItem(AskVerdict.icons_cache[text], text) model = self.ui.comboVerdict.model() model.itemFromIndex(model.index(0, 0)).setSelectable(False) self.ui.comboVerdict.activated.connect(self.on_dropdown_item_activated) self.ui.goodVerdict.clicked.connect(self.on_good_bad_button_clicked) self.ui.goodVerdict.setIcon(AskVerdict.icons_cache["good"]) self.ui.badVerdict.clicked.connect(self.on_good_bad_button_clicked) self.ui.badVerdict.setIcon(AskVerdict.icons_cache["bad"])
def capture(self, region=None, selector=None, format=QImage.Format_ARGB32_Premultiplied): """Returns snapshot as QImage. :param region: An optional tupple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.currentFrame().render(painter) painter.end() image = image.copy(x1, y1, w, h) else: self.currentFrame().setScrollBarPolicy(QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self.currentFrame().setScrollBarPolicy(QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff) self.setViewportSize(self.currentFrame().contentsSize()) image = QImage(self.viewportSize(), format) painter = QPainter(image) self.currentFrame().render(painter) painter.end() return image
def get_trial(scene_info, show_bg=True, show_sprite=True, show_box=True): case_num = scene_info.chapter sprite_id = scene_info.sprite if case_num > 6 or case_num <= 0: case_num = 1 out = None if show_bg: if scene_info.movie >= 0: out = get_movie(scene_info.movie) elif scene_info.flash >= 0: out = get_flash(scene_info.flash) elif scene_info.bgd >= 0: out = get_bgd(scene_info.bgd) else: # out = QImage(os.path.join(BG_DIR, "bg_%03d.png" % (199 + case_num))) out = get_bg(199 + case_num) else: out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) if not out.format() is QImage.Format_ARGB32_Premultiplied: out = out.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(out) painter.setRenderHint(QPainter.Antialiasing, True) if show_sprite: sprite_id.sprite_type = SPRITE_TYPE.stand sprite = get_sprite(sprite_id) if sprite: painter.drawImage(out.rect(), sprite, sprite.rect()) if not scene_info.img_filter == IMG_FILTERS.unfiltered: painter.end() out = filter_image(out, scene_info.img_filter) painter = QPainter(out) painter.setRenderHint(QPainter.Antialiasing, True) if show_box: box = get_box(scene_info) painter.drawImage(out.rect(), box, box.rect()) return out
def previewPixmap(self, size, vMin, vMax): pix = QPixmap(size) pix.fill(Qt.white) p = QPainter(pix) if self.item_count() == 0: p.drawLine(0, 0, size.width() - 1, size.height() - 1) p.drawLine(0, size.height() - 1, size.width() - 1, 0) else: for i in xrange(size.width()): v = vMin + (vMax - vMin) * i / (size.width() - 1) p.setPen(rgb2qcolor(self.value(v))) p.drawLine(i, 0, i, size.height() - 1) p.end() return pix
def paintEvent(self, event): pixmap = self._shadowPixmap widget_rect = QRectF(QPointF(0.0, 0.0), QSizeF(self.size())) frame_rect = QRectF(self.contentsRect()) left, top, right, bottom = self.getContentsMargins() pixmap_rect = QRectF(QPointF(0, 0), QSizeF(pixmap.size())) # Shadow casting rectangle. pixmap_shadow_rect = pixmap_rect.adjusted(left, top, -right, -bottom) source_rects = self._shadowPixmapFragments(pixmap_rect, pixmap_shadow_rect) target_rects = self._shadowPixmapFragments(widget_rect, frame_rect) painter = QPainter(self) for source, target in zip(source_rects, target_rects): painter.drawPixmap(target, pixmap, source) painter.end()
def on_stampa_triggered(self, checked=None): """Slot launched when the user click on the "stampa" button""" if checked is None: return printer = QPrinter() print_dialog = QPrintDialog(printer, self) if print_dialog.exec_() == QDialog.Accepted: printer.setOrientation(QPrinter.Landscape) painter = QPainter() painter.begin(printer) geometry = self.ui_calendar.Table.geometry() self.ui_calendar.Table.setGeometry(printer.pageRect()) self.ui_calendar.Table.render(painter) self.ui_calendar.Table.setGeometry(geometry) painter.end()
def _load_finished(self, result): if self.post_load_delay > 0: logger.debug( "Waiting {} seconds for page to run after load".format( self.post_load_delay)) time.sleep(int(self.post_load_delay)) frame = self.page().mainFrame() image = QImage(self.img_size, QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() image.save(self.output_file) self._loaded = True
def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) br = QBrush(QColor(Config.dimcolor)) painter = QPainter() painter.begin(self.mkpixmap) painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(), br) painter.end() self.wmk.setPixmap(self.mkpixmap)
def _load_icon(filename, backgroundColor, width, height): foreground = QPixmap() foreground.load(filename) pixmap = QPixmap(foreground.size()) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) painter.drawPixmap(QPointF(0, 0), foreground) painter.end() pixmap = pixmap.scaled(QSize(width, height), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def drawPixmapForCkecked(self): self.pixmapCkecked = QPixmap(self.itemWidth, self.itemHeight) self.pixmapCkecked.fill(Qt.transparent) painter = QPainter() painter.begin(self.pixmapCkecked) painter.setRenderHint(QPainter.Antialiasing) pen = QPen() pen.setWidth(2) painter.setPen(pen) painter.drawRect(QRect(5,5,self.itemWidth-10, self.itemHeight-10)) pen.setWidth(4) painter.setPen(pen) painter.drawLine(self.itemWidth/2-5, self.itemHeight/2, self.itemWidth/2, self.itemHeight-9) painter.drawLine(self.itemWidth/2, self.itemHeight-9, self.itemWidth/2+10, 2) painter.end()
def url2image(url, file_name=None): """Function at the specified url downloads the page and stores it QImage object and returns it. If you pass file_name, then the function will save the picture in the file. Функция по указанному url загружает страницу и сохраняет ее объект QImage и возвращает его. Если передать file_name, тогда функция сохранит в файл картинку. """ # Нужно создавать только один раз global qApp if qApp is None: qApp = QApplication([]) # Пришлось добавить из-за того, что картинки не прогружались load_pyqt4_plugins() # TODO: прятать вертикальный и горизонтальный ползунки # Загрузка url и ожидание ее view = QWebView() view.setPage(WebPage()) # view.show() view.load(QUrl(url)) loop = QEventLoop() view.loadFinished.connect(loop.quit) loop.exec_() # Запрашиваем через javascript размеры страницы сайта width = view.page().mainFrame().evaluateJavaScript( "window.document.body.scrollWidth") height = view.page().mainFrame().evaluateJavaScript( "window.document.body.scrollHeight") # Устанавливаем границы документа view.page().setViewportSize(QSize(width, height)) img = QImage(width, height, QImage.Format_ARGB32) painter = QPainter(img) painter.setRenderHint(QPainter.HighQualityAntialiasing) view.page().mainFrame().render(painter) painter.end() if file_name: img.save(file_name) # qApp.exec() return img
def data(self, index, role): ''' Reimplement, see labelListModel or boxListModel for concrete example :param index: :param role: ''' if role == Qt.EditRole and index.column() == self.ColumnID.Name: name = self._elements[index.row()].name return decode_to_qstring(name, 'utf-8') elif role == Qt.ToolTipRole and index.column() == self.ColumnID.Delete: s = "Delete {}".format(self._elements[index.row()].name) return decode_to_qstring(s, 'utf-8') elif role == Qt.ToolTipRole and index.column() == self.ColumnID.Name: suffix = self._getToolTipSuffix(index.row()) s = "{}\nDouble click to rename {}".format( self._elements[index.row()].name, suffix) return decode_to_qstring(s, 'utf-8') elif role == Qt.DisplayRole and index.column() == self.ColumnID.Name: name = self._elements[index.row()].name return decode_to_qstring(name, 'utf-8') if role == Qt.DecorationRole and index.column( ) == self.ColumnID.Delete: if index.row() in self.unremovable_rows: return row = index.row() pixmap = QPixmap(_NPIXELS, _NPIXELS) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QColor("red")) painter.drawEllipse(1, 1, _NPIXELS - 2, _NPIXELS - 2) pen = QPen(QColor("black")) pen.setWidth(2) painter.setPen(pen) x = _XSTART y = _NPIXELS - x painter.drawLine(x, x, y, y) painter.drawLine(y, x, x, y) painter.end() icon = QIcon(pixmap) return icon
def grab_svg(scene): """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ from PyQt4.QtSvg import QSvgGenerator svg_buffer = QBuffer() gen = QSvgGenerator() gen.setOutputDevice(svg_buffer) items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10) if items_rect.isNull(): items_rect = QRectF(0, 0, 10, 10) width, height = items_rect.width(), items_rect.height() rect_ratio = float(width) / height # Keep a fixed aspect ratio. aspect_ratio = 1.618 if rect_ratio > aspect_ratio: height = int(height * rect_ratio / aspect_ratio) else: width = int(width * aspect_ratio / rect_ratio) target_rect = QRectF(0, 0, width, height) source_rect = QRectF(0, 0, width, height) source_rect.moveCenter(items_rect.center()) gen.setSize(target_rect.size().toSize()) gen.setViewBox(target_rect) painter = QPainter(gen) # Draw background. painter.setBrush(QBrush(Qt.white)) painter.drawRect(target_rect) # Render the scene scene.render(painter, target_rect, source_rect) painter.end() buffer_str = str(svg_buffer.buffer()) return unicode(buffer_str.decode("utf-8"))
def export_scene(canvas, width, height, dpi, exportFileName): """ This function exports the scene to a file. """ # need this to make sure we take away focus from # any currently selected legend items canvas.clearFocus() with HiddenStitchManager(canvas): # NOTE: We seem to need the 1px buffer region to avoid # the image being cut off margin = 10 theScene = visible_bounding_rect(canvas.items()) theScene.adjust(-margin, -margin, margin, margin) # check if user requested an svg file svg = True if QFileInfo(exportFileName).completeSuffix() == "svg" \ else False if svg: generator = QSvgGenerator() generator.setFileName(exportFileName) generator.setSize(QSize(width, height)) generator.setViewBox(QRect(0, 0, width, height)) generator.setTitle("sconcho generated SVG image") generator.setDescription("this svg image was exported from " "a sconcho project") generator.setResolution(dpi) else: generator = QImage(width + 2 * margin, height + 2 * margin, QImage.Format_ARGB32_Premultiplied) generator.fill(1) inchesToMeter = 39.3700787 generator.setDotsPerMeterX(dpi * inchesToMeter) generator.setDotsPerMeterY(dpi * inchesToMeter) painter = QPainter(generator) painter.setRenderHints(QPainter.SmoothPixmapTransform | QPainter.HighQualityAntialiasing | QPainter.TextAntialiasing) painter.setBackgroundMode(Qt.TransparentMode) canvas.render(painter, QRectF(), theScene) painter.end() if not svg: generator.save(exportFileName)
def __updateMask(self): opt = QStyleOption() opt.init(self) rect = opt.rect size = rect.size() mask = QBitmap(size) p = QPainter(mask) p.setRenderHint(QPainter.Antialiasing) p.setBrush(Qt.black) p.setPen(Qt.NoPen) p.drawRoundedRect(rect, self.__radius, self.__radius) p.end() self.setMask(mask)
def renderScene(self, s, exportFilename=None, joinRendering=True): img = QImage(30, 30, QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) p = QPainter(img) s.render(p) #trigger a rendering of the whole scene if joinRendering: #wait for all the data to arrive s.joinRendering() #finally, render everything s.render(p) p.end() if exportFilename is not None: img.save(exportFilename) return byte_view(img)
def print_(self): """Prints the document.""" self._stop = False resolution = self.resolution() p = self.printer() p.setFullPage(True) p.setResolution(resolution) center = p.paperRect().center() painter = QPainter(p) pages = self.pageList() if p.pageOrder() != QPrinter.FirstPageFirst: pages.reverse() total = len(pages) opts = self.renderOptions() document = self.document() for num, pageNum in enumerate(pages, 1): if self._stop: return p.abort() self.progress(num, total, pageNum) if num > 1: p.newPage() with lock(document): opts.write(document) page = document.page(pageNum - 1) img = page.renderToImage(resolution, resolution) rect = img.rect() rect.moveCenter(center) painter.drawImage(rect, img) return painter.end()
def send_report(self): from PyQt4.QtSvg import QSvgGenerator if self.model: self.reportSection("Tree") urlfn, filefn = self.getUniqueImageName(ext=".svg") svg = QSvgGenerator() svg.setFileName(filefn) ssize = self.scene.sceneRect().size() w, h = ssize.width(), ssize.height() fact = 600 / w svg.setSize(QSize(600, h * fact)) painter = QPainter() painter.begin(svg) self.scene.render(painter) painter.end()
def replace_all_colors(image, color): new_img = image.copy() if not new_img.format() is QImage.Format_ARGB32_Premultiplied: new_img = new_img.convertToFormat(QImage.Format_ARGB32_Premultiplied) color_img = QImage(new_img.width(), new_img.height(), QImage.Format_ARGB32_Premultiplied) color_img.fill(color.rgba()) painter = QPainter(new_img) painter.setCompositionMode(QPainter.CompositionMode_SourceAtop) painter.drawImage(new_img.rect(), color_img, color_img.rect()) painter.end() return new_img
def data(self, index, role): if role == Qt.EditRole and index.column() == 0: return self._labels[index.row()].color if role == Qt.EditRole and index.column() == 1: return self._labels[index.row()].name if role == Qt.ToolTipRole and index.column() == 0: return "Hex code : " + self._labels[ index.row()].color.name() + "\n DoubleClick to change" if role == Qt.ToolTipRole and index.column() == 1: suffix = self._getToolTipSuffix(index.row()) return self._labels[ index.row()].name + "\n DoubleClick to rename" + suffix if role == Qt.ToolTipRole and index.column() == 2: return "Delete " + self._labels[index.row()].name if role == Qt.DecorationRole and index.column() == 0: row = index.row() value = self._labels[row] pixmap = QPixmap(26, 26) pixmap.fill(value.color) icon = QIcon(pixmap) return icon if role == Qt.DecorationRole and index.column() == 2: row = index.row() pixmap = QPixmap(26, 26) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QColor("red")) painter.drawEllipse(1, 1, 24, 24) pen = QPen(QColor("black")) pen.setWidth(2) painter.setPen(pen) painter.drawLine(8, 8, 18, 18) painter.drawLine(18, 8, 8, 18) painter.end() icon = QIcon(pixmap) return icon if role == Qt.DisplayRole and index.column() == 1: row = index.row() value = self._labels[row] return value.name
def paintEvent(self, event): painter = QPainter(self) painter.fillRect(self.rect(), QColor('#101010')) image = self._image if image is not None: if self.height() < 240: fast_scaler = QTransform() scale = 297 / image.height() if self.mirror: fast_scaler.scale(-scale, scale) else: fast_scaler.scale(scale, scale) rect = event.rect() painter.drawPixmap( rect, QPixmap.fromImage( image.transformed(fast_scaler)).scaledToHeight( self.height(), Qt.SmoothTransformation), rect) else: transform = QTransform() scale = min(self.width() / image.width(), self.height() / image.height()) if self.mirror: transform.translate( (self.width() + image.width() * scale) / 2, (self.height() - image.height() * scale) / 2) transform.scale(-scale, scale) else: transform.translate( (self.width() - image.width() * scale) / 2, (self.height() - image.height() * scale) / 2) transform.scale(scale, scale) inverse_transform, invertible = transform.inverted() rect = inverse_transform.mapRect(event.rect()).adjusted( -1, -1, 1, 1).intersected(image.rect()) painter.setTransform(transform) if self.height() > 400: painter.drawPixmap(rect, QPixmap.fromImage(image), rect) else: painter.drawImage(rect, image, rect) painter.end()
def capture(self, output_file): """ capture a screenshot from WebView """ if ".png" not in output_file: raise Exception("Err: image format invalid, please save with png extension.") self.load(QUrl(self.url)) self.wait_load() # set to webpage size frame = self.page().mainFrame() self.page().setViewportSize(self.size) # render image image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() image.save("{}".format(output_file))
def paintEvent(self, e): if self.dirty: iconSize = self.style().pixelMetric(QStyle.PM_SmallIconSize) pix = QPixmap(iconSize, iconSize) pix.fill(self.palette().button().color()) p = QPainter(pix) w = pix.width() h = pix.height() p.setPen(QPen(Qt.gray)) p.setBrush(self.col) p.drawRect(2, 2, w - 5, h - 5) self.setIcon(QIcon(pix)) self.dirty = False p.end() QPushButton.paintEvent(self, e)
def paintEvent(self, e): qp = QPainter() qp.begin(self) if self.step == 'waiting_to_start': qp.setPen(QPen(Qt.red, 20, Qt.SolidLine)) qp.setFont(QFont('Decorative', 20)) if self.step == 'calibration_started': qp.setPen(QPen(Qt.red, 35, Qt.SolidLine)) qp.drawEllipse(self.x, self.y, 40, 40) if self.step == 'show_gaze': qp.setPen(QPen(Qt.red, 10, Qt.SolidLine)) qp.drawEllipse(self.x, self.y, 10, 10) qp.end()
def _load_finished(self): #print "finished" frame = self.page().mainFrame() size = QSize(self.resolution[0], self.resolution[1]) self.page().setPreferredContentsSize(size) self.resize(frame.contentsSize()) self.page().setViewportSize(frame.contentsSize()) html = frame.documentElement() #two modes for these lines of code: page lenght and links position mode: page length activeted keys = [] values = [] for link in html.findAll('a'): href = unicode(link.attribute('href')) if href.startswith('./'): key = href.split('./')[-1].split('#')[0] keys.append(key) value = link.geometry().topLeft().x(), link.geometry().topLeft( ).y() values.append(value) counts = Counter( keys) # so we have: {'name':3, 'state':1, 'city':1, 'zip':2} for s, num in counts.items(): if num > 1: # ignore strings that only appear once for suffix in range( 1, num + 1): # suffix starts at 1 and increases by 1 each time keys[keys.index(s)] = s + '-----##$$$##-----' + str(suffix) self.positions = {k: v for k, v in zip(keys, values)} img = QImage(frame.contentsSize(), QImage.Format_ARGB32) paint = QPainter(img) print("rendering...") frame.render(paint) paint.end() img.save(self.out + "_" + str(self.resolution[0]) + ".png") print("... done") print("result: %s" % self.out) #print html.findFirst("div[class=pyqt_is_shit]").geometry().topLeft().y() self.page_length = html.findFirst( "div[class=pyqt_is_shit]").geometry().topLeft().y() print self.page_length #self.punched.emit(self.page_length) #self.close() #print "done" self.finished = True
def capture(self, url, output_file, viewport_size=None): """Capture `url` to `output_file`. If `viewport_size` is truthy, interpret it as a tuple (width, height) to use as the viewport size. Otherwise the size of the page frame will be used. """ self.load(QUrl(url)) self.wait_load() frame = self.page().mainFrame() viewport_size = PyQt4.QtCore.QSize( *viewport_size) if viewport_size else frame.contentsSize() self.page().setViewportSize(viewport_size) image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() image.save(output_file)
def round(self): bmp = QBitmap(self.size()) p = QPainter() p.begin(bmp) p.fillRect(bmp.rect(), Qt.white) p.setBrush(QColor(0, 0, 0)) p.drawRoundedRect(bmp.rect(), 5, 5) p.setPen(QColor(255, 255, 255, 255)) p.drawPoints(QPointF(self.width() - 2, self.height() - 1), QPointF(self.width() - 1, self.height() - 2)) p.setPen(QColor(0, 0, 0)) p.drawPoints(QPointF(0, 2), QPointF(3, 0), QPointF(2, 0), QPointF(1, 1)) p.end() self.setMask(bmp)
def drawBaseImage(self, backgroundImage, titleText, titleFont, fontSize, alignment, xOffset, yOffset): if self._image == None or not self.lastBackgroundImage == backgroundImage: self.lastBackgroundImage = backgroundImage if backgroundImage == "": im = Image.new("RGB", (1280, 720), "black") else: im = Image.open(backgroundImage) # resize if necessary if not im.size == (1280, 720): im = im.resize((1280, 720), Image.ANTIALIAS) self._image = ImageQt(im) self._image1 = QtGui.QImage(self._image) painter = QPainter(self._image1) font = titleFont font.setPointSizeF(fontSize) painter.setFont(font) painter.setPen(QColor(255, 255, 255)) yPosition = yOffset fm = QtGui.QFontMetrics(font) if alignment == 0: #Left xPosition = xOffset if alignment == 1: #Middle xPosition = xOffset - fm.width(titleText) / 2 if alignment == 2: #Right xPosition = xOffset - fm.width(titleText) painter.drawText(xPosition, yPosition, titleText) painter.end() buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) self._image1.save(buffer, "PNG") strio = io.BytesIO() strio.write(buffer.data()) buffer.close() strio.seek(0) return Image.open(strio)
def run_script(iface): canvas = iface.mapCanvas() img = QImage(QSize(1920, 1080), QImage.Format_ARGB32_Premultiplied) color = QColor(255, 255, 255) p = QPainter(img) for path in paths: #accessibilityLayer.setDataProvider(path) # http://www.qgisworkshop.org/html/workshop/python_in_qgis_tutorial2.html rlayer = iface.addRasterLayer(path) # http://gis.stackexchange.com/questions/26846 rlayer.loadNamedStyle( '/home/matthewc/microaccessibility/times/colors.qml') # add the vector layers poly = iface.addVectorLayer( 'dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=POLYGON table="public"."ucsb_final_polygon" (way) sql=', 'poly', 'postgres') poly.loadNamedStyle('/home/matthewc/microaccessibility/times/poly.qml') line = iface.addVectorLayer( 'dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=LINESTRING table="public"."ucsb_final_line" (way) sql=', 'line', 'postgres') line.loadNamedStyle('/home/matthewc/microaccessibility/times/line.qml') renderer = canvas.mapRenderer() img.fill(color.rgb()) p.begin(img) p.setRenderHint(QPainter.Antialiasing) renderer.setOutputSize(img.size(), img.logicalDpiX()) renderer.render(p) p.setFont(QFont("Ubuntu", 48, QFont.Bold)) p.setPen(QColor(0, 0, 0)) p.drawText(10, 58, parseToTime(path)) p.end() img.save(path + ".png", "png") QgsMapLayerRegistry.instance().removeMapLayer(rlayer.id()) QgsMapLayerRegistry.instance().removeMapLayer(poly.id()) QgsMapLayerRegistry.instance().removeMapLayer(line.id())
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 render(self, url): """The real worker. Loads the page (_load_page) and awaits the end of the given 'delay'. While it is waiting outstanding QApplication events are processed. After the given delay, the Window or Widget (depends on the value of 'grabWholeWindow' is drawn into a QPixmap and postprocessed (_post_process_image). """ self._load_page(url, self.width, self.height, self.timeout) # Wait for end of timer. In this time, process # other outstanding Qt events. if self.wait > 0: if self.logger: self.logger.debug("Waiting %d seconds " % self.wait) waitToTime = time.time() + self.wait while time.time() < waitToTime and QApplication.hasPendingEvents(): QApplication.processEvents() if self.renderTransparentBackground: # Another possible drawing solution image = QImage(self._page.viewportSize(), QImage.Format_ARGB32) image.fill(QColor(255, 0, 0, 0).rgba()) # http://ariya.blogspot.com/2009/04/transparent-qwebview-and-qwebpage.html palette = self._view.palette() palette.setBrush(QPalette.Base, Qt.transparent) self._page.setPalette(palette) self._view.setAttribute(Qt.WA_OpaquePaintEvent, False) painter = QPainter(image) painter.setBackgroundMode(Qt.TransparentMode) self._page.mainFrame().render(painter) painter.end() else: if self.grabWholeWindow: # Note that this does not fully ensure that the # window still has the focus when the screen is # grabbed. This might result in a race condition. self._view.activateWindow() image = QPixmap.grabWindow(self._window.winId()) else: image = QPixmap.grabWidget(self._window) return self._post_process_image(image)
def paintEvent(self, e): """This event handler is reimplemented in this subclass to receive paint events passed in event. A paint event is a request to repaint all or part of a widget. It can happen for one of the following reasons: repaint() or update() was invoked,the widget was obscured and has now been uncovered, or many other reasons. """ qp = QPainter() qp.begin(self) # if no steos have been receive draw last_diagram_bytes if not self.steps and self.last_diagram_bytes: diagram_bytes = self.last_diagram_bytes else: diagram = self.build_graph() diagram_bytes = diagram.pipe('svg') self.last_diagram_bytes = diagram_bytes svg = QSvgRenderer(diagram_bytes) svg.render(qp) qp.end()