async def loadImg(self, src, name): try: async with aiohttp.ClientSession() as session: async with session.get(src, headers=headers, timeout=60) as response: if response.status == 200: image_content = await response.read() else: raise aiohttp.ClientError() except Exception as e: print(e) return width = self.width height = self.height pic = QPixmap() pic.loadFromData(image_content) localSrc = cacheFolder + '/' + name pic.save(localSrc, 'jpg') pic = pic.scaled(width, height) self.src = localSrc # 上遮罩。 if self.pixMask: mask = QPixmap() mask.load(self.pixMask) mask = mask.scaled(width, height) pic.setMask(mask.createHeuristicMask()) self.setPixmap(pic)
def pango_get_icon(name, color=None): fn = ":/icons/" + name.lower().replace(" ", "_") + ".png" px = QPixmap(fn) mask = px.createMaskFromColor(QColor('white'), Qt.MaskOutColor) px.fill(pango_app_icon_color if color is None else color) px.setMask(mask) return QIcon(px)
def __initCursors(self): """ Private method to initialize the various cursors. """ self.__normalCursor = QCursor(Qt.ArrowCursor) pix = QPixmap(":colorpicker-cursor.xpm") mask = pix.createHeuristicMask() pix.setMask(mask) self.__colorPickerCursor = QCursor(pix, 1, 21) pix = QPixmap(":paintbrush-cursor.xpm") mask = pix.createHeuristicMask() pix.setMask(mask) self.__paintCursor = QCursor(pix, 0, 19) pix = QPixmap(":fill-cursor.xpm") mask = pix.createHeuristicMask() pix.setMask(mask) self.__fillCursor = QCursor(pix, 3, 20) pix = QPixmap(":aim-cursor.xpm") mask = pix.createHeuristicMask() pix.setMask(mask) self.__aimCursor = QCursor(pix, 10, 10) pix = QPixmap(":eraser-cursor.xpm") mask = pix.createHeuristicMask() pix.setMask(mask) self.__rubberCursor = QCursor(pix, 1, 16)
def _draw_flags_icon(mutable: bool, persistent: bool, icon_size: int) -> QPixmap: """ Combines icons into a single large icon and renders it into a pixmap of specified size. This operation is quite resource-consuming (we're drawing pictures after all, ask Picasso), so we cache the results in a LRU cache. """ icon_name = "edit" if mutable else "lock" mutability = get_icon_pixmap(icon_name, icon_size) # https://youtu.be/AX2uz2XYkbo?t=21s icon_name = "save" if persistent else "random-access-memory" persistence = get_icon_pixmap(icon_name, icon_size) icon_size_rect = QRect(0, 0, icon_size, icon_size) pixmap = QPixmap(icon_size * 2, icon_size) mask = QBitmap(pixmap.width(), pixmap.height()) mask.clear() pixmap.setMask(mask) painter = QPainter(pixmap) painter.drawPixmap(icon_size_rect, mutability, icon_size_rect) painter.drawPixmap( QRect(icon_size, 0, icon_size, icon_size), persistence, icon_size_rect ) return pixmap
def mouseMoveEvent(self, event): if QLineF(QPointF(event.screenPos()), QPointF(event.buttonDownScreenPos(Qt.LeftButton))).length() < QApplication.startDragDistance(): return drag = QDrag(event.widget()) mime = QMimeData() drag.setMimeData(mime) ColorItem.n += 1 if ColorItem.n > 2 and qrand() % 3 == 0: image = QImage(':/images/head.png') mime.setImageData(image) drag.setPixmap(QPixmap.fromImage(image).scaled(30,40)) drag.setHotSpot(QPoint(15, 30)) else: mime.setColorData(self.color) mime.setText("#%02x%02x%02x" % (self.color.red(), self.color.green(), self.color.blue())) pixmap = QPixmap(34, 34) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.translate(15, 15) painter.setRenderHint(QPainter.Antialiasing) self.paint(painter, None, None) painter.end() pixmap.setMask(pixmap.createHeuristicMask()) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(15, 20)) drag.exec_() self.setCursor(Qt.OpenHandCursor)
def toggleCursor(self): if self.cursor().shape() == QCursor(Qt.ArrowCursor).shape(): raw = QPixmap(":/gui/pics/pardusman-icon.png") raw.setMask(raw.mask()) self.setCursor(QCursor(raw, 2, 2)) else: self.unsetCursor()
def setSrc(self, src): src = str(src) if 'http' in src or 'https' in src: cacheList = os.listdir(cacheFolder) name = makeMd5(src) localSrc = cacheFolder + '/' + name if name in cacheList: self.setSrc(localSrc) self.src = localSrc return self.loadImg(src, name) else: self.src = src pix = QPixmap(src) pix.load(src) pix = pix.scaled(self.width, self.height) # mask需要与pix是相同大小。 if self.pixMask: mask = QPixmap(self.pixMask) mask = mask.scaled(self.width, self.height) pix.setMask(mask.createHeuristicMask()) self.setPixmap(pix)
def colored_icon(name, color): pix = QPixmap(name) mask = pix.createMaskFromColor(QColor(Qt.black), Qt.MaskOutColor) if isinstance(color, str): color = QColor(color) pix.fill(color) pix.setMask(mask) return QIcon(pix)
def __init__(self, filename="", tint_color=None): palette = QApplication.instance().palette() px = QPixmap(filename) pxr = QPixmap(px.size()) if not tint_color: pxr.fill(palette.color(QPalette.ButtonText)) else: pxr.fill(tint_color) pxr.setMask(px.createMaskFromColor((Qt.transparent))) super().__init__(pxr)
class Icon(): def __init__(self, filename, color='#FFF'): super().__init__() self.pixmap = QPixmap('./icons/{}'.format(filename)) mask = self.pixmap.createMaskFromColor(QColor('black'), Qt.MaskOutColor) self.pixmap.fill((QColor(color))) self.pixmap.setMask(mask) def getIcon(self): return QIcon(self.pixmap)
def __load_cursors(cls): cursors = { (DrawingMode.NoDraw, DrawingShape.NoShape): QCursor(Qt.ArrowCursor) } for k in cls.key_to_drawstate: px = QPixmap(cursors_xpm[k]) mask = px.createHeuristicMask() px.setMask(mask) cursor = QCursor(px, 0, 0) # hot point is always top left (mode, shape) = (cls.key_to_drawstate[k]) cursors[(mode, shape)] = cursor return cursors
def chromecast_device_connected(self, device): px = QPixmap('icons/cast.svg') pxr = QPixmap(px.size()) pxr.fill(Qt.lightGray) pxr.setMask(px.createMaskFromColor((Qt.transparent))) self.window().cast_label_pixmap.setPixmap(pxr) self.window().cast_label_pixmap.setScaledContents(True) self.window().cast_label.setText(self.tr("Connected to: {0}".format(device.device.friendly_name))) self.window().cast_label_pixmap.setHidden(False) self.window().cast_label.setHidden(False) self.chromecast_connected.emit(device) if self.player.path: self.chromecast_manager.play_url(self.player.path)
def get_icon(invert): # https://stackoverflow.com/questions/13350631/simple-color-fill-qicons-in-qt pixmap = QPixmap(':icon.png') assert(pixmap is not None) if invert: log.debug('inverting icon') mask = pixmap.mask() pixmap.fill((QColor('white'))) pixmap.setMask(mask) icon = QIcon(pixmap) return icon
def load_themed_icon(file_path: str, color: QColor) -> QIcon: """ Loads an icon, paints it the given color, and builds an icon :param file_path: Path where the icon is stored, to be loaded as a pixmap :param color: Color to paint pixmap :return: a new QIcon containing the photo at file_path """ photo_pixmap = QPixmap(file_path) themed_pixmap = QPixmap(photo_pixmap.size()) themed_pixmap.fill(color) themed_pixmap.setMask(photo_pixmap.createMaskFromColor(Qt.transparent)) return QIcon(themed_pixmap)
def mk_icons( style: QStyle, size: QSize, ) -> dict[str, QIcon]: '''This helper is indempotent. ''' global _icons, _icon_names if _icons: return _icons _icons[None] = QIcon() # the "null" icon # load account selection using current style for name, icon_name in _icon_names.items(): stdpixmap = getattr(QStyle, icon_name) stdicon = style.standardIcon(stdpixmap) pixmap = stdicon.pixmap(size) # fill hack from SO to change icon color: # https://stackoverflow.com/a/38369468 out_pixmap = QPixmap(size) out_pixmap.fill(QColor(hcolor('default_spotlight'))) out_pixmap.setMask(pixmap.createHeuristicMask()) # TODO: not idea why this doesn't work / looks like # trash. Sure would be nice to just generate our own # pixmaps on the fly.. # p = QPainter(out_pixmap) # p.setOpacity(1) # p.setBrush(QColor(hcolor('papas_special'))) # p.setPen(QColor(hcolor('default_lightest'))) # path = mk_marker_path(style='|<') # p.scale(6, 6) # # p.translate(0, 0) # p.drawPath(path) # p.save() # p.end() # del p # icon = QIcon(out_pixmap) icon = QIcon() icon.addPixmap(out_pixmap) _icons[name] = icon return _icons
def __init__(self): super().__init__() pixmap = QPixmap(imageDir + 'home.png') mask = pixmap.createMaskFromColor(QColor('transparent'), Qt.MaskInColor) pixmap.fill(QColor(150, 150, 150)) pixmap.setMask(mask) icon = QIcon(pixmap) self.setIcon(icon) self.setFixedSize(SIZE) self.setIconSize(SIZE) self.setStyleSheet("border: 0px solid black; background: transparent")
def mouseMoveEvent(self, event): if ( QLineF( QPointF(event.screenPos()), QPointF(event.buttonDownScreenPos(Qt.LeftButton)), ).length() < QApplication.startDragDistance() ): return drag = QDrag(event.widget()) mime = QMimeData() drag.setMimeData(mime) ColorItem.n += 1 if ColorItem.n > 2 and qrand() % 3 == 0: root = QFileInfo(__file__).absolutePath() image = QImage(root + "/images/head.png") mime.setImageData(image) drag.setPixmap(QPixmap.fromImage(image).scaled(30, 40)) drag.setHotSpot(QPoint(15, 30)) else: mime.setColorData(self.color) mime.setText( "#%02x%02x%02x" % (self.color.red(), self.color.green(), self.color.blue()) ) pixmap = QPixmap(34, 34) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.translate(15, 15) painter.setRenderHint(QPainter.Antialiasing) self.paint(painter, None, None) painter.end() pixmap.setMask(pixmap.createHeuristicMask()) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(15, 20)) drag.exec_() self.setCursor(Qt.OpenHandCursor)
def _mask_draw(self): if self.image is None: return # QBitmap 생성 bitmap = self.image.get_mask() # QPixmap 생성 pixmap = QPixmap(self.pixmap) pixmap.fill(self.mode.DRAW_MASK_COLOR) # pixmap 에 Mask를 씌운다. pixmap.setMask(bitmap) # Item 생성 및 추가 if self.obj['mask'] is not None: self.scene.removeItem(self.obj['mask']) self.obj['mask'] = QGraphicsPixmapItem(pixmap) self.scene.addItem(self.obj['mask'])
def __init__(self, job: Job): super(JobWidget, self).__init__() self.job = job self.setToolTip(f"{job.id} {job.name}") # self.setMaximumWidth(ICON_SIZE) pixmap = load_svg_sized_pixmap( f"icons/sprite_icons_status_{job.status}.svg") color_mask = QPixmap(pixmap.size()) q_color = QColor(COLORS[job.status]) color_mask.fill(q_color) color_mask.setMask(pixmap.createMaskFromColor(QColor(255, 255, 255, 0))) color_mask.setMask( pixmap.createMaskFromColor(QColor(255, 255, 255, 255))) resized = color_mask.scaled(ICON_SIZE, ICON_SIZE, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) self.setPixmap(resized)
def add_label(self, attr_name: str, width: int, height: int, x: int = 0, y: int = 0, set_pixmap: bool = False, parent: Widget = None, ignore_geometry: bool = False): label = Label() if parent is not None: label.setParent(parent) if not ignore_geometry: if parent is not None: label_geo = *self.relative_center(parent, tr_x=x, tr_y=y, width=width, height=height), width, height else: label_geo = self.center_x(width, x), self.center_y(height, y), width, height label.setGeometry(*label_geo) if set_pixmap: pixmap = QPixmap(width, height) mask = pixmap.createMaskFromColor(QColor(0, 0, 0), Qt.MaskInColor) pixmap.setMask(mask) label.setPixmap(pixmap) if not hasattr(self, attr_name): setattr(self, attr_name, label) else: raise ValueError('Label Attribute: attr_name = ' + attr_name + ' | is Already Exists')
def load_img(self, c): global counter counter += 1 imager = Imager(self.state["Title"], self.state["Artist"]) data = imager.get_data() if (c + 1 != counter): return pixmap = QPixmap() pixmap.loadFromData(data) map = QBitmap(pixmap.size()) map.fill(Qt.color0) painter = QPainter(map) painter.setBrush(Qt.color1) painter.drawRoundedRect(0, 0, pixmap.width(), pixmap.height(), 10, 10) painter.end() self.app.label.setScaledContents(True) pixmap.setMask(map) self.app.label.setPixmap( pixmap.scaled(self.app.label.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation))
def _color_icon(icon, color_code): pix_map = QPixmap(icon) mask = pix_map.createMaskFromColor(QColor('black'), Qt.MaskOutColor) pix_map.fill(QColor(color_code)) pix_map.setMask(mask) return QIcon(pix_map)
class ImageLayer(Layer): ## # Constructor. ## def __init__(self, name, x, y, width, height): super().__init__(Layer.ImageLayerType, name, x, y, width, height) self.mImage = QPixmap() self.mTransparentColor = QColor() self.mImageSource = QString() ## # Destructor. ## def __del__(self): pass def usedTilesets(self): return QSet() def referencesTileset(self, arg1): return False def replaceReferencesToTileset(self, arg1, arg2): pass def canMergeWith(self, arg1): return False def mergedWith(self, arg1): return None ## # Returns the transparent color, or an invalid color if no transparent # color is used. ## def transparentColor(self): return QColor(self.mTransparentColor) ## # Sets the transparent color. Pixels with this color will be masked out # when loadFromImage() is called. ## def setTransparentColor(self, c): self.mTransparentColor = c ## # Sets image source file name ## def setSource(self, source): self.mImageSource = source ## # Returns the file name of the layer image. ## def imageSource(self): return self.mImageSource ## # Returns the image of this layer. ## def image(self): return QPixmap(self.mImage) ## # Sets the image of this layer. ## def setImage(self, image): self.mImage = image ## # Resets layer image. ## def resetImage(self): self.mImage = QPixmap() self.mImageSource = '' ## # Load this layer from the given \a image. This will replace the existing # image. The \a fileName becomes the new imageSource, regardless of # whether the image could be loaded. # # @param image the image to load the layer from # @param fileName the file name of the image, which will be remembered # as the image source of this layer. # @return <code>true</code> if loading was successful, otherwise # returns <code>false</code> ## def loadFromImage(self, image, fileName): self.mImageSource = fileName if (image.isNull()): self.mImage = QPixmap() return False self.mImage = QPixmap.fromImage(image) if (self.mTransparentColor.isValid()): mask = image.createMaskFromColor(self.mTransparentColor.rgb()) self.mImage.setMask(QBitmap.fromImage(mask)) return True ## # Returns True if no image source has been set. ## def isEmpty(self): return self.mImage.isNull() def clone(self): return self.initializeClone( ImageLayer(self.mName, self.mX, self.mY, self.mWidth, self.mHeight)) def initializeClone(self, clone): super().initializeClone(clone) clone.mImageSource = self.mImageSource clone.mTransparentColor = self.mTransparentColor clone.mImage = self.mImage return clone
def set_tile_pix(self, pix: QPixmap, mask: QBitmap, x: int, y: int) -> None: """Create the pixmap for the part of the piece located at x,y . The pixmap is created inside the pix argument""" pid = self.klmap.pid(x, y) piece_type = pid if is_piece(piece_type): piece_type = Piece.pieces[0] offset_list = [(0, 0), (PIX_SIZE, 0), (PIX_SIZE, PIX_SIZE), (0, PIX_SIZE)] # Value assiociated with each neighbour # # 2 | 1 1 | 2 # ----- ----- # 4 | XXXX | 4 # XXXX # 4 | XXXX | 4 # ----- ----- # 2 | 1 1 | 2 # # (dx, dy, val) neighbour_val_list = [ [(0, -1, 1), (-1, -1, 2), (-1, 0, 4)], [(0, -1, 1), (1, -1, 2), (1, 0, 4)], [(0, 1, 1), (1, 1, 2), (1, 0, 4)], [(0, 1, 1), (-1, 1, 2), (-1, 0, 4)], ] # which pixmap to choose according to the value of the # neighbours which_quarter = { 0: Tile.corner, 1: Tile.ver_edge, 2: Tile.corner, 3: Tile.ver_edge, 4: Tile.hor_edge, 5: Tile.miss_corner, 6: Tile.hor_edge, 7: Tile.inner, } p = QPainter(pix) pm = QPainter(mask) for i in range(4): offset = offset_list[i] neighbour_val = neighbour_val_list[i] pix_nb = 0 for neigh in neighbour_val: if pid == self.klmap.pid(x + neigh[0], y + neigh[1]): pix_nb = pix_nb + neigh[2] quarter_nb = which_quarter[pix_nb] assert KLBoard.pix_tiles # to help mypy making sure that tiles_mask is not None p.drawPixmap( offset[0], offset[1], KLBoard.pix_tiles, quarter_nb * TILE_SIZE + offset[0], piece_tile[piece_type] * TILE_SIZE + offset[1], PIX_SIZE, PIX_SIZE, ) assert KLBoard.tiles_mask # to help mypy making sure that tiles_mask is not None pm.drawPixmap( offset[0], offset[1], KLBoard.tiles_mask, quarter_nb * TILE_SIZE + offset[0], piece_tile[piece_type] * TILE_SIZE + offset[1], PIX_SIZE, PIX_SIZE, ) p.end() pm.end() pix.setMask(mask)
def drawPixmap(self): pixmap = QPixmap(self.diameter, self.diameter) pixmap.fill(Qt.white) self.paintOnPixmap(pixmap) pixmap.setMask(pixmap.createHeuristicMask()) return pixmap
class ImageLayer(Layer): ## # Constructor. ## def __init__(self, name, x, y, width, height): super().__init__(Layer.ImageLayerType, name, x, y, width, height) self.mImage = QPixmap() self.mTransparentColor = QColor() self.mImageSource = QString() ## # Destructor. ## def __del__(self): pass def usedTilesets(self): return QSet() def referencesTileset(self, arg1): return False def replaceReferencesToTileset(self, arg1, arg2): pass def canMergeWith(self, arg1): return False def mergedWith(self, arg1): return None ## # Returns the transparent color, or an invalid color if no transparent # color is used. ## def transparentColor(self): return QColor(self.mTransparentColor) ## # Sets the transparent color. Pixels with this color will be masked out # when loadFromImage() is called. ## def setTransparentColor(self, c): self.mTransparentColor = c ## # Sets image source file name ## def setSource(self, source): self.mImageSource = source ## # Returns the file name of the layer image. ## def imageSource(self): return self.mImageSource ## # Returns the image of this layer. ## def image(self): return QPixmap(self.mImage) ## # Sets the image of this layer. ## def setImage(self, image): self.mImage = image ## # Resets layer image. ## def resetImage(self): self.mImage = QPixmap() self.mImageSource = '' ## # Load this layer from the given \a image. This will replace the existing # image. The \a fileName becomes the new imageSource, regardless of # whether the image could be loaded. # # @param image the image to load the layer from # @param fileName the file name of the image, which will be remembered # as the image source of this layer. # @return <code>true</code> if loading was successful, otherwise # returns <code>false</code> ## def loadFromImage(self, image, fileName): self.mImageSource = fileName if (image.isNull()): self.mImage = QPixmap() return False self.mImage = QPixmap.fromImage(image) if (self.mTransparentColor.isValid()): mask = image.createMaskFromColor(self.mTransparentColor.rgb()) self.mImage.setMask(QBitmap.fromImage(mask)) return True ## # Returns True if no image source has been set. ## def isEmpty(self): return self.mImage.isNull() def clone(self): return self.initializeClone(ImageLayer(self.mName, self.mX, self.mY, self.mWidth, self.mHeight)) def initializeClone(self, clone): super().initializeClone(clone) clone.mImageSource = self.mImageSource clone.mTransparentColor = self.mTransparentColor clone.mImage = self.mImage return clone