def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize key = "{}.SVGIconEngine/{}/{}x{}".format( __name__, self.__cache_id, size.width(), size.height() ) pm = QPixmapCache.find(key) if pm is None or pm.isNull(): pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render( painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() QPixmapCache.insert(key, pm) style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def paintEvent(self, _): painter = QPainter(self) painter.drawPixmap(0, 0, self._darken) if self._band.isVisible(): br = self._band.geometry() r = QRect(br.topLeft(), br.bottomRight()) painter.drawPixmap(r, self._snapshot.copy(r))
def event(self, event): if event.type() == event.Paint: pixmap = self.__pixmap painter = QPainter(self) if not pixmap.isNull(): painter.drawPixmap(0, 0, pixmap) self.drawContents(painter) return True return QSplashScreen.event(self, event)
def picture_children(): # Return a QPicture displaying all children patches of this # node. pic = QPicture() painter = QPainter(pic) for ch in child_patches(): painter.drawPicture(0, 0, ch.picture()) painter.end() return pic
def event(self, event): # type: (QEvent) -> bool if event.type() == QEvent.Paint: pixmap = self.__pixmap painter = QPainter(self) if not pixmap.isNull(): painter.drawPixmap(0, 0, pixmap) self.drawContents(painter) return True return super().event(event)
def paint_with_data(data): model.setItemData(index, data) opt = self.view.viewOptions() opt.rect = QRect(QPoint(0, 0), delegate.sizeHint(opt, index)) delegate.initStyleOption(opt, index) img = QImage(opt.rect.size(), QImage.Format_ARGB32_Premultiplied) p = QPainter(img) try: delegate.paint(p, opt, index) finally: p.end()
def palette_pixmap(colors, size): img = QPixmap(size) img.fill(Qt.transparent) painter = QPainter(img) grad = palette_gradient(colors) grad.setCoordinateMode(QLinearGradient.ObjectBoundingMode) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(grad)) painter.drawRect(0, 0, size.width(), size.height()) painter.end() return img
def paint_with_data_(data): paint_with_data(delegate, data, self.view.viewOptions()) model.setItemData(index, data) opt = self.view.viewOptions() size = delegate.sizeHint(opt, index).expandedTo(QSize(10, 10)) opt.rect = QRect(QPoint(0, 0), size) delegate.initStyleOption(opt, index) img = QImage(opt.rect.size(), QImage.Format_ARGB32_Premultiplied) p = QPainter(img) try: delegate.paint(p, opt, index) finally: p.end()
def createDiscPalettePixmap(width, height, palette): p = QPainter() img = QPixmap(width, height) p.begin(img) p.setPen(QPen(Qt.NoPen)) if type(palette) == dict: # if palette is the dict with different palette = palette[max(palette.keys())] if len(palette) == 0: return img rectWidth = width / float(len(palette)) for i, col in enumerate(palette): p.setBrush(QBrush(QColor(*col))) p.drawRect(QRectF(i * rectWidth, 0, (i + 1) * rectWidth, height)) return img
def shadowTemplatePixmap(color, length): """ Returns 1 pixel wide, `length` pixels long linear-gradient. Args: color (QColor): shadow color length (int): length of cast shadow """ key = "InnerShadowTemplate " + \ color.name() + " " + \ str(length) # get cached template shadowPixmap = QPixmapCache.find(key) if shadowPixmap: return shadowPixmap shadowPixmap = QPixmap(1, length) shadowPixmap.fill(Qt.transparent) grad = QLinearGradient(0, 0, 0, length) grad.setColorAt(0, color) grad.setColorAt(1, Qt.transparent) painter = QPainter() painter.begin(shadowPixmap) painter.fillRect(shadowPixmap.rect(), grad) painter.end() # cache template QPixmapCache.insert(key, shadowPixmap) return shadowPixmap
def export(self, filename=None): pw = QPdfWriter(filename) dpi = int(QApplication.primaryScreen().logicalDotsPerInch()) pw.setResolution(dpi) pw.setPageMargins(QMarginsF(0, 0, 0, 0)) pw.setPageSize( QPageSize( QSizeF(self.getTargetRect().size()) / dpi * 25.4, QPageSize.Millimeter)) painter = QPainter(pw) try: self.setExportMode( True, { 'antialias': True, 'background': self.background, 'painter': painter }) painter.setRenderHint(QPainter.Antialiasing, True) if QtCore.QT_VERSION >= 0x050D00: painter.setRenderHint(QPainter.LosslessImageRendering, True) self.getScene().render(painter, QRectF(self.getTargetRect()), QRectF(self.getSourceRect())) finally: self.setExportMode(False) painter.end()
def paintEvent(self, event): opt = QStyleOption() opt.initFrom(self) if not self.__popupicon.isVisible(): return if not (opt.state & QStyle.State_MouseOver or opt.state & QStyle.State_HasFocus): return palette = opt.palette # type: QPalette if opt.state & QStyle.State_HasFocus: pen = QPen(palette.color(QPalette.Highlight)) else: pen = QPen(palette.color(QPalette.Dark)) if (self.__fulltext and opt.state & QStyle.State_MouseOver and opt.state & QStyle.State_Active): g = QLinearGradient() g.setCoordinateMode(QLinearGradient.ObjectBoundingMode) base = palette.color(QPalette.Window) base.setAlpha(90) g.setColorAt(0, base.lighter(200)) g.setColorAt(0.6, base) g.setColorAt(1.0, base.lighter(200)) brush = QBrush(g) else: brush = QBrush(Qt.NoBrush) p = QPainter(self) p.setBrush(brush) p.setPen(pen) p.drawRect(opt.rect.adjusted(0, 0, -1, -1))
def grab_svg(scene): # type: (QGraphicsScene) -> str """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ 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.setPen(Qt.NoPen) painter.setBrush(scene.palette().base()) painter.drawRect(target_rect) # Render the scene scene.render(painter, target_rect, source_rect) painter.end() buffer_str = bytes(svg_buffer.buffer()) return buffer_str.decode("utf-8")
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 send_report(self): from AnyQt.QtSvg import QSvgGenerator if self.model: self.reportSection("Tree") _, 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 paintEvent(self, event): # type: (QPaintEvent) -> None if self.__flat: opt = QStyleOptionToolButton() self.initStyleOption(opt) p = QStylePainter(self) p.drawControl(QStyle.CE_ToolButtonLabel, opt) p.end() else: super().paintEvent(event) # paint shadow shadow = innerShadowPixmap(self.__shadowColor, self.size(), self.__shadowPosition, length=self.__shadowLength) p = QPainter(self) rect = self.rect() targetRect = QRect(rect.left() + 1, rect.top() + 1, rect.width() - 2, rect.height() - 2) p.drawPixmap(targetRect, shadow, shadow.rect()) p.end()
def StyledWidget_paintEvent(self, event): """A default styled QWidget subclass paintEvent function. """ opt = QStyleOption() opt.initFrom(self) painter = QPainter(self) self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)
def test_delegate(self): model = DistanceMatrixModel() matrix = np.array([[0.0, 0.1, 0.2], [0.1, 0.0, 0.1], [0.2, 0.1, 0.0]]) model.set_data(matrix) delegate = TableBorderItem() for row, col in product(range(model.rowCount()), range(model.columnCount())): index = model.index(row, col) option = QStyleOptionViewItem() size = delegate.sizeHint(option, index).expandedTo(QSize(30, 18)) delegate.initStyleOption(option, index) img = QImage(size, QImage.Format_ARGB32_Premultiplied) painter = QPainter(img) try: delegate.paint(painter, option, index) finally: painter.end()
def paint( self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex ) -> None: opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = option.widget style = QApplication.style() if widget is None else widget.style() self.__style = style text = opt.text opt.text = "" style.drawControl(QStyle.CE_ItemViewItem, opt, painter, widget) textrect = style.subElementRect( QStyle.SE_ItemViewItemText, opt, widget) ratio = self.barFillRatioData(index) if ratio is not None and 0. <= ratio <= 1.: color = self.barColorData(index) if color is None: color = self.color if not color.isValid(): color = opt.palette.color(QPalette.Foreground) rect = option.rect pw = self.penWidth hmargin = 3 + pw / 2 # + half pen width for the round line cap vmargin = 1 textoffset = pw + vmargin * 2 baseline = rect.bottom() - textoffset / 2 width = (rect.width() - 2 * hmargin) * ratio painter.save() painter.setRenderHint(QPainter.Antialiasing) pen = self.__pen pen.setColor(color) pen.setWidth(pw) painter.setPen(pen) line = self.__line left = rect.left() + hmargin line.setLine(left, baseline, left + width, baseline) painter.drawLine(line) painter.restore() textrect.adjust(0, 0, 0, -textoffset) opt.text = text self.drawViewItemText(style, painter, opt, textrect)
def paintEvent(self, event): opt = QStyleOption() opt.initFrom(self) if not self.__popupicon.isVisible(): return if not (opt.state & QStyle.State_MouseOver or opt.state & QStyle.State_HasFocus): return palette = opt.palette # type: QPalette if opt.state & QStyle.State_HasFocus: pen = QPen(palette.color(QPalette.Highlight)) else: pen = QPen(palette.color(QPalette.Dark)) if self.__fulltext and \ opt.state & QStyle.State_MouseOver and \ opt.state & QStyle.State_Active: g = QLinearGradient() g.setCoordinateMode(QLinearGradient.ObjectBoundingMode) base = palette.color(QPalette.Window) base.setAlpha(90) g.setColorAt(0, base.lighter(200)) g.setColorAt(0.6, base) g.setColorAt(1.0, base.lighter(200)) brush = QBrush(g) else: brush = QBrush(Qt.NoBrush) p = QPainter(self) p.setBrush(brush) p.setPen(pen) p.drawRect(opt.rect.adjusted(0, 0, -1, -1))
def paint_with_data( delegate: QAbstractItemDelegate, data: Dict[int, Any], options: QStyleOptionViewItem = None ) -> None: model = create_model(1, 1) index = model.index(0, 0) model.setItemData(index, data) opt = QStyleOptionViewItem(options) if options is not None else QStyleOptionViewItem() size = delegate.sizeHint(opt, index).expandedTo(QSize(10, 10)) opt.rect = QRect(QPoint(0, 0), size) delegate.initStyleOption(opt, index) img = QImage(opt.rect.size(), QImage.Format_ARGB32_Premultiplied) p = QPainter(img) try: delegate.paint(p, opt, index) finally: p.end()
def __paint(self): picture = QPicture() painter = QPainter(picture) pen = QPen(QBrush(Qt.white), 0.5) pen.setCosmetic(True) painter.setPen(pen) geom = self.geometry x, y = geom.x(), geom.y() w, h = geom.width(), geom.height() wsingle = w / len(self.dist) for d, c in zip(self.dist, self.colors): painter.setBrush(QBrush(c)) painter.drawRect(QRectF(x, y, wsingle, d * h)) x += wsingle painter.end() self.__picture = picture
def qmacstyle_accent_color(style: QStyle): option = QStyleOptionButton() option.state |= (QStyle.State_Active | QStyle.State_Enabled | QStyle.State_Raised) option.features |= QStyleOptionButton.DefaultButton option.text = "" size = style.sizeFromContents(QStyle.CT_PushButton, option, QSize(20, 10), None) option.rect = QRect(0, 0, size.width(), size.height()) img = QImage(size.width(), size.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.transparent) painter = QPainter(img) try: style.drawControl(QStyle.CE_PushButton, option, painter, None) finally: painter.end() color = img.pixelColor(size.width() // 2, size.height() // 2) return color
def paintEvent(self, event): style = self.style() # type: QStyle painter = QPainter(self) option = QStyleOption() option.initFrom(self) style.drawPrimitive(QStyle.PE_Widget, option, painter, self) option = QStyleOptionViewItem() self.initStyleOption(option) style.drawControl(QStyle.CE_ItemViewItem, option, painter, self)
def render_drop_shadow_frame(pixmap, shadow_rect, shadow_color, offset, radius, rect_fill_color): pixmap.fill(QColor(0, 0, 0, 0)) scene = QGraphicsScene() rect = QGraphicsRectItem(shadow_rect) rect.setBrush(QColor(rect_fill_color)) rect.setPen(QPen(Qt.NoPen)) scene.addItem(rect) effect = QGraphicsDropShadowEffect(color=shadow_color, blurRadius=radius, offset=offset) rect.setGraphicsEffect(effect) scene.setSceneRect(QRectF(QPointF(0, 0), QSizeF(pixmap.size()))) painter = QPainter(pixmap) scene.render(painter) painter.end() scene.clear() scene.deleteLater() return pixmap
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: Optional[QWidget] = None) -> None: if self.__pixmap.isNull(): return pixmap = self.__pixmap crect = self.contentsRect() exposed = option.exposedRect exposedcrect = crect.intersected(exposed) pixmaptransform = self.pixmapTransform() # map exposed rect to exposed pixmap coords assert pixmaptransform.type() <= QTransform.TxRotate pixmaptransform, ok = pixmaptransform.inverted() if not ok: painter.drawPixmap(crect, pixmap, QRectF(QPointF(0, 0), QSizeF(pixmap.size()))) else: exposedpixmap = pixmaptransform.mapRect(exposed) painter.drawPixmap(exposedcrect, pixmap, exposedpixmap)
def export(self, filename=None): from AnyQt.QtGui import QPdfWriter pw = QPdfWriter(filename) dpi = QDesktopWidget().logicalDpiX() pw.setResolution(dpi) pw.setPageMargins(QMarginsF(0, 0, 0, 0)) pw.setPageSizeMM(QSizeF(self.getTargetRect().size()) / dpi * 25.4) painter = QPainter(pw) try: self.setExportMode(True, {'antialias': True, 'background': self.background, 'painter': painter}) painter.setRenderHint(QPainter.Antialiasing, True) self.getScene().render(painter, QRectF(self.getTargetRect()), QRectF(self.getSourceRect())) finally: self.setExportMode(False) painter.end()
def render_as_png(self, filename): png = self.__transparent_png() painter = QPainter(png) painter.setRenderHint(QPainter.Antialiasing, 1) self.scene.render(painter, QRectF(0, 0, 50, 50), QRectF(-25, -25, 50, 50)) painter.end() png.save(filename)
def paintEvent(self, event): if self.__pixmap.isNull(): return sourcerect = QRect(QPoint(0, 0), self.__pixmap.size()) pixsize = QSizeF(self.__pixmap.size()) rect = self.contentsRect() pixsize.scale(QSizeF(rect.size()), Qt.KeepAspectRatio) targetrect = QRectF(QPointF(0, 0), pixsize) targetrect.moveCenter(QPointF(rect.center())) painter = QPainter(self) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.drawPixmap(targetrect, self.__pixmap, QRectF(sourcerect)) painter.end()
def createContPalettePixmap(width, height, color1, color2, passThroughBlack): p = QPainter() img = QPixmap(width, height) p.begin(img) #p.eraseRect(0, 0, w, h) p.setPen(QPen(Qt.NoPen)) g = QLinearGradient(0, 0, width, height) g.setColorAt(0, color1) g.setColorAt(1, color2) if passThroughBlack: g.setColorAt(0.5, Qt.black) p.fillRect(img.rect(), QBrush(g)) return img
def drawViewItemText(self, style: QStyle, painter: QPainter, option: QStyleOptionViewItem, rect: QRect) -> None: """ Draw view item text in `rect` using `style` and `painter`. """ margin = style.pixelMetric(QStyle.PM_FocusFrameHMargin, None, option.widget) + 1 rect = rect.adjusted(margin, 0, -margin, 0) font = option.font st = self.__static_text_elided_cache(option.text, font, option.fontMetrics, option.textElideMode, rect.width()) tsize = st.size() textalign = int(option.displayAlignment) text_pos_x = text_pos_y = 0.0 if textalign & _Qt_AlignLeft: text_pos_x = rect.left() elif textalign & _Qt_AlignRight: text_pos_x = rect.x() + rect.width() - tsize.width() elif textalign & _Qt_AlignHCenter: text_pos_x = rect.x() + rect.width() / 2 - tsize.width() / 2 if textalign & _Qt_AlignVCenter: text_pos_y = rect.y() + rect.height() / 2 - tsize.height() / 2 elif textalign & _Qt_AlignTop: text_pos_y = rect.top() elif textalign & _Qt_AlignBottom: text_pos_y = rect.top() + rect.height() - tsize.height() painter.setPen(self.__pen_cache(option.palette, option.state)) painter.setFont(font) painter.drawStaticText(QPointF(text_pos_x, text_pos_y), st)
def test(self): img = QImage(100, 100, QImage.Format_ARGB32) img.fill(Qt.green) p = QPainter(img) pix = QPixmap(10, 10) pix.fill(Qt.red) frgmts = [ QPainter.PixmapFragment.create( QPointF(25, 25), QRectF(0, 0, 10, 10), 5., 5., ), QPainter.PixmapFragment.create( QPointF(75, 75), QRectF(0, 0, 10, 10), 5., 5., ) ] p.drawPixmapFragments(frgmts, pix) p.end() self.assertEqual(QColor(img.pixel(10, 10)), QColor(Qt.red)) self.assertEqual(QColor(img.pixel(80, 80)), QColor(Qt.red)) self.assertEqual(QColor(img.pixel(90, 10)), QColor(Qt.green)) self.assertEqual(QColor(img.pixel(10, 90)), QColor(Qt.green))
def createExContPalettePixmap(width, height, color1, color2, passThroughColors): p = QPainter() img = QPixmap(width, height) p.begin(img) #p.eraseRect(0, 0, w, h) p.setPen(QPen(Qt.NoPen)) g = QLinearGradient(0, 0, width, height) g.setColorAt(0, color1) g.setColorAt(1, color2) for i, color in enumerate(passThroughColors): g.setColorAt(float(i + 1) / (len(passThroughColors) + 1), color) p.fillRect(img.rect(), QBrush(g)) return img
def paintEvent(self, event): # type: (QPaintEvent) -> None # TODO: Use QPainter.drawPixmapFragments on Qt 4.7 if self.__widget is None: return opt = QStyleOption() opt.initFrom(self) radius = self.__radius offset = self.__offset pixmap = self.__shadowPixmap() pixr = pixmap.devicePixelRatio() assert pixr == self.devicePixelRatioF() shadow_rect = QRectF(opt.rect) widget_rect = QRectF(self.__widget.geometry()) widget_rect.moveTo(radius - offset.x(), radius - offset.y()) left = top = right = bottom = radius * pixr pixmap_rect = QRectF(QPointF(0, 0), QSizeF(pixmap.size())) # Shadow casting rectangle in the source pixmap. pixmap_shadow_rect = pixmap_rect.adjusted(left, top, -right, -bottom) pixmap_shadow_rect.translate(-offset.x() * pixr, -offset.y() * pixr) source_rects = self.__shadowPixmapFragments(pixmap_rect, pixmap_shadow_rect) target_rects = self.__shadowPixmapFragments(shadow_rect, widget_rect) painter = QPainter(self) for source, target in zip(source_rects, target_rects): painter.drawPixmap(target, pixmap, source) painter.end()
def paint(self, painter: QPainter, option, widget): painter.setBrush(self.COLOR) painter.setPen(self.COLOR) painter.drawRect(self.boundingRect().adjusted(-self.PADDING, -self.PADDING, self.PADDING, self.PADDING)) super().paint(painter, option, widget)
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render(painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def render_as_png(self, filename): img = QImage(50, 50, QImage.Format_ARGB32) img.fill(Qt.transparent) painter = QPainter(img) painter.setRenderHint(QPainter.Antialiasing, 1) self.scene.render(painter, QRectF(0, 0, 50, 50), QRectF(-25, -25, 50, 50)) painter.end() img.save(filename)
def setHistogram(self, values=None, bins=None, use_kde=False, histogram=None): """ Set background histogram (or density estimation, violin plot) The histogram of bins is calculated from values, optionally as a Gaussian KDE. If histogram is provided, its values are used directly and other parameters are ignored. """ if (values is None or not len(values)) and histogram is None: self.setPixmap(None) return if histogram is not None: self._histogram = hist = histogram else: if bins is None: bins = min(100, max(10, len(values) // 20)) if use_kde: hist = gaussian_kde(values, None if isinstance(use_kde, bool) else use_kde)( np.linspace(np.min(values), np.max(values), bins)) else: hist = np.histogram(values, bins)[0] self._histogram = hist = hist / hist.max() HEIGHT = self.rect().height() / 2 OFFSET = HEIGHT * .3 pixmap = QPixmap(QSize(len(hist), 2 * (HEIGHT + OFFSET))) # +1 avoids right/bottom frame border shadow pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setPen(QPen(Qt.darkGray)) for x, value in enumerate(hist): painter.drawLine(x, HEIGHT * (1 - value) + OFFSET, x, HEIGHT * (1 + value) + OFFSET) if self.orientation() != Qt.Horizontal: pixmap = pixmap.transformed(QTransform().rotate(-90)) self.setPixmap(pixmap)
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render( painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def paintEvent(self, event): # TODO: Use QPainter.drawPixmapFragments on Qt 4.7 opt = QStyleOption() opt.initFrom(self) pixmap = self.__shadowPixmap shadow_rect = QRectF(opt.rect) widget_rect = QRectF(self.widget().geometry()) widget_rect.moveTo(self.radius_, self.radius_) left = top = right = bottom = self.radius_ pixmap_rect = QRectF(QPointF(0, 0), QSizeF(pixmap.size())) # Shadow casting rectangle in the source pixmap. pixmap_shadow_rect = pixmap_rect.adjusted(left, top, -right, -bottom) source_rects = self.__shadowPixmapFragments(pixmap_rect, pixmap_shadow_rect) target_rects = self.__shadowPixmapFragments(shadow_rect, widget_rect) painter = QPainter(self) for source, target in zip(source_rects, target_rects): painter.drawPixmap(target, pixmap, source) painter.end()
def grab_svg(scene): """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ from AnyQt.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 = bytes(svg_buffer.buffer()) return buffer_str.decode("utf-8")
def __startInternalDrag(self, frame, hotSpot=None): drag = QDrag(self) pixmap = QPixmap(frame.size()) frame.render(pixmap) transparent = QPixmap(pixmap.size()) transparent.fill(Qt.transparent) painter = QPainter(transparent) painter.setOpacity(0.35) painter.drawPixmap(0, 0, pixmap.width(), pixmap.height(), pixmap) painter.end() drag.setPixmap(transparent) if hotSpot is not None: drag.setHotSpot(hotSpot) mime = QMimeData() mime.setData("application/x-internal-move", b"") drag.setMimeData(mime) return drag.exec_(Qt.MoveAction)
def crosshairs(color, radius=24, circle=False): radius = max(radius, 16) pixmap = QPixmap(radius, radius) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHints(QPainter.Antialiasing) pen = QPen(QBrush(color), 1) pen.setWidthF(1.5) painter.setPen(pen) if circle: painter.drawEllipse(2, 2, radius - 2, radius - 2) painter.drawLine(radius / 2, 7, radius / 2, radius / 2 - 7) painter.drawLine(7, radius / 2, radius / 2 - 7, radius / 2) painter.end() return pixmap
def decorate_welcome_icon(icon, background_color): """Return a `QIcon` with a circle shaped background. """ welcome_icon = QIcon() sizes = [32, 48, 64, 80, 128, 256] background_color = NAMED_COLORS.get(background_color, background_color) background_color = QColor(background_color) grad = radial_gradient(background_color) for size in sizes: icon_size = QSize(5 * size / 8, 5 * size / 8) icon_rect = QRect(QPoint(0, 0), icon_size) pixmap = QPixmap(size, size) pixmap.fill(Qt.transparent) 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()) icon.paint(p, icon_rect, Qt.AlignCenter, ) p.end() welcome_icon.addPixmap(pixmap) return welcome_icon
def __init__(self, parent=None): super().__init__(parent, Qt.CustomizeWindowHint | Qt.FramelessWindowHint | Qt.Window | Qt.WindowStaysOnTopHint | Qt.X11BypassWindowManagerHint) self.setAttribute(Qt.WA_DeleteOnClose) self.installEventFilter(self) self.setMouseTracking(True) self._band = QRubberBand(QRubberBand.Rectangle, self) self._resize_origin = None self._drag_mask = 0 self._origin = None self.selected_image = None # Window background desktop = QApplication.desktop() if is_qt5(): g = desktop.geometry() self._snapshot = QPixmap(g.width(), g.height()) painter = QPainter(self._snapshot) for screen in QApplication.screens(): g = screen.geometry() painter.drawPixmap(g, screen.grabWindow(0, g.x(), g.y(), g.width(), g.height())) painter.end() else: self._snapshot = QPixmap.grabWindow(desktop.winId(), 0, 0, desktop.width(), desktop.height()) self.setGeometry(desktop.geometry()) self._darken = self._snapshot.copy() painter = QPainter(self._darken) brush = QBrush(QColor(0, 0, 0, 128)) painter.setBrush(brush) painter.drawRect(self._darken.rect()) painter.end() # Buttons self._buttons = QWidget(self) self._button_layout = QHBoxLayout(self._buttons) self._button_layout.setSpacing(0) self._button_layout.setContentsMargins(0, 0, 0, 0) self._button_layout.setContentsMargins(0, 0, 0, 0) self.save_as = QPushButton(self.tr('Save As')) self.save_as.pressed.connect(self.save_image_as) self.save_as.setCursor(Qt.ArrowCursor) self._button_layout.addWidget(self.save_as) self.copy = QPushButton(self.tr('Copy')) self.copy.pressed.connect(self.copy_to_clipboard) self.copy.setCursor(Qt.ArrowCursor) self._button_layout.addWidget(self.copy) self.share = QPushButton(self.tr('Share')) self.share.pressed.connect(self.share_selection) self.share.setCursor(Qt.ArrowCursor) self._button_layout.addWidget(self.share) self._buttons.hide()
def splash_screen(): # type: () -> Tuple[QPixmap, QRect] """ Return a splash screen pixmap and an text area within it. The text area is used for displaying text messages during application startup. The default implementation returns a bland rectangle splash screen. Returns ------- t : Tuple[QPixmap, QRect] A QPixmap and a rect area within it. """ path = pkg_resources.resource_filename( __name__, "icons/orange-canvas-core-splash.svg") pm = QPixmap(path) version = QCoreApplication.applicationVersion() if version: version_parsed = LooseVersion(version) version_comp = version_parsed.version version = ".".join(map(str, version_comp[:2])) size = 21 if len(version) < 5 else 16 font = QFont() 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.moveBottomRight(QPoint(pm.width() - 15, pm.height() - 15)) 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() textarea = QRect(15, 15, 170, 20) return pm, textarea
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 paintEvent(self, event): """ Paint the interpolated pixmap image. """ p = QPainter(self) p.setClipRect(event.rect()) factor = self.blendingFactor_ ** 2 if self.pixmap1 and 1. - factor: p.setOpacity(1. - factor) p.drawPixmap(QPoint(0, 0), self.pixmap1) if self.pixmap2 and factor: p.setOpacity(factor) p.drawPixmap(QPoint(0, 0), self.pixmap2)
def paintEvent(self, event): if self.__isTransparencySupported: opt = QStyleOption() opt.initFrom(self) rect = opt.rect p = QPainter(self) p.setRenderHint(QPainter.Antialiasing, True) p.setBrush(opt.palette.brush(QPalette.Window)) p.setPen(Qt.NoPen) p.drawRoundedRect(rect, self.__radius, self.__radius) p.end() else: StyledWidget_paintEvent(self, event)
def redraw_markers_overlay_image(self, *args, new_image=False): if not args and not self._drawing_args or self.data is None: return if args: self._drawing_args = args north, east, south, west, width, height, zoom, origin, map_pane_pos = self._drawing_args lat, lon = self._latlon_data.T visible = ((lat <= north) & (lat >= south) & (lon <= east) & (lon >= west)).nonzero()[0] in_subset = (np.in1d(self.data.ids, self._subset_ids) if self._subset_ids.size else np.tile(True, len(lon))) is_js_path = self.is_js_path = len(visible) < self.N_POINTS_PER_ITER self._update_legend(is_js_path) np.random.shuffle(visible) # Sort points in subset to be painted last visible = visible[np.lexsort((in_subset[visible],))] if is_js_path: self.evalJS('clear_markers_overlay_image()') self._update_js_markers(visible, in_subset[visible]) self._owwidget.disable_some_controls(False) return self.evalJS('clear_markers_js();') self._owwidget.disable_some_controls(True) selected = (self._selected_indices if self._selected_indices is not None else np.zeros(len(lat), dtype=bool)) cur = 0 im = QImage(self._overlay_image_path) if im.isNull() or self._prev_origin != origin or new_image: im = QImage(width, height, QImage.Format_ARGB32) im.fill(Qt.transparent) else: dx, dy = self._prev_map_pane_pos - map_pane_pos im = im.copy(dx, dy, width, height) self._prev_map_pane_pos = np.array(map_pane_pos) self._prev_origin = origin painter = QPainter(im) painter.setRenderHint(QPainter.Antialiasing, True) self.evalJS('clear_markers_overlay_image(); markersImageLayer.setBounds(map.getBounds());0') self._image_token = image_token = np.random.random() n_iters = np.ceil(len(visible) / self.N_POINTS_PER_ITER) def add_points(): nonlocal cur, image_token if image_token != self._image_token: return batch = visible[cur:cur + self.N_POINTS_PER_ITER] batch_lat = lat[batch] batch_lon = lon[batch] x, y = self.Projection.latlon_to_easting_northing(batch_lat, batch_lon) x, y = self.Projection.easting_northing_to_pixel(x, y, zoom, origin, map_pane_pos) if self._jittering: dx, dy = self._jittering_offsets[batch].T x, y = x + dx, y + dy colors = (self._colorgen.getRGB(self._scaled_color_values[batch]).tolist() if self._color_attr else repeat((0xff, 0, 0))) sizes = self._size_coef * \ (self._sizes[batch] if self._size_attr else np.tile(10, len(batch))) opacity_subset, opacity_rest = self._opacity, int(.8 * self._opacity) for x, y, is_selected, size, color, _in_subset in \ zip(x, y, selected[batch], sizes, colors, in_subset[batch]): pensize2, selpensize2 = (.35, 1.5) if size >= 5 else (.15, .7) pensize2 *= self._size_coef selpensize2 *= self._size_coef size2 = size / 2 if is_selected: painter.setPen(QPen(QBrush(Qt.green), 2 * selpensize2)) painter.drawEllipse(x - size2 - selpensize2, y - size2 - selpensize2, size + selpensize2, size + selpensize2) color = QColor(*color) if _in_subset: color.setAlpha(opacity_subset) painter.setBrush(QBrush(color)) painter.setPen(QPen(QBrush(color.darker(180)), 2 * pensize2)) else: color.setAlpha(opacity_rest) painter.setBrush(Qt.NoBrush) painter.setPen(QPen(QBrush(color.lighter(120)), 2 * pensize2)) painter.drawEllipse(x - size2 - pensize2, y - size2 - pensize2, size + pensize2, size + pensize2) im.save(self._overlay_image_path, 'PNG') self.evalJS('markersImageLayer.setUrl("{}#{}"); 0;' .format(self.toFileURL(self._overlay_image_path), np.random.random())) cur += self.N_POINTS_PER_ITER if cur < len(visible): QTimer.singleShot(10, add_points) self._owwidget.progressBarAdvance(100 / n_iters, None) else: self._owwidget.progressBarFinished(None) self._image_token = None self._owwidget.progressBarFinished(None) self._owwidget.progressBarInit(None) QTimer.singleShot(10, add_points)
def __paintEventNoStyle(self): p = QPainter(self) opt = QStyleOptionToolButton() self.initStyleOption(opt) fm = QFontMetrics(opt.font) palette = opt.palette # highlight brush is used as the background for the icon and background # when the tab is expanded and as mouse hover color (lighter). brush_highlight = palette.highlight() foregroundrole = QPalette.ButtonText if opt.state & QStyle.State_Sunken: # State 'down' pressed during a mouse press (slightly darker). background_brush = brush_darker(brush_highlight, 110) foregroundrole = QPalette.HighlightedText elif opt.state & QStyle.State_MouseOver: background_brush = brush_darker(brush_highlight, 95) foregroundrole = QPalette.HighlightedText elif opt.state & QStyle.State_On: background_brush = brush_highlight foregroundrole = QPalette.HighlightedText else: # The default button brush. background_brush = palette.button() rect = opt.rect icon_area_rect = QRect(rect) icon_area_rect.setRight(int(icon_area_rect.height() * 1.26)) text_rect = QRect(rect) text_rect.setLeft(icon_area_rect.right() + 10) # Background (TODO: Should the tab button have native # toolbutton shape, drawn using PE_PanelButtonTool or even # QToolBox tab shape) # Default outline pen pen = QPen(palette.color(QPalette.Mid)) p.save() p.setPen(Qt.NoPen) p.setBrush(QBrush(background_brush)) p.drawRect(rect) # Draw the background behind the icon if the background_brush # is different. if not opt.state & QStyle.State_On: p.setBrush(brush_highlight) p.drawRect(icon_area_rect) # Line between the icon and text p.setPen(pen) p.drawLine(icon_area_rect.topRight(), icon_area_rect.bottomRight()) if opt.state & QStyle.State_HasFocus: # Set the focus frame pen and draw the border pen = QPen(QColor(FOCUS_OUTLINE_COLOR)) p.setPen(pen) p.setBrush(Qt.NoBrush) # Adjust for pen rect = rect.adjusted(0, 0, -1, -1) p.drawRect(rect) else: p.setPen(pen) # Draw the top/bottom border if self.position == QStyleOptionToolBox.OnlyOneTab or \ self.position == QStyleOptionToolBox.Beginning or \ self.selected & \ QStyleOptionToolBox.PreviousIsSelected: p.drawLine(rect.topLeft(), rect.topRight()) p.drawLine(rect.bottomLeft(), rect.bottomRight()) p.restore() p.save() text = fm.elidedText(opt.text, Qt.ElideRight, text_rect.width()) p.setPen(QPen(palette.color(foregroundrole))) p.setFont(opt.font) p.drawText(text_rect, int(Qt.AlignVCenter | Qt.AlignLeft) | \ int(Qt.TextSingleLine), text) if not opt.icon.isNull(): if opt.state & QStyle.State_Enabled: mode = QIcon.Normal else: mode = QIcon.Disabled if opt.state & QStyle.State_On: state = QIcon.On else: state = QIcon.Off icon_area_rect = icon_area_rect icon_rect = QRect(QPoint(0, 0), opt.iconSize) icon_rect.moveCenter(icon_area_rect.center()) opt.icon.paint(p, icon_rect, Qt.AlignCenter, mode, state) p.restore()
def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self.viewport()) painter.setBrush(QColor(100, 100, 100, 100)) painter.setRenderHints(self.renderHints()) painter.drawPolygon(self.viewPolygon())