def __save_atlas(self) -> None: """Saving all the atlas to image file. We should turn transparent background to white first. Then using QImage class to merge into one image. """ count = self.structure_list.count() if count < 1: return lateral = self.__save_atlas_ask() if not lateral: return file_name = self.output_to("atlas image", qt_image_format) if not file_name: return width = self.structure_list.iconSize().width() image_main = QImage(QSize( lateral * width if count > lateral else count * width, ((count // lateral) + bool(count % lateral)) * width ), self.__atlas_image(0).format()) image_main.fill(Qt.transparent) painter = QPainter(image_main) for row in range(count): image = self.__atlas_image(row) painter.drawImage(QPointF(row % lateral, row // lateral) * width, image) painter.end() pixmap = QPixmap.fromImage(image_main) pixmap.save(file_name) self.save_reply_box("Atlas", file_name)
def __save_atlas(self) -> None: """Save function as same as type synthesis widget.""" count = self.collection_list.count() if count < 1: return lateral, ok = QInputDialog.getInt(self, "Atlas", "The number of lateral:", 5, 1) if not ok: return file_name = self.output_to("atlas image", qt_image_format) if not file_name: return icon_size = self.collection_list.iconSize() width = icon_size.width() image = self.collection_list.item(0).icon().pixmap(icon_size).toImage() image_main = QImage( QSize(lateral if count > lateral else count, (count // lateral) + bool(count % lateral)) * width, image.format()) image_main.fill(Qt.transparent) painter = QPainter(image_main) for row in range(count): image = self.collection_list.item(row).icon().pixmap( icon_size).toImage() painter.drawImage( QPointF(row % lateral, row // lateral) * width, image) painter.end() pixmap = QPixmap() pixmap.convertFromImage(image_main) pixmap.save(file_name) self.save_reply_box("Atlas", file_name)
def _paint_inner_grid(self, painter: QPainter, rect: QRect, colors) -> None: margin = 10 job_nr = len(colors) grid_dim = math.ceil(math.sqrt(job_nr)) k = 0 colors_hash = hash(tuple([color.name() for color in colors])) if colors_hash not in self._image_cache: foreground_image = QImage(grid_dim, grid_dim, QImage.Format_ARGB32) foreground_image.fill(QColorConstants.Gray) for y in range(grid_dim): for x in range(grid_dim): if k >= job_nr: color = QColorConstants.Gray else: color = colors[k] foreground_image.setPixel(x, y, color.rgb()) k += 1 self._image_cache[colors_hash] = foreground_image else: foreground_image = self._image_cache[colors_hash] painter.drawImage(rect, foreground_image)
def render_image(scene): image = QImage(scene.sceneRect().size().toSize(), QImage.Format_ARGB32) image.fill(Qt.transparent) painter = QPainter(image) scene.render(painter) painter.end() return image
def create_thumbnail(name='./.thumbnail', model='tfm', geometry=False, chemistry=False, background=None): if background is not None and os.path.exists(background): img = QImage(background) base = img.scaled(300, 300).scaled(128, 128, Qt.IgnoreAspectRatio) else: base = QImage(QSize(128, 128), QImage.Format_ARGB32) base.fill(Qt.white) painter = QPainter(base) # add images model = QImage(get_image_path(model + '.svg')) painter.drawImage(0, 128 - 24, model) if geometry: geo = QImage(get_image_path('geometry.svg')) painter.drawImage(24, 128 - 24, geo) if chemistry: geo = QImage(get_image_path('chemistry.svg')) painter.drawImage(24 * 2, 128 - 24, geo) base.save(name, "PNG") del painter
def toImage(self, *args): """ .. py:method:: toImage() :noindex: Convert the graphic to a `QImage` All pixels of the image get initialized by 0 ( transparent ) before the graphic is scaled and rendered on it. The format of the image is `QImage.Format_ARGB32_Premultiplied`. The size of the image is the default size ( ceiled to integers ) of the graphic. :return: The graphic as image in default size .. py:method:: toImage(size, [aspectRatioMode=Qt.IgnoreAspectRatio]) :noindex: Convert the graphic to a `QImage` All pixels of the image get initialized by 0 ( transparent ) before the graphic is scaled and rendered on it. The format of the image is `QImage.Format_ARGB32_Premultiplied`. :param QSize size: Size of the image :param `Qt.AspectRatioMode` aspectRatioMode: Aspect ratio how to scale the graphic :return: The graphic as image .. seealso:: :py:meth:`toPixmap()`, :py:meth:`render()` """ if len(args) == 0: if self.isNull(): return QImage() sz = self.defaultSize() w = np.ceil(sz.width()) h = np.ceil(sz.height()) image = QImage(w, h, QImage.Format_ARGB32) image.fill(0) r = QRect(0, 0, sz.width(), sz.height()) painter = QPainter(image) self.render(painter, r, Qt.KeepAspectRatio) painter.end() return image elif len(args) in (1, 2): size = args[0] aspectRatioMode = Qt.IgnoreAspectRatio if len(args) == 2: aspectRatioMode = args[-1] image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(0) r = QRect(0, 0, size.width(), size.height()) painter = QPainter(image) self.render(painter, r, aspectRatioMode) return image
def pixmap(self, size, mode, state): """Return the icon as a pixmap with requested size, mode, and state.""" img = QImage(size, QImage.Format_ARGB32) img.fill(Qt.transparent) pixmap = QPixmap.fromImage(img, Qt.NoFormatConversion) painter = QPainter(pixmap) self.paint(painter, QRect(QPoint(0, 0), size), mode, state) return pixmap
def paintEvent(self, event): super(DetailedProgress, self).paintEvent(event) if not self._current_progress: return painter = QPainter(self) width = self.width() height = self.height() aspect_ratio = float(width) / height nr_realizations = max([iens for iens, _, _ in self._current_progress]) + 1 fm_size = max( [len(progress) for _, progress, _ in self._current_progress]) self.grid_height = math.ceil(math.sqrt(nr_realizations / aspect_ratio)) self.grid_width = math.ceil(self.grid_height * aspect_ratio) sub_grid_size = math.ceil(math.sqrt(fm_size)) cell_height = height / self.grid_height cell_width = width / self.grid_width foreground_image = QImage(self.grid_width * sub_grid_size, self.grid_height * sub_grid_size, QImage.Format_ARGB32) foreground_image.fill(QColor(0, 0, 0, 0)) for index, (iens, progress, _) in enumerate(self._current_progress): y = int(iens / self.grid_width) x = int(iens - (y * self.grid_width)) self.draw_window(x * sub_grid_size, y * sub_grid_size, progress, foreground_image) painter.drawImage(self.contentsRect(), foreground_image) for index, (iens, progress, state) in enumerate(self._current_progress): y = int(iens / self.grid_width) x = int(iens - (y * self.grid_width)) painter.setPen(QColor(80, 80, 80)) painter.drawText(int(x * cell_width), int(y * cell_height), int(cell_width), int(cell_height), int(Qt.AlignHCenter | Qt.AlignVCenter), str(iens)) if iens == self.selected_realization: pen = QPen(QColor(240, 240, 240)) elif (self.has_realization_failed(progress)): pen = QPen(QColor(*self.state_colors['Failure'])) elif (state == JobStatusType.JOB_QUEUE_RUNNING): pen = QPen(QColor(*self.state_colors['Running'])) else: pen = QPen(QColor(80, 80, 80)) thickness = 4 pen.setWidth(thickness) painter.setPen(pen) painter.drawRect( int(x * cell_width) + (thickness // 2), int(y * cell_height) + (thickness // 2), int(cell_width) - (thickness - 1), int(cell_height) - (thickness - 1))
def grab_no_background(self) -> QPixmap: """Grab function without background.""" image = QImage(self.size(), QImage.Format_ARGB32_Premultiplied) image.fill(Qt.transparent) self.switch_grab() self.painter.begin(image) self.render(self.painter, QPoint(), QRegion(), QWidget.DrawChildren) self.switch_grab() return QPixmap.fromImage(image)
def qwtBackgroundWidget(w): if w.parentWidget() is None: return w if w.autoFillBackground(): brush = w.palette().brush(w.backgroundRole()) if brush.color().alpha() > 0: return w if w.testAttribute(Qt.WA_StyledBackground): image = QImage(1, 1, QImage.Format_ARGB32) image.fill(Qt.transparent) painter = QPainter(image) painter.translate(-w.rect().center()) qwtDrawStyledBackground(w, painter) painter.end() if qAlpha(image.pixel(0, 0)) != 0: return w return qwtBackgroundWidget(w.parentWidget())
def create_splash_screen(): """Create splash screen.""" if not running_under_pytest(): image = QImage(500, 400, QImage.Format_ARGB32_Premultiplied) image.fill(0) painter = QPainter(image) renderer = QSvgRenderer(get_image_path('splash')) renderer.render(painter) painter.end() pm = QPixmap.fromImage(image) pm = pm.copy(0, 0, 500, 400) splash = QSplashScreen(pm) splash_font = splash.font() splash_font.setPixelSize(14) splash.setFont(splash_font) else: splash = None return splash
def __structure_list_context_menu(self, point) -> None: """Context menu for the type synthesis results.""" index = self.structure_list.currentIndex().row() self.to_collection.setEnabled(index > -1) self.copy_edges.setEnabled(index > -1) self.copy_image.setEnabled(index > -1) action = self.pop_menu_topo.exec_(self.structure_list.mapToGlobal(point)) if not action: return clipboard = QApplication.clipboard() if action == self.to_collection: self.add_collection(self.answer[index].edges) elif action == self.copy_edges: clipboard.setText(str(self.answer[index].edges)) elif action == self.copy_image: # Turn the transparent background to white image1 = self.__atlas_image() image2 = QImage(image1.size(), image1.format()) image2.fill(Qt.white) painter = QPainter(image2) painter.drawImage(QPointF(0, 0), image1) painter.end() clipboard.setPixmap(QPixmap.fromImage(image2))
def graph2icon(g: Graph, width: int, node_mode: bool, show_label: bool, monochrome: bool, *, except_node: Optional[int] = None, engine: str = "", pos: Optional[_Pos] = None) -> QIcon: """Draw a generalized chain graph.""" if engine: pos = engine_picker(g, engine, node_mode) if pos is None: raise ValueError("no engine selected") if not pos: pixmap = QPixmap(width, width) pixmap.fill(Qt.transparent) return QIcon(pixmap) width_bound = -float('inf') for x, y in pos.values(): if abs(x) > width_bound: width_bound = x if abs(y) > width_bound: width_bound = y width_bound *= 2.5 image = QImage(QSize(int(width_bound), int(width_bound)), QImage.Format_ARGB32_Premultiplied) image.fill(Qt.transparent) painter = QPainter(image) painter.translate(image.width() / 2, image.height() / 2) pen = QPen() r = int(width_bound / 50) pen.setWidth(r) painter.setPen(pen) _font.setPixelSize(r * 6) painter.setFont(_font) # Draw edges if node_mode: for l1, l2 in g.edges: if except_node in {l1, l2}: pen.setColor(Qt.gray) else: pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(QPointF(pos[l1][0], -pos[l1][1]), QPointF(pos[l2][0], -pos[l2][1])) else: color = color_qt('dark-gray') if monochrome else LINK_COLOR color.setAlpha(150) painter.setBrush(QBrush(color)) for link in g.vertices: if link == except_node: pen.setColor(Qt.gray) else: pen.setColor(Qt.black) painter.setPen(pen) painter.drawPolygon(*convex_hull([(pos[n][0], -pos[n][1]) for n, edge in edges_view(g) if link in edge], as_qpoint=True)) # Draw vertices for k, (x, y) in pos.items(): if node_mode: color = color_num(len(list(g.neighbors(k))) - 1) if k == except_node: color.setAlpha(150) else: if monochrome: color = Qt.black elif except_node in dict(edges_view(g))[k]: color = color_qt('green') else: color = color_qt('blue') pen.setColor(color) painter.setPen(pen) painter.setBrush(QBrush(color)) point = QPointF(x, -y) painter.drawEllipse(point, r, r) if show_label: pen.setColor(Qt.darkMagenta) painter.setPen(pen) painter.drawText(point, str(k)) painter.end() return QIcon(QPixmap.fromImage(image).scaledToWidth(width))
def renderDocument(self, plot, filename, sizeMM=(300, 200), resolution=85, format_=None): """ Render a plot to a file The format of the document will be auto-detected from the suffix of the file name. :param qwt.plot.QwtPlot plot: Plot widget :param str fileName: Path of the file, where the document will be stored :param QSizeF sizeMM: Size for the document in millimeters :param int resolution: Resolution in dots per Inch (dpi) """ if isinstance(sizeMM, tuple): sizeMM = QSizeF(*sizeMM) if format_ is None: ext = osp.splitext(filename)[1] if not ext: raise TypeError( "Unable to determine target format from filename") format_ = ext[1:] if plot is None or sizeMM.isEmpty() or resolution <= 0: return title = plot.title().text() if not title: title = "Plot Document" mmToInch = 1.0 / 25.4 size = sizeMM * mmToInch * resolution documentRect = QRectF(0.0, 0.0, size.width(), size.height()) fmt = format_.lower() if fmt in ("pdf", "ps"): printer = QPrinter() if fmt == "pdf": printer.setOutputFormat(QPrinter.PdfFormat) else: printer.setOutputFormat(QPrinter.PostScriptFormat) printer.setColorMode(QPrinter.Color) printer.setFullPage(True) printer.setPaperSize(sizeMM, QPrinter.Millimeter) printer.setDocName(title) printer.setOutputFileName(filename) printer.setResolution(resolution) painter = QPainter(printer) self.render(plot, painter, documentRect) painter.end() elif fmt == "svg": generator = QSvgGenerator() generator.setTitle(title) generator.setFileName(filename) generator.setResolution(resolution) generator.setViewBox(documentRect) painter = QPainter(generator) self.render(plot, painter, documentRect) painter.end() elif fmt in QImageWriter.supportedImageFormats(): imageRect = documentRect.toRect() dotsPerMeter = int(round(resolution * mmToInch * 1000.0)) image = QImage(imageRect.size(), QImage.Format_ARGB32) image.setDotsPerMeterX(dotsPerMeter) image.setDotsPerMeterY(dotsPerMeter) image.fill(QColor(Qt.white).rgb()) painter = QPainter(image) self.render(plot, painter, imageRect) painter.end() image.save(filename, fmt) else: raise TypeError("Unsupported file format '%s'" % fmt)
class Window(QWindow): def __init__(self, parent=None): super().__init__(parent) global colorIndexId colorIndexId += 1 self.m_backgroundColorIndex = colorIndexId self.m_text = "" self.m_image = QImage() self.m_lastPos = QPoint() self.m_backingStore = None self.m_renderTimer = 0 self.initialize() def mousePressEvent(self, event): self.m_lastPos = event.pos() def mouseMoveEvent(self, event): if self.m_lastPos != QPoint(-1, -1): p = QPainter(self.m_image) p.setRenderHint(QPainter.Antialiasing) p.drawLine(self.m_lastPos, event.pos()) self.m_lastPos = event.pos() self.scheduleRender() def mouseReleaseEvent(self, event): if self.m_lastPos != QPoint(-1, -1): p = QPainter(self.m_image) p.setRenderHint(QPainter.Antialiasing) p.drawLine(self.m_lastPos, event.pos()) self.m_lastPos = QPoint(-1, -1) self.scheduleRender() def keyPressEvent(self, event): if event.key() == Qt.Key_Backspace: if len(self.m_text) > 1: self.m_text = self.m_text[:-1] elif event.key() in (Qt.Key_Enter, Qt.Key_Return): self.m_text += "\n" else: self.m_text += event.text() self.scheduleRender() def exposeEvent(self, event): self.scheduleRender() def resizeEvent(self, event): old = QImage(self.m_image) width = max(self.geometry().width(), old.width()) height = max(self.geometry().height(), old.height()) if width > old.width() or height > old.height(): self.m_image = QImage(width, height, QImage.Format_RGB32) self.m_image.fill( colorTable[self.m_backgroundColorIndex % len(colorTable)].rgba() ) p = QPainter(self.m_image) p.drawImage(0, 0, old) self.scheduleRender() def timerEvent(self, event): if self.isExposed(): self.render() self.killTimer(self.m_renderTimer) self.m_renderTimer = 0 def render(self): rect = QRect(QPoint(), self.geometry().size()) self.m_backingStore.resize(rect.size()) self.m_backingStore.beginPaint(QRegion(rect)) device = self.m_backingStore.paintDevice() p = QPainter(device) p.drawImage(0, 0, self.m_image) font = QFont() font.setPixelSize(32) p.setFont(font) p.drawText(rect, 0, self.m_text) self.m_backingStore.endPaint() self.m_backingStore.flush(QRegion(rect)) def scheduleRender(self): if not self.m_renderTimer: self.m_renderTimer = self.startTimer(1) def initialize(self): if self.parent(): self.setGeometry(QRect(160, 120, 320, 240)) else: self.setFlags( self.flags() | Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint ) baseSize = QSize(640, 480) self.setGeometry(QRect(self.geometry().topLeft(), baseSize)) self.setSizeIncrement(QSize(10, 10)) self.setBaseSize(baseSize) self.setMinimumSize(QSize(240, 160)) self.setMaximumSize(QSize(800, 600)) self.create() self.m_backingStore = QBackingStore(self) self.m_image = QImage(self.geometry().size(), QImage.Format_RGB32) self.m_image.fill( colorTable[self.m_backgroundColorIndex % len(colorTable)].rgba() ) self.m_lastPos = QPoint(-1, -1) self.m_renderTimer = 0