def __updatePixmap(self): """ Update the cached shadow pixmap. """ rect_size = QSize(50, 50) left = top = right = bottom = self.radius_ # Size of the pixmap. pixmap_size = QSize(rect_size.width() + left + right, rect_size.height() + top + bottom) shadow_rect = QRect(QPoint(left, top), rect_size) pixmap = QPixmap(pixmap_size) pixmap.fill(QColor(0, 0, 0, 0)) rect_fill_color = self.palette().color(QPalette.Window) pixmap = render_drop_shadow_frame( pixmap, QRectF(shadow_rect), shadow_color=self.color_, offset=QPointF(0, 0), radius=self.radius_, rect_fill_color=rect_fill_color, ) self.__shadowPixmap = pixmap self.update()
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 __init__(self, widget, parent=None, name=None): OWPlot.__init__(self, parent, name, axes=[], widget=widget) ScaleData.__init__(self) self.update_antialiasing(False) self.widget = widget self.last_selected_curve = None self.enableGridXB(0) self.enableGridYL(0) self.domain_contingencies = None self.auto_update_axes = 1 self.old_legend_keys = [] self.selection_conditions = {} self.attributes = [] self.visualized_mid_labels = [] self.attribute_indices = [] self.valid_data = [] self.groups = {} self.colors = None self.selected_examples = [] self.unselected_examples = [] self.bottom_pixmap = QPixmap(gui.resource_filename("icons/upgreenarrow.png")) self.top_pixmap = QPixmap(gui.resource_filename("icons/downgreenarrow.png"))
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 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 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 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 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 decorate_welcome_icon(icon, background_color): # type: (QIcon, Union[QColor, str]) -> QIcon """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(int(5 * size / 8), int(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 __updatePixmap(self): """ Update the cached shadow pixmap. """ rect_size = QSize(50, 50) left = top = right = bottom = self.radius_ # Size of the pixmap. pixmap_size = QSize(rect_size.width() + left + right, rect_size.height() + top + bottom) shadow_rect = QRect(QPoint(left, top), rect_size) pixmap = QPixmap(pixmap_size) pixmap.fill(QColor(0, 0, 0, 0)) rect_fill_color = self.palette().color(QPalette.Window) pixmap = render_drop_shadow_frame( pixmap, QRectF(shadow_rect), shadow_color=self.color_, offset=QPointF(0, 0), radius=self.radius_, rect_fill_color=rect_fill_color ) self.__shadowPixmap = pixmap self.update()
def __init__(self, widget, parent=None, name=None): OWPlot.__init__(self, parent, name, axes=[], widget=widget) ScaleData.__init__(self) self.update_antialiasing(False) self.widget = widget self.last_selected_curve = None self.enableGridXB(0) self.enableGridYL(0) self.domain_contingencies = None self.auto_update_axes = 1 self.old_legend_keys = [] self.selection_conditions = {} self.attributes = [] self.visualized_mid_labels = [] self.attribute_indices = [] self.valid_data = [] self.groups = {} self.colors = None self.selected_examples = [] self.unselected_examples = [] self.bottom_pixmap = QPixmap( gui.resource_filename("icons/upgreenarrow.png")) self.top_pixmap = QPixmap( gui.resource_filename("icons/downgreenarrow.png"))
def __init__(self, pixmap=None, parent=None): super().__init__(parent) self.setCacheMode(QGraphicsItem.ItemCoordinateCache) self._pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap() self._keepAspect = True self._crop = False self._subset = True self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pixmap = QPixmap() # Flag indicating if the widget was resized as a result of user # initiated window resize. When false the widget will automatically # resize/re-position based on pixmap size. self.__hasExplicitSize = False self.__inUpdateWindowGeometry = False
class GraphicsPixmapWidget(QGraphicsWidget): """ A QGraphicsWidget displaying a QPixmap """ def __init__(self, pixmap=None, parent=None): super().__init__(parent) self.setCacheMode(QGraphicsItem.ItemCoordinateCache) self._pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap() self._keepAspect = True self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) def setPixmap(self, pixmap): self._pixmap = QPixmap(pixmap) self.updateGeometry() self.update() def pixmap(self): return QPixmap(self._pixmap) def setKeepAspectRatio(self, keep): if self._keepAspect != keep: self._keepAspect = bool(keep) self.update() def keepAspectRatio(self): return self._keepAspect def setGeometry(self, rect): self.prepareGeometryChange() super().setGeometry(rect) def sizeHint(self, which, constraint=QSizeF()): if which == Qt.PreferredSize: return QSizeF(self._pixmap.size()) else: return QGraphicsWidget.sizeHint(self, which, constraint) def paint(self, painter, option, widget=0): if self._pixmap.isNull(): return rect = self.contentsRect() pixsize = QSizeF(self._pixmap.size()) aspectmode = (Qt.KeepAspectRatio if self._keepAspect else Qt.IgnoreAspectRatio) pixsize.scale(rect.size(), aspectmode) pixrect = QRectF(QPointF(0, 0), pixsize) pixrect.moveCenter(rect.center()) painter.save() painter.setPen(QPen(QColor(0, 0, 0, 50), 3)) painter.drawRoundedRect(pixrect, 2, 2) painter.setRenderHint(QPainter.SmoothPixmapTransform) source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size())) painter.drawPixmap(pixrect, self._pixmap, source) painter.restore()
def setPathway(self, pathway): """ Set pathway """ self.pathway = pathway if pathway: image_filename = pathway.get_image() self._pixmap = QPixmap(image_filename) else: self._pixmap = QPixmap() self.setPixmap(self._pixmap)
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 __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 __init__(self, parent: Optional[QGraphicsItem] = None, pixmap: Optional[QPixmap] = None, scaleContents=False, aspectMode=Qt.KeepAspectRatio, **kwargs) -> None: self.__scaleContents = scaleContents self.__aspectMode = aspectMode self.__pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap() super().__init__(None, **kwargs) self.setFlag(QGraphicsWidget.ItemUsesExtendedStyleOption, True) self.setContentsMargins(0, 0, 0, 0) if parent is not None: self.setParentItem(parent)
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 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 update_legend(self, colors, labels): layout = self.legend.layout() while self.legend_items: w = self.legend_items.pop() layout.removeWidget(w) w.deleteLater() for row, (color, label) in enumerate(zip(colors, labels)): icon = QLabel() p = QPixmap(12, 12) p.fill(color) icon.setPixmap(p) label = QLabel(label) layout.addWidget(icon, row, 0) layout.addWidget(label, row, 1, alignment=Qt.AlignLeft) self.legend_items += (icon, label)
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 splash_screen(): splash_n = random.randint(1, 3) path = pkg_resources.resource_filename( __name__, f"icons/orange-splash-screen-{splash_n:02}.png") pm = QPixmap(path) version = Config.ApplicationVersion if version: version_parsed = LooseVersion(version) version_comp = version_parsed.version version = ".".join(map(str, version_comp[:2])) size = 13 font = QFont("Helvetica") font.setPixelSize(size) metrics = QFontMetrics(font) br = metrics.boundingRect(version) br.moveTopLeft(QPoint(171, 438)) p = QPainter(pm) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setFont(font) p.setPen(QColor("#000000")) p.drawText(br, Qt.AlignLeft, version) p.end() return pm, QRect(23, 24, 200, 20)
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 init_combos(): """ function initialize the combos with attributes """ reset_combos() c_vars = [var for var in data.domain.variables if var.is_continuous] self.x_var_model[:] = c_vars self.y_var_model[:] = c_vars for i, var in enumerate(data.domain.class_var.values): pix_map = QPixmap(60, 60) color = tuple(data.domain.class_var.colors[i].tolist()) pix_map.fill(QColor(*color)) self.target_class_combobox.addItem(QIcon(pix_map), var)
def test_splashscreen(self): splash = pkg_resources.resource_filename( config.__package__, "icons/orange-canvas-core-splash.svg" ) w = SplashScreen() w.setPixmap(QPixmap(splash)) w.setTextRect(QRect(100, 100, 400, 50)) w.show() def advance_time(): now = datetime.now() time = now.strftime("%c : %f") i = now.second % 3 if i == 2: w.setTextFormat(Qt.RichText) time = "<i>" + time + "</i>" else: w.setTextFormat(Qt.PlainText) w.showMessage(time, alignment=Qt.AlignCenter) rect = QRect(100, 100 + i * 20, 400, 50) w.setTextRect(rect) self.assertEqual(w.textRect(), rect) timer = QTimer(w, interval=1) timer.timeout.connect(advance_time) timer.start() self.app.exec_()
def update_webcam_image(self): if not self.isVisible(): if self.cap is not None: self.cap.release() self.cap = None return if self.cap is None: # Try capture devices in LIFO order for dev in range(5, -1, -1): cap = self.cap = cv2.VideoCapture(dev) if cap.isOpened(): break cap = self.cap self.capture_button.setDisabled(not cap.isOpened()) success, frame = cap.read() if not cap.isOpened() or not success: self.Error.no_webcam() return else: self.Error.no_webcam.clear() if self.snapshot_flash > 0: np.clip(frame.astype(np.int16) + self.snapshot_flash, 0, 255, out=frame) self.snapshot_flash -= 15 image = QImage(frame if self.avatar_filter else self.bgr2rgb(frame), frame.shape[1], frame.shape[0], QImage.Format_RGB888) pix = QPixmap.fromImage(image).scaled( self.imageLabel.size(), Qt.KeepAspectRatio | Qt.FastTransformation) self.imageLabel.setPixmap(pix)
def set_pixmap(future, thumb=thumbnail): if future.cancelled(): return assert future.done() if future.exception(): # Should be some generic error image. pixmap = QPixmap() thumb.setToolTip(thumb.toolTip() + "\n" + str(future.exception())) else: pixmap = QPixmap.fromImage(future.result()) thumb.setPixmap(pixmap) self._noteCompleted(future)
def __shadowPixmap(self): # type: () -> QPixmap if self.__cachedShadowPixmap is None \ or self.__cachedShadowPixmap.devicePixelRatioF() \ != self.devicePixelRatioF(): self.__cachedShadowPixmap = self.__shadowPixmapForDpr( self.devicePixelRatioF()) return QPixmap(self.__cachedShadowPixmap)
def pixmap_from_image(image): # type: (QImage) -> QPixmap pixmap = QPixmap.fromImage(image) # type: QPixmap if hasattr(pixmap, "setDevicePixelRatio"): pixmap.setDevicePixelRatio(image.logicalDpiX() / 72) else: pixmap = pixmap.scaled((image.size() * 72) / image.logicalDpiX(), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def setPixmap(self, pixmap): # type: (QPixmap) -> None self.setAttribute(Qt.WA_TranslucentBackground, pixmap.hasAlpha() and is_transparency_supported()) self.__pixmap = QPixmap(pixmap) super().setPixmap(pixmap) if pixmap.hasAlpha() and not is_transparency_supported(): self.setMask(pixmap.createHeuristicMask())
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 setupScene(self): self.error() if self.data: attr = self.stringAttrs[self.smilesAttr] titleAttr = self.allAttrs[self.titleAttr] assert self.thumbnailView.count() == 0 size = QSizeF(self.imageSize, self.imageSize) for i, inst in enumerate(self.data): if not numpy.isfinite(inst[attr]): # skip missing continue smiles = str(inst[attr]) title = str(inst[titleAttr]) thumbnail = GraphicsThumbnailWidget(QPixmap(), title=title) thumbnail.setThumbnailSize(size) thumbnail.setToolTip(smiles) thumbnail.instance = inst self.thumbnailView.addThumbnail(thumbnail) if self.check_smiles(smiles): pixmap = self.pixmap_from_smiles(smiles) thumbnail.setPixmap(pixmap) self._successcount += 1 else: pixmap = QPixmap() thumbnail.setPixmap(pixmap) thumbnail.setToolTip(thumbnail.toolTip() + "\nInvalid SMILES") self._errcount += 1 future = Future() future.set_result(pixmap) future._reply = None self.items.append(_ImageItem(i, thumbnail, smiles, future)) if any(it.future is not None and not it.future.done() for it in self.items): self.info.setText("Retrieving...\n") else: self._updateStatus()
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 init_combos(): """ function initialize the combos with attributes """ reset_combos() c_vars = [var for var in d.domain.attributes if var.is_continuous] self.x_var_model[:] = c_vars self.y_var_model[:] = c_vars if self.is_logistic else [] for i, var in (enumerate(d.domain.class_var.values) if d.domain.class_var.is_discrete else []): pix_map = QPixmap(60, 60) color = tuple(d.domain.class_var.colors[i].tolist()) pix_map.fill(QColor(*color)) self.target_class_combobox.addItem(QIcon(pix_map), var) self.cby.setDisabled(not self.is_logistic) self.target_class_combobox.setDisabled(not self.is_logistic)
def _updateShadowPixmap(self): """Update the cached drop shadow pixmap. """ # Rectangle casting the shadow rect_size = QSize(*CACHED_SHADOW_RECT_SIZE) left, top, right, bottom = self.getContentsMargins() # Size of the pixmap. pixmap_size = QSize(rect_size.width() + left + right, rect_size.height() + top + bottom) shadow_rect = QRect(QPoint(left, top), rect_size) pixmap = QPixmap(pixmap_size) pixmap.fill(QColor(0, 0, 0, 0)) rect_fill_color = self.palette().color(QPalette.Window) pixmap = render_drop_shadow_frame(pixmap, QRectF(shadow_rect), shadow_color=self.color, offset=self.offset, radius=self.radius, rect_fill_color=rect_fill_color) self._shadowPixmap = pixmap
def image_data(pm): # type: (QPixmap) -> str """ Render the contents of the pixmap as a data URL (RFC-2397) Parameters ---------- pm : QPixmap Returns ------- datauri : str """ pm = QPixmap(pm) device = QBuffer() assert device.open(QBuffer.ReadWrite) pm.save(device, b'png') device.close() data = bytes(device.data()) payload = base64.b64encode(data).decode("ascii") return "data:image/png;base64," + payload
def setIcon(self, icon): """ Set the message icon. :type icon: QIcon | QPixmap | QString | QStyle.StandardPixmap """ if isinstance(icon, QStyle.StandardPixmap): icon = self.style().standardIcon(icon) else: icon = QIcon(icon) if self.__icon != icon: self.__icon = QIcon(icon) if not self.__icon.isNull(): size = self.style().pixelMetric( QStyle.PM_SmallIconSize, None, self) pm = self.__icon.pixmap(QSize(size, size)) else: pm = QPixmap() self.__iconlabel.setPixmap(pm) self.__iconlabel.setVisible(not pm.isNull())
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 update_properties(self): ## Mostly copied from OWScatterPlotGraph if not self.plot(): return if not self.rect: x,y = self.axes() self.rect = self.plot().data_rect_for_axes(x,y) s = self.graph_transform().mapRect(self.rect).size().toSize() if not s.isValid(): return rx = s.width() ry = s.height() rx -= rx % self.granularity ry -= ry % self.granularity p = self.graph_transform().map(QPointF(0, 0)) - self.graph_transform().map(self.rect.topLeft()) p = p.toPoint() ox = p.x() oy = -p.y() if self.classifier.classVar.is_continuous: imagebmp = orangeom.potentialsBitmap(self.classifier, rx, ry, ox, oy, self.granularity, self.scale) palette = [qRgb(255.*i/255., 255.*i/255., 255-(255.*i/255.)) for i in range(255)] + [qRgb(255, 255, 255)] else: imagebmp, nShades = orangeom.potentialsBitmap(self.classifier, rx, ry, ox, oy, self.granularity, self.scale, self.spacing) palette = [] sortedClasses = get_variable_values_sorted(self.classifier.domain.classVar) for cls in self.classifier.classVar.values: color = self.plot().discPalette.getRGB(sortedClasses.index(cls)) towhite = [255-c for c in color] for s in range(nShades): si = 1-float(s)/nShades palette.append(qRgb(*tuple([color[i]+towhite[i]*si for i in (0, 1, 2)]))) palette.extend([qRgb(255, 255, 255) for i in range(256-len(palette))]) self.potentialsImage = QImage(imagebmp, rx, ry, QImage.Format_Indexed8) self.potentialsImage.setColorTable(palette) self.potentialsImage.setNumColors(256) self.pixmap_item.setPixmap(QPixmap.fromImage(self.potentialsImage)) self.pixmap_item.setPos(self.graph_transform().map(self.rect.bottomLeft()))
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)
class OWParallelGraph(OWPlot, ScaleData): show_distributions = Setting(False) show_attr_values = Setting(True) show_statistics = Setting(default=False) group_lines = Setting(default=False) number_of_groups = Setting(default=5) number_of_steps = Setting(default=30) use_splines = Setting(False) alpha_value = Setting(150) alpha_value_2 = Setting(150) def __init__(self, widget, parent=None, name=None): OWPlot.__init__(self, parent, name, axes=[], widget=widget) ScaleData.__init__(self) self.update_antialiasing(False) self.widget = widget self.last_selected_curve = None self.enableGridXB(0) self.enableGridYL(0) self.domain_contingencies = None self.auto_update_axes = 1 self.old_legend_keys = [] self.selection_conditions = {} self.attributes = [] self.visualized_mid_labels = [] self.attribute_indices = [] self.valid_data = [] self.groups = {} self.colors = None self.selected_examples = [] self.unselected_examples = [] self.bottom_pixmap = QPixmap(gui.resource_filename("icons/upgreenarrow.png")) self.top_pixmap = QPixmap(gui.resource_filename("icons/downgreenarrow.png")) def set_data(self, data, subset_data=None, **args): self.start_progress() self.set_progress(1, 100) self.data = data self.have_data = True self.domain_contingencies = None self.groups = {} OWPlot.setData(self, data) ScaleData.set_data(self, data, no_data=True, **args) self._compute_domain_data_stat() self.end_progress() def update_data(self, attributes, mid_labels=None): old_selection_conditions = self.selection_conditions self.clear() if self.data is None: return if len(attributes) < 2: return if self.show_statistics: self.alpha_value = TRANSPARENT self.alpha_value_2 = VISIBLE else: self.alpha_value = VISIBLE self.alpha_value_2 = TRANSPARENT self.attributes = attributes self.attribute_indices = [self.domain.index(name) for name in self.attributes] self.valid_data = self.get_valid_list(self.attribute_indices) self.visualized_mid_labels = mid_labels self.add_relevant_selections(old_selection_conditions) class_var = self.domain.class_var if not class_var: self.colors = None elif class_var.is_discrete: self.colors = class_var.colors elif class_var.is_continuous: self.colors = ContinuousPaletteGenerator(*class_var.colors) if self.group_lines: self.show_statistics = False self.draw_groups() else: self.show_statistics = False self.draw_curves() self.draw_distributions() self.draw_axes() self.draw_statistics() self.draw_mid_labels(mid_labels) self.draw_legend() self.replot() def add_relevant_selections(self, old_selection_conditions): """Keep only conditions related to the currently visualized attributes""" for name, value in old_selection_conditions.items(): if name in self.attributes: self.selection_conditions[name] = value def draw_axes(self): self.remove_all_axes() for i in range(len(self.attributes)): axis_id = UserAxis + i a = self.add_axis(axis_id, line=QLineF(i, 0, i, 1), arrows=AxisStart | AxisEnd, zoomable=True) a.always_horizontal_text = True a.max_text_width = 100 a.title_margin = -10 a.text_margin = 0 a.setZValue(5) self.set_axis_title(axis_id, self.domain[self.attributes[i]].name) self.set_show_axis_title(axis_id, self.show_attr_values) if self.show_attr_values: attr = self.domain[self.attributes[i]] if attr.is_continuous: self.set_axis_scale(axis_id, self.attr_values[attr][0], self.attr_values[attr][1]) elif attr.is_discrete: attribute_values = get_variable_values_sorted(self.domain[self.attributes[i]]) attr_len = len(attribute_values) values = [float(1.0 + 2.0 * j) / float(2 * attr_len) for j in range(len(attribute_values))] a.set_bounds((0, 1)) self.set_axis_labels(axis_id, labels=attribute_values, values=values) def draw_curves(self): conditions = {name: self.attributes.index(name) for name in self.selection_conditions.keys()} def is_selected(example): return all(self.selection_conditions[name][0] <= example[index] <= self.selection_conditions[name][1] for (name, index) in list(conditions.items())) selected_curves = defaultdict(list) background_curves = defaultdict(list) diff, mins = [], [] for i in self.attribute_indices: var = self.domain[i] if var.is_discrete: diff.append(len(var.values)) mins.append(-0.5) else: diff.append(self.domain_data_stat[i].max - self.domain_data_stat[i].min or 1) mins.append(self.domain_data_stat[i].min) def scale_row(row): return [(x - m) / d for x, m, d in zip(row, mins, diff)] for row_idx, row in enumerate(self.data[:, self.attribute_indices]): if any(np.isnan(v) for v in row.x): continue color = tuple(self.select_color(row_idx)) if is_selected(row): color += (self.alpha_value,) selected_curves[color].extend(scale_row(row)) self.selected_examples.append(row_idx) else: color += (self.alpha_value_2,) background_curves[color].extend(row) self.unselected_examples.append(row_idx) self._draw_curves(selected_curves) self._draw_curves(background_curves) def select_color(self, row_index): domain = self.data.domain if domain.class_var is None: return 0, 0, 0 class_val = self.data[row_index, domain.index(domain.class_var)] if domain.has_continuous_class: return self.continuous_palette.getRGB(class_val) else: return self.colors[int(class_val)] def _draw_curves(self, selected_curves): n_attr = len(self.attributes) for color, y_values in sorted(selected_curves.items()): n_rows = int(len(y_values) / n_attr) x_values = list(range(n_attr)) * n_rows curve = OWCurve() curve.set_style(OWCurve.Lines) curve.set_color(QColor(*color)) curve.set_segment_length(n_attr) curve.set_data(x_values, y_values) curve.attach(self) def draw_groups(self): phis, mus, sigmas = self.compute_groups() diff, mins = [], [] for i in self.attribute_indices: var = self.domain[i] if var.is_discrete: diff.append(len(var.values)) mins.append(-0.5) else: diff.append(self.domain_data_stat[i].max - self.domain_data_stat[i].min or 1) mins.append(self.domain_data_stat[i].min) for j, (phi, cluster_mus, cluster_sigma) in enumerate(zip(phis, mus, sigmas)): for i, (mu1, sigma1, mu2, sigma2), in enumerate( zip(cluster_mus, cluster_sigma, cluster_mus[1:], cluster_sigma[1:])): nmu1 = (mu1 - mins[i]) / diff[i] nmu2 = (mu2 - mins[i + 1]) / diff[i + 1] nsigma1 = math.sqrt(sigma1) / diff[i] nsigma2 = math.sqrt(sigma2) / diff[i + 1] polygon = ParallelCoordinatePolygon(i, nmu1, nmu2, nsigma1, nsigma2, phi, tuple(self.colors[j]) if self.colors else (0, 0, 0)) polygon.attach(self) self.replot() def compute_groups(self): key = (tuple(self.attributes), self.number_of_groups, self.number_of_steps) if key not in self.groups: def callback(i, n): self.set_progress(i, 2*n) conts = create_contingencies(self.data[:, self.attribute_indices], callback=callback) self.set_progress(50, 100) w, mu, sigma, phi = lac(conts, self.number_of_groups, self.number_of_steps) self.set_progress(100, 100) self.groups[key] = list(map(np.nan_to_num, (phi, mu, sigma))) return self.groups[key] def draw_legend(self): domain = self.data.domain class_var = domain.class_var if class_var: if class_var.is_discrete: self.legend().clear() values = get_variable_values_sorted(class_var) for i, value in enumerate(values): self.legend().add_item( class_var.name, value, OWPoint(OWPoint.Rect, QColor(*self.colors[i]), 10)) else: values = self.attr_values[class_var] decimals = class_var.number_of_decimals self.legend().add_color_gradient( class_var.name, ["%%.%df" % decimals % v for v in values]) else: self.legend().clear() self.old_legend_keys = [] def draw_mid_labels(self, mid_labels): if mid_labels: for j in range(len(mid_labels)): self.addMarker(mid_labels[j], j + 0.5, 1.0, alignment=Qt.AlignCenter | Qt.AlignTop) def draw_statistics(self): """Draw lines that represent standard deviation or quartiles""" return # TODO: Implement using BasicStats if self.show_statistics and self.data is not None: data = [] domain = self.data.domain for attr_idx in self.attribute_indices: if not self.domain[attr_idx].is_continuous: data.append([()]) continue # only for continuous attributes if not domain.class_var or domain.has_continuous_class: if self.show_statistics == MEANS: m = self.domain_data_stat[attr_idx].mean dev = self.domain_data_stat[attr_idx].var data.append([(m - dev, m, m + dev)]) elif self.show_statistics == MEDIAN: data.append([(0, 0, 0)]); continue sorted_array = np.sort(attr_values) if len(sorted_array) > 0: data.append([(sorted_array[int(len(sorted_array) / 4.0)], sorted_array[int(len(sorted_array) / 2.0)], sorted_array[int(len(sorted_array) * 0.75)])]) else: data.append([(0, 0, 0)]) else: curr = [] class_values = get_variable_values_sorted(self.domain.class_var) class_index = self.domain.index(self.domain.class_var) for c in range(len(class_values)): attr_values = self.data[attr_idx, self.data[class_index] == c] attr_values = attr_values[~np.isnan(attr_values)] if len(attr_values) == 0: curr.append((0, 0, 0)) continue if self.show_statistics == MEANS: m = attr_values.mean() dev = attr_values.std() curr.append((m - dev, m, m + dev)) elif self.show_statistics == MEDIAN: sorted_array = np.sort(attr_values) curr.append((sorted_array[int(len(attr_values) / 4.0)], sorted_array[int(len(attr_values) / 2.0)], sorted_array[int(len(attr_values) * 0.75)])) data.append(curr) # draw vertical lines for i in range(len(data)): for c in range(len(data[i])): if data[i][c] == (): continue x = i - 0.03 * (len(data[i]) - 1) / 2.0 + c * 0.03 col = QColor(self.discrete_palette[c]) col.setAlpha(self.alpha_value_2) self.add_curve("", col, col, 3, OWCurve.Lines, OWPoint.NoSymbol, xData=[x, x, x], yData=[data[i][c][0], data[i][c][1], data[i][c][2]], lineWidth=4) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03], yData=[data[i][c][0], data[i][c][0]], lineWidth=4) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03], yData=[data[i][c][1], data[i][c][1]], lineWidth=4) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03], yData=[data[i][c][2], data[i][c][2]], lineWidth=4) # draw lines with mean/median values if not domain.class_var or domain.has_continuous_class: class_count = 1 else: class_count = len(self.domain.class_var.values) for c in range(class_count): diff = - 0.03 * (class_count - 1) / 2.0 + c * 0.03 ys = [] xs = [] for i in range(len(data)): if data[i] != [()]: ys.append(data[i][c][1]) xs.append(i + diff) else: if len(xs) > 1: col = QColor(self.discrete_palette[c]) col.setAlpha(self.alpha_value_2) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=xs, yData=ys, lineWidth=4) xs = [] ys = [] col = QColor(self.discrete_palette[c]) col.setAlpha(self.alpha_value_2) self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=xs, yData=ys, lineWidth=4) def draw_distributions(self): """Draw distributions with discrete attributes""" if not (self.show_distributions and self.data is not None and self.domain.has_discrete_class): return class_count = len(self.domain.class_var.values) class_ = self.domain.class_var # we create a hash table of possible class values (happens only if we have a discrete class) if self.domain_contingencies is None: self.domain_contingencies = dict( zip([attr for attr in self.domain if attr.is_discrete], get_contingencies(self.data, skipContinuous=True))) self.domain_contingencies[class_] = get_contingency(self.data, class_, class_) max_count = max([contingency.max() for contingency in self.domain_contingencies.values()] or [1]) sorted_class_values = get_variable_values_sorted(self.domain.class_var) for axis_idx, attr_idx in enumerate(self.attribute_indices): attr = self.domain[attr_idx] if attr.is_discrete: continue contingency = self.domain_contingencies[attr] attr_len = len(attr.values) # we create a hash table of variable values and their indices sorted_variable_values = get_variable_values_sorted(attr) # create bar curve for j in range(attr_len): attribute_value = sorted_variable_values[j] value_count = contingency[:, attribute_value] for i in range(class_count): class_value = sorted_class_values[i] color = QColor(*self.colors[i]) color.setAlpha(self.alpha_value) width = float(value_count[class_value] * 0.5) / float(max_count) y_off = float(1.0 + 2.0 * j) / float(2 * attr_len) height = 0.7 / float(class_count * attr_len) y_low_bottom = y_off + float(class_count * height) / 2.0 - i * height curve = PolygonCurve(QPen(color), QBrush(color), xData=[axis_idx, axis_idx + width, axis_idx + width, axis_idx], yData=[y_low_bottom, y_low_bottom, y_low_bottom - height, y_low_bottom - height], tooltip=attr.name) curve.attach(self) # handle tooltip events def event(self, ev): if ev.type() == QEvent.ToolTip: x = self.inv_transform(xBottom, ev.pos().x()) y = self.inv_transform(yLeft, ev.pos().y()) canvas_position = self.mapToScene(ev.pos()) x_float = self.inv_transform(xBottom, canvas_position.x()) contact, (index, pos) = self.testArrowContact(int(round(x_float)), canvas_position.x(), canvas_position.y()) if contact: attr = self.domain[self.attributes[index]] if attr.is_continuous: condition = self.selection_conditions.get(attr.name, [0, 1]) val = self.attr_values[attr][0] + condition[pos] * ( self.attr_values[attr][1] - self.attr_values[attr][0]) str_val = attr.name + "= %%.%df" % attr.number_of_decimals % val QToolTip.showText(ev.globalPos(), str_val) else: for curve in self.items(): if type(curve) == PolygonCurve and \ curve.boundingRect().contains(x, y) and \ getattr(curve, "tooltip", None): (name, value, total, dist) = curve.tooltip count = sum([v[1] for v in dist]) if count == 0: continue tooltip_text = "Attribute: <b>%s</b><br>Value: <b>%s</b><br>" \ "Total instances: <b>%i</b> (%.1f%%)<br>" \ "Class distribution:<br>" % ( name, value, count, 100.0 * count / float(total)) for (val, n) in dist: tooltip_text += " <b>%s</b> : <b>%i</b> (%.1f%%)<br>" % ( val, n, 100.0 * float(n) / float(count)) QToolTip.showText(ev.globalPos(), tooltip_text[:-4]) elif ev.type() == QEvent.MouseMove: QToolTip.hideText() return OWPlot.event(self, ev) def testArrowContact(self, indices, x, y): if type(indices) != list: indices = [indices] for index in indices: if index >= len(self.attributes) or index < 0: continue int_x = self.transform(xBottom, index) bottom = self.transform(yLeft, self.selection_conditions.get(self.attributes[index], [0, 1])[0]) bottom_rect = QRect(int_x - self.bottom_pixmap.width() / 2, bottom, self.bottom_pixmap.width(), self.bottom_pixmap.height()) if bottom_rect.contains(QPoint(x, y)): return 1, (index, 0) top = self.transform(yLeft, self.selection_conditions.get(self.attributes[index], [0, 1])[1]) top_rect = QRect(int_x - self.top_pixmap.width() / 2, top - self.top_pixmap.height(), self.top_pixmap.width(), self.top_pixmap.height()) if top_rect.contains(QPoint(x, y)): return 1, (index, 1) return 0, (0, 0) def mousePressEvent(self, e): canvas_position = self.mapToScene(e.pos()) x = self.inv_transform(xBottom, canvas_position.x()) contact, info = self.testArrowContact(int(round(x)), canvas_position.x(), canvas_position.y()) if contact: self.pressed_arrow = info else: OWPlot.mousePressEvent(self, e) def mouseMoveEvent(self, e): if hasattr(self, "pressed_arrow"): canvas_position = self.mapToScene(e.pos()) y = min(1, max(0, self.inv_transform(yLeft, canvas_position.y()))) index, pos = self.pressed_arrow attr = self.domain[self.attributes[index]] old_condition = self.selection_conditions.get(attr.name, [0, 1]) old_condition[pos] = y self.selection_conditions[attr.name] = old_condition self.update_data(self.attributes, self.visualized_mid_labels) if attr.is_continuous: val = self.attr_values[attr][0] + old_condition[pos] * ( self.attr_values[attr][1] - self.attr_values[attr][0]) strVal = attr.name + "= %.2f" % val QToolTip.showText(e.globalPos(), strVal) if self.sendSelectionOnUpdate and self.auto_send_selection_callback: self.auto_send_selection_callback() else: OWPlot.mouseMoveEvent(self, e) def mouseReleaseEvent(self, e): if hasattr(self, "pressed_arrow"): del self.pressed_arrow else: OWPlot.mouseReleaseEvent(self, e) def zoom_to_rect(self, r): r.setTop(self.graph_area.top()) r.setBottom(self.graph_area.bottom()) super().zoom_to_rect(r) def removeAllSelections(self, send=1): self.selection_conditions = {} self.update_data(self.attributes, self.visualized_mid_labels) # draw the curves and the selection conditions def drawCanvas(self, painter): OWPlot.drawCanvas(self, painter) for i in range( int(max(0, math.floor(self.axisScaleDiv(xBottom).interval().minValue()))), int(min(len(self.attributes), math.ceil(self.axisScaleDiv(xBottom).interval().maxValue()) + 1))): bottom, top = self.selection_conditions.get(self.attributes[i], (0, 1)) painter.drawPixmap(self.transform(xBottom, i) - self.bottom_pixmap.width() / 2, self.transform(yLeft, bottom), self.bottom_pixmap) painter.drawPixmap(self.transform(xBottom, i) - self.top_pixmap.width() / 2, self.transform(yLeft, top) - self.top_pixmap.height(), self.top_pixmap) def auto_send_selection_callback(self): pass def clear(self): super().clear() self.attributes = [] self.visualized_mid_labels = [] self.selected_examples = [] self.unselected_examples = [] self.selection_conditions = {}
def setPixmap(self, pixmap): self._pixmap = QPixmap(pixmap) self.updateGeometry() self.update()
class Preview(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pixmap = QPixmap() # Flag indicating if the widget was resized as a result of user # initiated window resize. When false the widget will automatically # resize/re-position based on pixmap size. self.__hasExplicitSize = False self.__inUpdateWindowGeometry = False def setPixmap(self, pixmap): if self.__pixmap != pixmap: self.__pixmap = QPixmap(pixmap) self.__updateWindowGeometry() self.update() self.updateGeometry() def pixmap(self): return QPixmap(self.__pixmap) def resizeEvent(self, event): super().resizeEvent(event) if self.isVisible() and self.isWindow() and \ not self.__inUpdateWindowGeometry: # mark that we have an explicit user provided size self.__hasExplicitSize = True def __updateWindowGeometry(self): if not self.isWindow() or self.__hasExplicitSize: return def framemargins(widget): frame, geom = widget.frameGeometry(), widget.geometry() return QMargins(geom.left() - frame.left(), geom.top() - frame.top(), geom.right() - frame.right(), geom.bottom() - frame.bottom()) def fitRect(rect, targetrect): size = rect.size().boundedTo(targetgeom.size()) newrect = QRect(rect.topLeft(), size) dx, dy = 0, 0 if newrect.left() < targetrect.left(): dx = targetrect.left() - newrect.left() if newrect.top() < targetrect.top(): dy = targetrect.top() - newrect.top() if newrect.right() > targetrect.right(): dx = targetrect.right() - newrect.right() if newrect.bottom() > targetrect.bottom(): dy = targetrect.bottom() - newrect.bottom() return newrect.translated(dx, dy) margins = framemargins(self) minsize = QSize(120, 120) pixsize = self.__pixmap.size() available = QApplication.desktop().availableGeometry(self) available = available.adjusted(margins.left(), margins.top(), -margins.right(), -margins.bottom()) # extra adjustment so the preview does not cover the whole desktop available = available.adjusted(10, 10, -10, -10) targetsize = pixsize.boundedTo(available.size()).expandedTo(minsize) pixsize.scale(targetsize, Qt.KeepAspectRatio) if not self.testAttribute(Qt.WA_WState_Created) or \ self.testAttribute(Qt.WA_WState_Hidden): center = available.center() else: center = self.geometry().center() targetgeom = QRect(QPoint(0, 0), pixsize) targetgeom.moveCenter(center) if not available.contains(targetgeom): targetgeom = fitRect(targetgeom, available) self.__inUpdateWindowGeometry = True self.setGeometry(targetgeom) self.__inUpdateWindowGeometry = False def sizeHint(self): return self.__pixmap.size() 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 setStamp(self, stamp): self.stamp = stamp self.setPixmap(QPixmap.fromImage(ImageQt.ImageQt(im_numbers[stamp]), flags=Qt.AutoColor))
def setupScene(self): self.error() if self.data: attr = self.stringAttrs[self.imageAttr] titleAttr = self.allAttrs[self.titleAttr] instances = [inst for inst in self.data if numpy.isfinite(inst[attr])] assert self.thumbnailView.count() == 0 size = QSizeF(self.imageSize, self.imageSize) for i, inst in enumerate(instances): url = self.urlFromValue(inst[attr]) title = str(inst[titleAttr]) thumbnail = GraphicsThumbnailWidget(QPixmap(), title=title) thumbnail.setThumbnailSize(size) thumbnail.setToolTip(url.toString()) thumbnail.instance = inst self.thumbnailView.addThumbnail(thumbnail) if url.isValid() and url.isLocalFile(): reader = QImageReader(url.toLocalFile()) image = reader.read() if image.isNull(): error = reader.errorString() thumbnail.setToolTip( thumbnail.toolTip() + "\n" + error) self._errcount += 1 else: pixmap = QPixmap.fromImage(image) thumbnail.setPixmap(pixmap) self._successcount += 1 future = Future() future.set_result(image) future._reply = None elif url.isValid(): future = self.loader.get(url) @future.add_done_callback def set_pixmap(future, thumb=thumbnail): if future.cancelled(): return assert future.done() if future.exception(): # Should be some generic error image. pixmap = QPixmap() thumb.setToolTip(thumb.toolTip() + "\n" + str(future.exception())) else: pixmap = QPixmap.fromImage(future.result()) thumb.setPixmap(pixmap) self._noteCompleted(future) else: future = None self.items.append(_ImageItem(i, thumbnail, url, future)) if any(it.future is not None and not it.future.done() for it in self.items): self.info.setText("Retrieving...\n") else: self._updateStatus()
def setPixmap(self, pixmap): if self.__pixmap != pixmap: self.__pixmap = QPixmap(pixmap) self.__updateWindowGeometry() self.update() self.updateGeometry()