def _add_table(self, tab, cursor): fmt = QTextCharFormat() fmt.setFont(QFont(self.factory.font_name)) fmt.setFontPointSize(self.factory.font_size) bc = QColor(self.factory.bg_color) if self.factory.bg_color else None ec, oc, hc = bc, bc, bc if self.factory.even_color: ec = QColor(self.factory.even_color) if self.factory.odd_color: oc = QColor(self.factory.odd_color) if self.factory.header_color: hc = QColor(self.factory.header_color) with EditBlock(cursor): for i, row in enumerate(tab.items): cell = row.cells[0] if cell.bold: fmt.setFontWeight(QFont.Bold) else: fmt.setFontWeight(QFont.Normal) if i == 0 and hc: c = hc elif (i - 1) % 2 == 0: c = ec else: c = oc if c: fmt.setBackground(c) txt = ''.join([u'{{:<{}s}}'.format(cell.width).format(cell.text) for cell in row.cells ]) cursor.insertText(txt + '\n', fmt)
def _fade(self, lineno): cursor = self._get_line_cursor(lineno) fmt = cursor.charFormat() color=QColor('black') color.setAlphaF(0.5) fmt.setForeground(color) cursor.beginEditBlock() cursor.mergeCharFormat(fmt) cursor.endEditBlock()
def format(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
def _add_laser_logo(self, scene, bounding_rect, ex, ey, cx, cy, w, h): tw = w - 20 poly = QPolygon() poly.append(QPoint(cx - tw / 2, h - 10)) poly.append(QPoint(cx + tw / 2, h - 10)) poly.append(QPoint(cx, 10)) pen = QPen() pen.setWidth(5) # brush = QBrush() # brush.setStyle(Qt.SolidPattern) # brush.setColor(QColor(255, 255, 0)) item = scene.addPolygon(poly, pen=pen) item.setBrush(QColor(255, 255, 0)) item.setParentItem(bounding_rect) pen = QPen() pen.setWidth(3) item = scene.addLine(cx - 40, ey, cx, ey, pen=pen) item.setParentItem(bounding_rect) pen = QPen() pen.setColor(Qt.black) pen.setWidth(2) for l, n in ((25, 12), (17, 24)): s = 360 / n for theta in range(n): theta = math.radians(theta * s) x = l * math.cos(theta) y = l * math.sin(theta) ll = scene.addLine(ex, ey, ex + x, ey + y, pen=pen) ll.setParentItem(bounding_rect) return bounding_rect
def get_status_color(self, obj): c = QColor(Qt.white) if not isinstance(obj, Pipeline): c = QColor(Qt.lightGray) if not obj.enabled: c = QColor('lightblue') elif obj.visited: c = QColor(Qt.green) elif obj.active: c = QColor('orange') # if obj.status == 'ran': # c = QColor('green') # elif obj.status == 'paused': # c = QColor('orange') return c
def test_image_to_bitmap(self): qimage = QImage(32, 64, QImage.Format.Format_RGB32) qimage.fill(QColor(0x44, 0x88, 0xcc)) qpixmap = image_to_bitmap(qimage) self.assertIsInstance(qpixmap, QPixmap)
def __init__(self): super(QDiffConnector, self).__init__() self.color = QColor(0, 100, 0, 100) self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Ignored)) self.setFixedWidth(30)
def _create_control(self): ctrl = QGraphicsView() ctrl.setRenderHints(QPainter.Antialiasing) scene = QGraphicsScene() ctrl.setScene(scene) scene.setBackgroundBrush(QBrush(QColor(237, 237, 237))) ctrl.setStyleSheet("border: 0px") w, h = 150, 150 ctrl.setMinimumHeight(h + 22) ctrl.setMinimumWidth(w + 22) cx, cy = w / 2, h / 2. ex, ey = cx, cy + 20 pen = QPen() pen.setStyle(Qt.NoPen) # pen.setColor(QColor(237, 237, 237)) bounding_rect = scene.addRect(0, 0, w, h, pen=pen) bounding_rect.setFlag(QGraphicsItem.ItemClipsChildrenToShape) self.animation = QSequentialAnimationGroup() self._add_laser_logo(scene, bounding_rect, ex, ey, cx, cy, w, h) self._add_bullet(scene, bounding_rect, ex, ey, cx, cy) self._add_fragments(scene, bounding_rect, ex, ey) self.animation.setLoopCount(-1) return ctrl
def _get_text_color(self): r = self.color[:2] g = self.color[2:4] b = self.color[4:6] s = sum((int(r, 16), int(g, 16), int(b, 16))) c = 'white' if s < 256 else 'black' return QColor(c)
def update_editor(self, *args, **kw): ctrl = self.control if self.value: while 1: try: v, c, force, is_marker = self.value.get(timeout=0.01) except Empty: return fmt = ctrl.currentCharFormat() fmt.setForeground(QColor(c)) fmt.setFontPointSize(self.font_size) ctrl.setCurrentCharFormat(fmt) if is_marker: ov = v if self._nominal_character_width is None: self._calculate_nominal_character_width(ov, ctrl) v = ov * self._nominal_character_width if self._check_character_width(v, ctrl): self._calculate_nominal_character_width(ov, ctrl) v = ov * self._nominal_character_width ctrl.appendPlainText(v) ctrl.moveCursor(QTextCursor.End) ctrl.ensureCursorVisible()
def test_bitmap_to_icon(self): qpixmap = QPixmap(32, 64) qpixmap.fill(QColor(0x44, 0x88, 0xcc)) qimage = bitmap_to_icon(qpixmap) self.assertIsInstance(qimage, QIcon)
def get_background(self, obj): if isinstance(obj, Pipeline): c = QColor(Qt.white) else: if isinstance(obj, ReviewNode): if not obj.enabled: c = QColor('#ff8080') # light red else: c = QColor(Qt.cyan) elif obj.skip_configure: c = QColor('#D05BFF') elif not obj.enabled: c = QColor('#ff8080') # light red else: c = super(PipelineTreeNode, self).get_background(obj) return c
def update_editor(self, ): dim = self._dimension sp = self._spacing self._scene.clear() for r, v in enumerate(self.value.split('\n')): for c, vi in enumerate(v): rect = self._scene.addRect(c * (dim + sp), r * (dim + sp), dim, dim) if vi == '1': rect.setBrush(QColor(200, 0, 0))
def test_resize_image_smooth(self): qimage = QImage(32, 64, QImage.Format.Format_RGB32) qimage.fill(QColor(0x44, 0x88, 0xcc)) qimage = resize_image(qimage, (128, 128), mode=ScaleMode.smooth) self.assertIsInstance(qimage, QImage) self.assertEqual(qimage.width(), 128) self.assertEqual(qimage.height(), 128)
def test_resize_image_expand(self): qimage = QImage(32, 64, QImage.Format.Format_RGB32) qimage.fill(QColor(0x44, 0x88, 0xcc)) qimage = resize_image(qimage, (128, 128), AspectRatio.keep_expand) self.assertIsInstance(qimage, QImage) self.assertEqual(qimage.width(), 128) self.assertEqual(qimage.height(), 256)
def test_resize_bitmap_smooth(self): qpixmap = QPixmap(32, 64) qpixmap.fill(QColor(0x44, 0x88, 0xcc)) qpixmap = resize_bitmap(qpixmap, (128, 128), mode=ScaleMode.smooth) self.assertIsInstance(qpixmap, QPixmap) self.assertEqual(qpixmap.width(), 128) self.assertEqual(qpixmap.height(), 128)
def test_resize_bitmap_expand(self): qpixmap = QPixmap(32, 64) qpixmap.fill(QColor(0x44, 0x88, 0xcc)) qpixmap = resize_bitmap(qpixmap, (128, 128), AspectRatio.keep_expand) self.assertIsInstance(qpixmap, QPixmap) self.assertEqual(qpixmap.width(), 128) self.assertEqual(qpixmap.height(), 256)
def _set_text_highlighting(self, lines): has_deletion=False for idx, li in enumerate(lines): if li.startswith('-'): has_deletion=True a=li if has_deletion and li.startswith('+'): #find diff b=li for i, s in enumerate(ndiff(a,b)): if s[0] == ' ': continue elif s[0] == '-': if not s[-1] in ('-', '+'): self._set_diff(idx - 2, i, QColor(200,0, 0)) elif s[0] == '+': if not s[-1] in ('-','+'): self._set_diff(idx-1, i, QColor(0,200,0))
def _highlight(self, lineno, kind): if kind=='addition': color=QColor(225,254,229) #light green elif kind=='deletion': color=QColor(255, 228, 228) #light red selection = QTextEdit.ExtraSelection() selection.format.setBackground(color) selection.format.setProperty( QTextFormat.FullWidthSelection, True) ctrl = self.control doc = ctrl.document() block = doc.findBlockByLineNumber(lineno) pos = block.position() cursor = ctrl.textCursor() cursor.setPosition(pos) selection.cursor=cursor return selection
def paintEvent(self, evt): # print 'paint', self.color, self.text(), self.width(), self.height(), evt.rect().width() qp = QPainter() qp.begin(self) qp.setBrush(QColor('#{}'.format(self.color[:-2]))) qp.drawRect(0, 0, self.width(), self.height()) qp.end() qp.begin(self) qp.setPen(self._get_text_color()) qp.drawText(evt.rect(), QtCore.Qt.AlignCenter, self.text()) qp.end()
def test_image_to_array_rgba(self): qimage = QImage(32, 64, QImage.Format.Format_ARGB32) qimage.fill(QColor(0x44, 0x88, 0xcc, 0xee)) array = image_to_array(qimage) self.assertEqual(array.shape, (64, 32, 4)) self.assertEqual(array.dtype, np.dtype('uint8')) self.assertTrue(np.all(array[:, :, 0] == 0x44)) self.assertTrue(np.all(array[:, :, 1] == 0x88)) self.assertTrue(np.all(array[:, :, 2] == 0xcc)) self.assertTrue(np.all(array[:, :, 3] == 0xee))
def init(self, parent): """ """ self.control = lcd = QLCDNumber() lcd.setDigitCount(self.factory.ndigits) lcd.setSmallDecimalPoint(self.factory.use_small_decimal_point) lcd.setSegmentStyle(QLCDNumber.Flat) lcd.setStyleSheet('background-color:rgb(0,0,0)') lcd.setMinimumHeight(self.factory.height) lcd.setMinimumWidth(self.factory.width) palette = lcd.palette() palette.setColor(palette.Foreground, QColor('green')) lcd.setPalette(palette)
def init(self, parent): """ """ rad = self.factory.radius if not rad: rad = 20 if self.control is None: scene = QGraphicsScene() # system background color scene.setBackgroundBrush(QBrush(QColor(237, 237, 237))) x, y = 10, 10 cx = x + rad / DIAMETER_SCALAR cy = y + rad / DIAMETER_SCALAR self.colors = [QColor(ci) for ci in self.factory.colors] brush = get_gradient(self.colors[self.value], cx, cy, rad / 2) pen = QPen() pen.setWidth(0) self._led_ellipse = scene.addEllipse(x, y, rad, rad, pen=pen, brush=brush) ctrl = LEDGraphicsView(rad, scene) layout = QVBoxLayout() layout.addWidget(ctrl) layout.setAlignment(ctrl, Qt.AlignHCenter) if self.factory.label: txt = QLabel(self.factory.label) layout.addWidget(txt) layout.setAlignment(txt, Qt.AlignHCenter) self.control = QWidget() self.control.setLayout(layout)
def _add_bullet(self, scene, bounding_rect, ex, ey, cx, cy): pen = QPen() pen.setColor(QColor('orange')) pen.setWidth(1) bullet = scene.addRect(-16, ey - 5, 15, 10, pen=pen) bullet.setParentItem(bounding_rect) bullet.setBrush(Qt.black) self.animation_objects['bullet'] = w = Wrapper(bullet) anim = QPropertyAnimation(w, 'position') anim.setDuration(500) anim.setKeyValueAt(0, bullet.pos()) anim.setKeyValueAt(1, QPoint(cx + 10, 0)) self.animation.addAnimation(anim)
def rgba_to_toolkit_color(rgba): """ Convert an RGBA tuple to a QColor. Parameters ---------- rgba_tuple : tuple A tuple of 4 floating point values between 0.0 and 1.0 inclusive. Returns ------- qcolor : QColor A QColor object. """ values = channels_to_ints(rgba) return QColor(*values)
def _init_ui(self, txt): self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) pal = QPalette() color = QColor() color.setNamedColor(self._window_bgcolor) color.setAlpha(255 * self._opacity) pal.setColor(QPalette.Background, color) self.setAutoFillBackground(True) self.setPalette(pal) wm, hm = 5, 5 spacing = 8 layout = QVBoxLayout() layout.setSpacing(spacing) layout.setContentsMargins(wm, hm, wm, hm) nlines, ts = self._generate_text(txt) qlabel = QLabel('\n'.join(ts)) ss = 'QLabel {{color: {}; font-family:{}, sans-serif; font-size: {}px}}'.format(self._color, self._font, self._fontsize) qlabel.setStyleSheet(ss) layout.addWidget(qlabel) hlabel = QLabel('double click to dismiss') hlabel.setStyleSheet('QLabel {font-size: 10px}') hlayout = QHBoxLayout() hlayout.addStretch() hlayout.addWidget(hlabel) hlayout.addStretch() layout.addLayout(hlayout) self.setLayout(layout) font = QFont(self._font, self._fontsize) fm = QFontMetrics(font) pw = max([fm.width(ti) for ti in ts]) ph = (fm.height() + 2) * nlines w = pw + wm * 2 h = ph + (hm + spacing + 1) * 2 self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setFixedWidth(w) self.setFixedHeight(h) self.setMask(mask(self.rect(), 10))
def paintEvent(self, event): qp = QPainter() qp.begin(self) c = QColor() c.setNamedColor(self._window_bgcolor) h, s, l, a = c.getHsl() c.setHsl(h, s, 100, a) pen = QPen(c, 8, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawRoundedRect(event.rect(), 12, 12) qp.end()
def highlight(self, ctrl, lineno): selection = QTextEdit.ExtraSelection() selection.cursor = ctrl.textCursor() selection.format.setBackground(QColor(100, 200, 100)) selection.format.setProperty( QTextFormat.FullWidthSelection, True) doc = ctrl.document() block = doc.findBlockByLineNumber(lineno) selection.cursor.setPosition(block.position()) ss = ctrl.extraSelections() ss.append(selection) ctrl.setExtraSelections(ss) selection.cursor.clearSelection()
def _create_control(self): ctrl = QGraphicsView() scene = QGraphicsScene() ctrl.setScene(scene) scene.setBackgroundBrush(QBrush(QColor(237, 237, 237))) ctrl.setStyleSheet("border: 0px") md = self._dimension * 3 + self._spacing * 4 ctrl.setMaximumWidth(md) ctrl.setMaximumHeight(md) layout = QVBoxLayout() layout.addWidget(ctrl) self._scene = scene self.control = QWidget() self.control.setLayout(layout)
def paintEvent(self, event): painter = QtGui.QPainter(self) painter.setFont(self.font) # painter.setPen(QColor(200, 0, 100))#light grey painter.fillRect(event.rect(), self.background_color) p=QPen() p.setColor(QColor(100,100,100)) painter.setPen(p) rect=event.rect() rect.adjust(0,-1, self.adjust_width,1) painter.drawRect(rect) cw = self.parent() block = cw.firstVisibleBlock() blocknum = block.blockNumber() top = cw.blockBoundingGeometry(block).translated( cw.contentOffset()).top() bottom = top + int(cw.blockBoundingRect(block).height()) lineno=self.start while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): if blocknum>0: text=block.text() if not text.startswith(self.anti_tag): painter.drawText(0, top, self.width() - 2, self.fontMetrics().height(), QtCore.Qt.AlignRight, str(lineno)) lineno+=1 else: painter.drawText(0, top, self.width() - 2, self.fontMetrics().height(), QtCore.Qt.AlignRight, '...') block = next(block) top = bottom bottom = top + int(cw.blockBoundingRect(block).height()) blocknum += 1