class Video(QWidget): def __init__(self): QWidget.__init__(self) self._bridge = CvBridge() self._frame = None self._img = None self._label = QLabel(self) self._pxmp = QPixmap() self._pxmp.fill(QColor('black')) self._label.setPixmap(self._pxmp) self._layout = QVBoxLayout() self._layout.addWidget(self._label) self.setLayout(self._layout) def vid_callback(self, data): try: # convert received ROS Image to cv2 image and convert to RGB self._frame = cv2.cvtColor(self._bridge.imgmsg_to_cv2(data), cv2.COLOR_BGR2RGB) # convert cv2 image to QPixmap self._img = QImage(self._frame.data, self._frame.shape[1], self._frame.shape[0], self._frame.strides[0], QImage.Format_RGB888) # set self._label to pixmap self._label.setPixmap(QPixmap.fromImage(self._img)) self.update() except CvBridgeError, e: print e
def _create_tray_icon(self): menu = QMenu() self._mode_group = QActionGroup(menu) self._mode_group.triggered.connect(self._mode_changed) self._mode_off = QAction("&Off", parent=menu) self._mode_off.setCheckable(True) self._mode_off.setChecked(True) self._mode_group.addAction(self._mode_off) menu.addAction(self._mode_off) self._mode_enabled = QAction("&Enabled", parent=menu) self._mode_enabled.setCheckable(True) self._mode_group.addAction(self._mode_enabled) menu.addAction(self._mode_enabled) self._mode_training = QAction("&Training mode", parent=menu) self._mode_training.setCheckable(True) self._mode_group.addAction(self._mode_training) menu.addAction(self._mode_training) menu.addSeparator() menu.addAction("&Preferences", self.open_preferences) menu.addSeparator() menu.addAction("E&xit", self.exit) pixmap = QPixmap(32, 32) pixmap.fill(Qt.white) icon = QIcon(pixmap) self._tray_icon = QSystemTrayIcon(parent=self) self._tray_icon.setContextMenu(menu) self._tray_icon.setIcon(icon) self._tray_icon.show()
class QCaptionedImage(QWidget): def __init__(self, caption=None, image=None, *args, **kwargs): super().__init__(*args, **kwargs) self.window = QLabel() self.window.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.window.setLineWidth(2) self.caption = QLabel() self.caption.setAlignment(Qt.AlignCenter) self.caption.setWordWrap(True) # placeholder background when nothing is shown self.blank_background = QPixmap(290, 290) self.blank_background.fill(QColor(0, 0, 0, 32)) self.layout = QVBoxLayout() self.layout.addWidget(self.caption) self.layout.addWidget(self.window) self.setLayout(self.layout) if caption: self.caption.setText(caption) if image is None: self.clearImage() else: self.setImage(image) def clearImage(self): self.window.setPixmap(self.blank_background) def setImage(self, image: QPixmap): self.window.setPixmap(image)
def group_object_pixmap(self, object_class_name): if object_class_name in self.group_obj_pixmap_cache: return self.group_obj_pixmap_cache[object_class_name] object_pixmap = self.object_pixmap(object_class_name) size = object_pixmap.size() width, height = size.width(), size.height() radius = width / 8 pen_width = width / 32 margin = width / 16 pen = QPen(QApplication.palette().shadow().color()) pen.setWidth(pen_width) path = QPainterPath() path.addRoundedRect(0, 0, width, height, radius, radius) pixmap = QPixmap(size) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.fillPath(path, QApplication.palette().window()) painter.setPen(pen) painter.drawRoundedRect(pixmap.rect().adjusted(pen_width, pen_width, -pen_width, -pen_width), radius, radius) painter.drawPixmap( pixmap.rect().adjusted(margin, margin, -width / 2, -height / 2), object_pixmap, object_pixmap.rect() ) painter.drawPixmap( pixmap.rect().adjusted(width / 2, margin, -margin, -height / 2), object_pixmap, object_pixmap.rect() ) painter.drawPixmap( pixmap.rect().adjusted(width / 2, height / 2, -margin, -margin), object_pixmap, object_pixmap.rect() ) painter.drawPixmap( pixmap.rect().adjusted(margin, height / 2, -width / 2, -margin), object_pixmap, object_pixmap.rect() ) painter.end() self.group_obj_pixmap_cache[object_class_name] = pixmap return pixmap
def __init__(self, parent, delegate): QWidget.__init__(self, parent) self.delegate = delegate self.emitted = False self.ui = Ui_AskVerdict() self.ui.setupUi(self) # build verdict icons if not AskVerdict.icons_cache: for text in VERDICTS: color = VERDICT_TO_ROW_COLORS.get(text[0]) pixmap = QPixmap(16, 16) pixmap.fill(Qt.transparent) if color: painter = QPainter(pixmap) painter.setPen(Qt.black) painter.setBrush(color) painter.drawEllipse(0, 0, 15, 15) painter.end() AskVerdict.icons_cache[text] = QIcon(pixmap) # set combo verdict for text in ("other...", "skip", "retry"): self.ui.comboVerdict.addItem(AskVerdict.icons_cache[text], text) model = self.ui.comboVerdict.model() model.itemFromIndex(model.index(0, 0)).setSelectable(False) self.ui.comboVerdict.activated.connect(self.on_dropdown_item_activated) self.ui.goodVerdict.clicked.connect(self.on_good_bad_button_clicked) self.ui.goodVerdict.setIcon(AskVerdict.icons_cache["good"]) self.ui.badVerdict.clicked.connect(self.on_good_bad_button_clicked) self.ui.badVerdict.setIcon(AskVerdict.icons_cache["bad"])
def __init__(self, size=100, border=20, parentItem=None): super().__init__(size=size, parentItem=parentItem) # brightness sliders self.brightnessSliderHeight = 20 self.brightnessSliderWidth = size #+ 2 * border px = QPixmap(self.brightnessSliderWidth, self.brightnessSliderHeight) px.fill(Qt.gray) self.brightnessSlider = QGraphicsPixmapItem(px, parent=self) self.brightnessSlider.setPos(0, size + 20) # brightnessSlider handles self.brightnessThr0 = activeRsMarker.fromTriangle( parent=self.brightnessSlider, role='min') self.brightnessThr0.setMoveRange( QRectF(0.0, self.brightnessThr0.size, self.brightnessSlider.pixmap().width(), 0.0)) self.brightnessThr0.setPos( 0, self.brightnessSlider.pixmap().height() - self.brightnessThr0.size) self.brightnessThr0.val = 0.0 self.brightnessThr1 = activeRsMarker.fromTriangle( parent=self.brightnessSlider, role='max') self.brightnessThr1.setMoveRange( QRectF(0.0, self.brightnessThr0.size, self.brightnessSlider.pixmap().width(), 0.0)) self.brightnessThr1.setPos( self.brightnessSlider.pixmap().width(), self.brightnessSlider.pixmap().height() - self.brightnessThr0.size) self.brightnessThr1.val = 1.0
def updateScene(self): ''' Clear the displayed scene using self.__lastclearcolor, then draw the scaled current image. ''' # get the scaled scene size labelwidth = int(self.__scalefactor * self.__scenewidth + 0.5) labelheight = int(self.__scalefactor * self.__sceneheight + 0.5) # Create the new pixmap for the label to display newpixmap = QPixmap(labelwidth, labelheight) newpixmap.fill(self.__lastclearcolor) if self.__sceneimage != None: # Draw the scaled image to the pixmap mypainter = QPainter(newpixmap) trgrect = QRectF(0.0, 0.0, float(labelwidth), float(labelheight)) srcrect = QRectF(0.0, 0.0, float(self.__scenewidth), float(self.__sceneheight)) mypainter.drawImage(trgrect, self.__sceneimage, srcrect, Qt.AutoColor) mypainter.end() # Assign the new pixmap to the label self.__label.setPixmap(newpixmap) # set the label size and values # so the scrollarea knows of the new size self.__label.setMinimumSize(labelwidth, labelheight) self.__label.resize(labelwidth, labelheight) # update the label from the new pixmap self.__label.update()
def update_screen(self) -> None: use_live_screen = ( self.live_screen_checkbox.checkState() == Qt.CheckState.Checked) is_powered_on = self.power_checkbox.checkState( ) == Qt.CheckState.Checked image_display = (self.image_display_on if is_powered_on else self.image_display_off) result = QPixmap(image_display.size()) result.fill(Qt.transparent) painter = QPainter(result) painter.drawPixmap(QPoint(0, 0), image_display) if is_powered_on: screenshot = get_screenshot( ) if use_live_screen else self.screenshot screenshot = screenshot.scaled(800, 800, Qt.KeepAspectRatio, Qt.SmoothTransformation) screenshot = screenshot.copy(QRect(0, 0, 800, 480 * 0.94)) offset_x = (image_display.size().width() - screenshot.size().width()) / 2 offset_y = (image_display.size().height() - screenshot.size().height()) / 2 painter.setOpacity(self.backlight.brightness / 100) painter.drawPixmap(QPoint(offset_x, offset_y), screenshot) painter.end() result = result.scaled(600, 600, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.screen_image.setPixmap(result)
def set_color(self, color): if color != self._color: self._color = color self.colorChanged.emit(self._color) pixmap = QPixmap(self.iconSize()) pixmap.fill(color) self.setIcon(QIcon(pixmap))
def relationship_pixmap(self, str_object_class_name_list): """A pixmap for the given object_class name list, created by rendering several object pixmaps next to each other.""" if not str_object_class_name_list: engine = CharIconEngine("\uf1b3", 0) return engine.pixmap(self.ICON_SIZE) object_class_name_list = tuple(str_object_class_name_list.split(",")) if object_class_name_list in self.rel_cls_pixmap_cache: return self.rel_cls_pixmap_cache[object_class_name_list] scene = QGraphicsScene() x = 0 for j, object_class_name in enumerate(object_class_name_list): pixmap = self.object_pixmap(object_class_name) pixmap_item = scene.addPixmap(pixmap) if j % 2 == 0: y = 0 else: y = -0.875 * 0.75 * pixmap_item.boundingRect().height() pixmap_item.setZValue(-1) pixmap_item.setPos(x, y) x += 0.875 * 0.5 * pixmap_item.boundingRect().width() pixmap = QPixmap(scene.itemsBoundingRect().toRect().size()) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) scene.render(painter) painter.end() self.rel_cls_pixmap_cache[object_class_name_list] = pixmap return pixmap
def init(self): widget = QWidget() layout = QGridLayout(widget) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) num = 0 self.ColorDict = dict() self.ButtonList = QButtonGroup() for column in range(self._columns): for row in range(self._rows): if num < len(self.palette): newColor = self.palette[num] button = QPushButton('') button.setContentsMargins(0,0,0,0) button.setStyleSheet("padding: 0px;margin: 0px;") button.setFixedSize(20,20) self.ColorDict[button] = self.palette[num] self.ButtonList.addButton(button) pixmap = QPixmap(20, 20) pixmap.fill(newColor) button.setIcon(QIcon(pixmap)) layout.addWidget(button, row, column) num+=1 else: break self.ButtonList.buttonClicked.connect(self.handleButton) self.setDefaultWidget(widget)
def findIcons(self): if hou.applicationVersion()[0] < 15: for category in os.listdir(self.path): for ico in os.listdir(os.path.join(self.path, category)): iconPath = os.path.join( os.path.join(self.path, category, ico)) iconName = '_'.join([category, os.path.splitext(ico)[0]]) self.icons[iconName] = QPixmap(iconPath) else: zf = zipfile.ZipFile(self.path, 'r') for f in zf.namelist(): if f.startswith('old'): continue if os.path.splitext(f)[-1] == '.svg': svg = QSvgRenderer(QByteArray(zf.read(f))) if not svg.isValid(): continue pixmap = QPixmap(iconSize, iconSize) painter = QPainter() painter.begin(pixmap) pixmap.fill(QColor(Qt.black)) svg.render(painter) painter.end() category, ico = f.split('/') iconName = '_'.join([category, os.path.splitext(ico)[0]]) self.icons[iconName] = pixmap zf.close()
def _icon_by_painter(self, painter, options): size = QSize(width, height) pm = QPixmap(size) pm.fill(Qt.transparent) painter.paint(self, QPainter(pm), QRect(QPoint(0, 0), size), PySide2.QtGui.QIcon.Mode.Normal, PySide2.QtGui.QIcon.State.Off, options) return QIcon(pm)
def setColor(self, color): self.color = color pixels = QPixmap(35, 12) pixels.fill(color) icon = QIcon(pixels) self.setIcon(icon) self.setIconSize(pixels.rect().size())
def __init__(self): super().__init__() self.label = QLabel() canvas = QPixmap(400, 300) canvas.fill(Qt.white) self.label.setPixmap(canvas) self.draw_something()
def update_bg_color(self): """Set tool button icon as the selected color and update Design View scene background color.""" pixmap = QPixmap(16, 16) pixmap.fill(self.bg_color) self.ui.toolButton_bg_color.setIcon(pixmap) self._toolbox.ui.graphicsView.scene().set_bg_color(self.bg_color) self._toolbox.ui.graphicsView.scene().update()
def create_painter(self) -> typing.Iterator[QPainter]: white = QColor('white') pixmap = QPixmap(self.width, self.height) pixmap.fill(white) painter = QPainter(pixmap) try: yield painter finally: painter.end()
class BackgroundPainter(BasePainter): def __init__(self, parent): BasePainter.__init__(self, parent) self._galaxy = QPixmap(IMAGE_GALAXY_PATH) if self._galaxy.size() != QSize(PartyConst.WIDTH, PartyConst.HEIGHT): self._galaxy = QPixmap(QSize(PartyConst.WIDTH, PartyConst.HEIGHT)) self._galaxy.fill(QColor('#20124d')) else: self.is_set = True def setup(self): if not self.is_set: _edge = max([PartyConst.WIDTH, PartyConst.HEIGHT]) self._stars = np.random.randint(low=0, high=_edge, size=((_edge // 250)**2, 2)) self._pen_link = QPen(QColor('#351c75'), 2, Qt.SolidLine) self._lines = [] min_dist = 100 for _star in self._stars: for _sub_star in self._stars: if 0 < np.linalg.norm(_star - _sub_star) < min_dist: self._lines.append((_star, _sub_star)) _edge = max([PartyConst.WIDTH, PartyConst.HEIGHT]) _center = QPoint(self._galaxy.width() // 2, self._galaxy.height() // 2) _gradient = QRadialGradient(_center, _edge // 2) _gradient.setColorAt(1, QColor('#20124d')) _gradient.setColorAt(0, QColor('#351c75')) painter = QPainter(self._galaxy) painter.fillRect(0, 0, _edge, _edge, _gradient) painter.setPen(self._pen_link) for _xy1, _xy2 in self._lines: _xy1, _xy2 = QPoint(*_xy1), QPoint(*_xy2) painter.drawLine(_xy1, _xy2) _star_pens = [ QPen(QColor('#ffffff'), _size, Qt.SolidLine) for _size in [1, 2, 3, 4] ] for _i, (_x, _y) in enumerate(self._stars): _xy = QPoint(_x, _y) painter.setPen(_star_pens[_i % len(_star_pens)]) painter.drawPoint(_xy) painter.end() self._galaxy.save(IMAGE_GALAXY_PATH) self.is_set = True def paint(self, painter: QPainter, model: BaseModel = None): _xy = self.transform(-self._galaxy.width() // 2, self._galaxy.height() // 2, is_point=True) painter.drawPixmap(_xy, self._galaxy)
def drawHeader(self): """Draw logo/copyright in the header""" pHeight = 90 pMargin = 15 icon_path = cm.DIR_ICONS + "app.png" self.header_lbl.setMinimumHeight(pHeight) self.header_lbl.setFrameShape(QFrame.StyledPanel) self.header_lbl.setContentsMargins(0, 0, 0, 0) pixmap = QPixmap(450, pHeight) pixmap.fill(Qt.transparent) iconY = (pHeight - 64) / 2 logoRect = QRect(pMargin, iconY, 64, 64) painter = QPainter(pixmap) painter.setBrush(QBrush(Qt.red)) painter.drawPixmap( logoRect, QPixmap(icon_path).scaled( logoRect.width(), logoRect.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation, ), ) titleRect = QRect(logoRect.right() + 10, iconY, 200, pHeight) font = QFont() font.setBold(True) font.setPixelSize(16) painter.setFont(font) painter.setPen(QPen(QApplication.instance().palette().text().color())) painter.drawText(titleRect, Qt.AlignTop, "Cutevariant") font_metrics = QFontMetrics(font) font.setBold(False) font.setPixelSize(12) painter.setFont(font) painter.setPen(QPen(Qt.darkGray)) titleRect.setY(titleRect.y() + font_metrics.height()) painter.drawText( titleRect, Qt.AlignTop, f"Version %s\nGPL3 Copyright (C) 2018-2020\nLabsquare.org" % __version__, ) self.header_lbl.setPixmap(pixmap) # Painting is finished ! # Avoid Segfault: # QPaintDevice: Cannot destroy paint device that is being painted painter.end()
def create_pixmap(self, transparent=False): w = self.byte_advance * 64 h = self.byte_rect.height() * 64 pixmap = QPixmap(w, h) if transparent: pixmap.fill(Qt.transparent) return pixmap
def view_Clear(self): try: clear = QPixmap(1, 1) clear.fill(QColor("white")) clear = QGraphicsPixmapItem(clear) scene = QGraphicsScene() scene.addItem(clear) return scene except: pass
def _make_icon(self, i=None): if not self._ranked: return None pixmap = QPixmap(16, 16) pixmap.fill(Qt.white) if i is not None: painter = QPainter(pixmap) painter.drawText(0, 0, 16, 16, Qt.AlignCenter, str(i)) painter.end() return QIcon(pixmap)
def pix_add_blurry(pix, transparency: float): temp_pix = QPixmap(pix.size()) temp_pix.fill(Qt.transparent) painter = QPainter(temp_pix) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.drawPixmap(0, 0, pix) painter.setCompositionMode(QPainter.CompositionMode_DestinationIn) painter.fillRect(temp_pix.rect(), QColor(0, 0, 0, int(255 * transparency))) painter.end() return temp_pix
def color_icon(cls, color): """ Creates a one-color QIcon from (R, G, B) tuple """ r, g, b = color qcolor = QColor(r, g, b) pixmap = QPixmap(cls.ICON_SIZE, cls.ICON_SIZE) pixmap.fill(qcolor) icon = QIcon(pixmap) return icon
def __tab_color_changed(self, index, color): nodes_window = self.widget(index) if not nodes_window: return nodes_window.color_identifier = color square_pixmap = QPixmap(16, 16) square_pixmap.fill(nodes_window.color_identifier) self.setTabIcon(index, QIcon(square_pixmap))
def slotPrintPreview(self): pix = QPixmap(1000, 200) pix.fill(Qt.white) painter = QPainter(pix) view.print(painter, pix.rect()) painter.end() label = QLabel(this) label.setPixmap(pix) label.show()
def __load_svg(self, svg_file: str) -> QPixmap: """Loads a SVG file and scales it correctly for High-DPI screens""" svg_renderer = QSvgRenderer(svg_file) pixmap = QPixmap(svg_renderer.defaultSize() * self.devicePixelRatio()) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) svg_renderer.render(painter) painter.end() pixmap.setDevicePixelRatio(self.devicePixelRatio()) return pixmap
def createColorToolButtonIcon(icon, color): pixmap = QPixmap(50, 80) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) image = icon.pixmap(QSize(50, 80)) target = QRect(0, 0, 50, 60) source = QRect(0, 0, 42, 42) painter.fillRect(QRect(0, 60, 50, 80), color) painter.drawPixmap(target, image, source) painter.end() return QIcon(pixmap)
def __init__(self, color: QColor): super(ColorSquare, self).__init__() self.color = color color_square = QPixmap(self.square_size) color_square.fill(color) self.setPixmap(color_square) self.setFrameShape(QFrame.Box) self.setLineWidth(1)
def show_label_img(self, do_roate=False, do_roate_img=False, do_roate_mask=False, do_clear=False): if not self.all_img_file: return img_path = self.all_img_file[self.all_img_file_index] img = QPixmap(str(img_path)) img_mask_path = img_path.parent.joinpath(f'mask/{img_path.stem}.bmp') img_mask_path.parent.mkdir(parents=True, exist_ok=True) if img_mask_path.is_dir(): QMessageBox.warning( self, '<致命错误>', f'标注文件<{img_mask_path}>是一个目录, 请把它拷贝到别的地方, 然后重新打开标注工具!!!', QMessageBox.Ok) sys.exit(-1) if img_mask_path.exists(): img_mask = QPixmap(str(img_mask_path)) if img_mask.size() != self.mask_img_size: os.remove(str(img_mask_path)) if not img_mask_path.exists() or do_clear: img_mask = QPixmap(self.mask_img_size) img_mask.fill(QColor(0, 0, 0)) img_mask.save(str(img_mask_path)) if do_roate: rm = QMatrix() rm.rotate(90) img = img.transformed(rm) img.save(str(img_path)) img_mask = img_mask.transformed(rm) img_mask.save(str(img_mask_path)) if do_roate_img: rm = QMatrix() rm.rotate(90) img = img.transformed(rm) img.save(str(img_path)) if do_roate_mask: rm = QMatrix() rm.rotate(90) img_mask = img_mask.transformed(rm) img_mask.save(str(img_mask_path)) self.label_img.update_label_img(img, img_mask, str(img_mask_path))
def createDropTextPixmap(self): pixmap = QPixmap(481, 300) pixmap.fill(QColor("#333333")) painter = QPainter(pixmap) font = QFont("Arial") font.setPixelSize(28) font.setBold(True) fm = QFontMetrics(font) painter.setFont(font) painter.setPen(QPen(QColor("#888888"), 1)) text = "Drop the tileset image here" x = (pixmap.width()-fm.width(text))/2 y = (pixmap.height()+fm.height())/2 painter.drawText(x, y, text) del painter return pixmap
class QPixmapQDatastream(UsesQApplication): '''QDataStream <<>> QPixmap''' def setUp(self): super(QPixmapQDatastream, self).setUp() self.source_pixmap = QPixmap(100, 100) self.source_pixmap.fill(Qt.red) self.output_pixmap = QPixmap() self.buffer = QByteArray() self.read_stream = QDataStream(self.buffer, QIODevice.ReadOnly) self.write_stream = QDataStream(self.buffer, QIODevice.WriteOnly) def testStream(self): self.write_stream << self.source_pixmap self.read_stream >> self.output_pixmap image = self.output_pixmap.toImage() pixel = image.pixel(10,10) self.assertEqual(pixel, QColor(Qt.red).rgba()) self.assertEqual(self.source_pixmap.toImage(), self.output_pixmap.toImage())