def get_color(cls, preset=None, allow_alpha: bool = False, parent=None) -> gui.Color: if isinstance(preset, str): preset = gui.Color(preset) if preset is None: preset = gui.Color() kwargs = dict(options=cls.ShowAlphaChannel) if allow_alpha else dict() return gui.Color(cls.getColor(preset, parent, **kwargs))
def __init__(self, parent=None): super().__init__(parent) self.rules = [] self.commentStart = core.RegExp("#") self.commentEnd = core.RegExp("\n|\r") self.commentFormat = gui.TextCharFormat() self.commentFormat.setFontItalic(True) self.commentFormat.set_foreground_color("darkgray") f = gui.TextCharFormat() r = core.RegExp() r.setMinimal(True) f.setFontWeight(gui.Font.Normal) f.set_foreground_color("blue") tag_list = ["\\btrue\\b", "\\bfalse\\b"] for tag in tag_list: r.setPattern(tag) self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setForeground(gui.Color(127, 64, 127)) r.setPattern(r"\\d+") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkblue") r.setPattern(r"^\s*[_.\w]*\s*:") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkblue") r.setPattern(r":\s*:[_\.\w]*$|:\s*\@[_\.\w]*$") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setFontWeight(gui.Font.Bold) f.set_foreground_color("darkred") r.setPattern(r"^\s*-") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkred") r.setPattern(r"^---$") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkgreen") r.setPattern(r"[\[\]\{\}\,]") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setFontWeight(gui.Font.Normal) f.set_foreground_color("magenta") r.setPattern(r"\".*\"|\'.*\'") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setForeground(gui.Color(127, 64, 127)) r.setPattern(r"\\$\\(.*\\)") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("lightgray") r.setPattern(r"<!DOCTYPE.*>") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) r.setPattern(r"<\\?xml.*\\?>") self.rules.append((core.RegExp(r), gui.TextCharFormat(f)))
class Number(Rule): regex = [ r"\b[+-]?[0-9]+[lL]?\b", r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b", r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b", ] color = gui.Color(100, 150, 190)
def paintEvent(self, event): painter = gui.Painter(self) painter.use_antialiasing() painter.set_pen("none") painter.set_transparent_background(False) painter.set_transparent_background(True) painter.set_brush(gui.Brush()) with painter.paint_on(widgets.Widget()): pass painter.set_brush(gui.Color("red")) painter.fill_rect((0, 1, 3, 5), "transparent") painter.fill_rect(core.Rect(), "transparent") with pytest.raises(InvalidParamError): painter.fill_rect(core.Rect(), "transparent", "test") with pytest.raises(ValueError): painter.fill_rect(core.Rect(), "testus") painter.set_color("black") painter.set_composition_mode("source_atop") painter.get_composition_mode() == "source_atop" with pytest.raises(InvalidParamError): painter.set_composition_mode("test") painter.set_clip_path(gui.PainterPath(), "replace") with pytest.raises(InvalidParamError): painter.set_clip_path(gui.PainterPath(), "test") with pytest.raises(InvalidParamError): painter.set_pen(style="test") with painter.backup_state(): pass assert painter.get_text_rect("test") is not None
def serialize_fields(self): offset = self.offset() return dict( blur_radius=self.blurRadius(), color=gui.Color(self.color()), offset=(offset.x(), offset.y()), )
def test_colordialog(): dlg = widgets.ColorDialog() assert str(dlg.current_color()) == str(gui.Color("white")) with open("data.pkl", "wb") as jar: pickle.dump(dlg, jar) with open("data.pkl", "rb") as jar: dlg = pickle.load(jar)
def test_spanslider(qtbot, qttester): slider = custom_widgets.SpanSlider() qtbot.add_widget(slider) slider.show() slider.set_lower_value(10) slider.set_upper_value(20) slider.set_lower_pos(15) slider.set_lower_pos(15) slider.set_upper_pos(25) slider.set_upper_pos(25) assert slider.lower_value == 15 assert slider.upper_value == 25 slider.set_value((16, 24)) assert slider.get_value() == (16, 24) slider.set_lower_value(12) slider.set_upper_pos(20) color = gui.Color("blue") slider.set_left_color(color) slider.set_right_color(color) slider._swap_controls() slider.trigger_action(slider.SliderAction.SliderNoAction, True) slider.trigger_action(slider.SliderAction.SliderSingleStepAdd, True) slider.repaint() slider._pixel_pos_to_value(100) slider._move_pressed_handle() qttester.send_mousepress(slider, QtCore.Qt.MouseButton.LeftButton) qttester.send_mousemove(slider, core.Point(20, 20)) qttester.send_mousemove(slider, core.Point(0, 0), delay=10) assert slider.get_movement_mode() == "no_crossing" slider.set_movement_mode("no_overlap") slider.close()
def test_color(): color = gui.Color() color.set_color("gray") with open("data.pkl", "wb") as jar: pickle.dump(color, jar) with open("data.pkl", "rb") as jar: color = pickle.load(jar) assert str(color) == "#808080"
def set_color(self, color): if isinstance(color, str): self.current_color = gui.Color(color) else: self.current_color = color self.lineedit.set_text(self.current_color.name().upper()) icon = gui.Icon.for_color(self.current_color) self.button.set_icon(icon)
def set_text(self, text, color="black", h_align="center", v_align="bottom"): self.showMessage(text, color=gui.Color(color), alignment=H_ALIGNMENTS[h_align] | V_ALIGNMENTS[v_align])
def _check_selection(self, x: int): # Check if user clicked in video sample for sample in self.video_samples: if sample.start_pos < x < sample.end_pos: sample.color = gui.Color(PEN_COLOR) if self.selected_sample is not sample: self.selected_sample = sample self.selection_changed.emit(sample) else: sample.color = sample.def_color
def fill_rect(self, rect, color, pattern="solid"): if isinstance(rect, tuple): rect = core.Rect(*rect) if isinstance(color, str): if color not in gui.Color.colorNames(): raise ValueError("Invalid value for color.") color = gui.Color(color) if pattern != "solid": color = gui.Brush(color, PATTERNS[pattern]) self.fillRect(rect, color)
def test_colorchooserbutton(): btn = custom_widgets.ColorChooserButton() btn.set_color("green") with open("data.pkl", "wb") as jar: pickle.dump(btn, jar) with open("data.pkl", "rb") as jar: btn = pickle.load(jar) repr(btn) assert btn.get_value() == gui.Color("green") btn.set_value("blue") assert btn.is_valid()
def test_palette(): pal = gui.Palette() assert len(pal.get_colors()) == 21 assert len(pal.get_brushes()) == 21 color = gui.Color("red") pal.set_brush("window", "red") assert pal.get_brush("window") == color pal.highlight_inactive() pal.set_color("window", "red") pal["button"] = color assert pal["button"] == color bytes(pal)
def set_text( self, text: str, color: types.ColorType = "black", h_align: constants.HorizontalAlignmentStr = "center", v_align: constants.VerticalAlignmentStr = "bottom", ): self.showMessage( text, color=gui.Color(color), alignment=constants.H_ALIGNMENT[h_align] | constants.V_ALIGNMENT[v_align], )
def paint(self, painter, option, widget): path = QtGui.QPainterPath() path.addRoundedRect(self.rect, 5, 5) anchor = self.mapFromParent(self.chart.mapToPosition(self.anchor)) if not self.rect.contains(anchor): point1 = QtCore.QPointF() point2 = QtCore.QPointF() # establish the position of the anchor point in relation to self.rect above = anchor.y() <= self.rect.top() above_center = self.rect.top() < anchor.y() <= self.rect.center( ).y() below_center = self.rect.center().y() < anchor.y( ) <= self.rect.bottom() below = anchor.y() > self.rect.bottom() on_left = anchor.x() <= self.rect.left() left_of_center = self.rect.left() < anchor.x() <= self.rect.center( ).x() right_of_center = self.rect.center().x() < anchor.x( ) <= self.rect.right() on_right = anchor.x() > self.rect.right() # get the nearest self.rect corner. x = (on_right + right_of_center) * self.rect.width() y = (below + below_center) * self.rect.height() corner_case = (above and on_left) or (above and on_right) or ( below and on_left) or (below and on_right) vertical = abs(anchor.x() - x) > abs(anchor.y() - y) x1 = x + left_of_center * 10 - right_of_center * 20 + \ corner_case * (not vertical) * (on_left * 10 - on_right * 20) y1 = y + above_center * 10 - below_center * 20 + \ corner_case * vertical * (above * 10 - below * 20) point1.setX(x1) point1.setY(y1) x2 = x + left_of_center * 20 - right_of_center * 10 + \ corner_case * (not vertical) * (on_left * 20 - on_right * 10) y2 = y + above_center * 20 - below_center * 10 + \ corner_case * vertical * (above * 20 - below * 10) point2.setX(x2) point2.setY(y2) path.moveTo(point1) path.lineTo(anchor) path.lineTo(point2) path = path.simplified() painter.setBrush(gui.Color(255, 255, 255)) painter.drawPath(path) painter.drawText(self.text_rect, self.text)
def get_color(color: types.ColorType) -> gui.Color: """Get gui.Color instance for given parameter. named colors are 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'transparent', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen' Args: color (ColorType): color to create gui.Icon from Returns: gui.Color: color instance """ if isinstance(color, (tuple, list)): return gui.Color(*color) return gui.Color(color)
def highlight_current_line(self): extra_selections = [] if not self.isReadOnly(): selection = widgets.TextEdit.ExtraSelection() line_color = gui.Color("yellow").lighter(160) selection.format.setBackground(line_color) selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True) selection.cursor = self.textCursor() selection.cursor.clearSelection() extra_selections.append(selection) self.setExtraSelections(extra_selections)
def create_dark_palette(cls) -> Palette: pal = cls() pal.set_color("window", gui.Color(53, 53, 53)) pal.set_color("window_text", "white") pal.set_color("window_text", "grey", group="disabled") pal.set_color("base", gui.Color(25, 25, 25)) pal.set_color("alternate_base", gui.Color(53, 53, 53)) pal.set_color("tool_tip_base", "slategrey") pal.set_color("tool_tip_base", "slategrey", group="inactive") pal.set_color("tool_tip_text", "white") pal.set_color("tool_tip_text", "white", group="inactive") pal.set_color("text", "white") pal.set_color("text", "grey", group="disabled") pal.set_color("button", gui.Color(53, 53, 53)) pal.set_color("button_text", "white") pal.set_color("button_text", "grey", group="disabled") pal.set_color("bright_text", "red") pal.set_color("link", "dodgerblue") pal.set_color("highlight", "dodgerblue") pal.set_color("highlight", gui.Color(80, 80, 80), group="disabled") pal.set_color("highlighted_text", "black") pal.set_color("highlighted_text", "grey", group="disabled") return pal
def create_dot(cls, color: types.ColorType = "black", size: int = 16) -> Pixmap: col = colors.get_color(color) px = cls(size, size) px.fill(QtCore.Qt.GlobalColor.transparent) # type: ignore px_size = px.rect().adjusted(1, 1, -1, -1) with gui.Painter(px) as painter: painter.use_antialiasing() painter.setBrush(col) pen_color = gui.Color(15, 15, 15) painter.set_pen(color=pen_color, width=1) painter.drawEllipse(px_size) return px
def __init__( self, color: types.ColorType = None, parent: QtWidgets.QWidget | None = None ): super().__init__(parent) layout = widgets.BoxLayout("horizontal", self) layout.set_margin(0) self.lineedit = widgets.LineEdit() self.lineedit.set_regex_validator(r"^#(?:[0-9a-fA-F]{6})$") layout.add(self.lineedit) action = widgets.Action(icon="mdi.format-color-fill") action.triggered.connect(self.choose_color) self.button = widgets.ToolButton() self.button.setDefaultAction(action) layout.add(self.button) self._current_color: gui.Color = gui.Color("white") if color is not None: self.set_current_color(color)
def current_line_color(self, count_distance, total_lines, trailFadePerc, min_opacity, colorinput): color = gui.Color(colorinput) if count_distance == 0: return color min_alpha_f = min_opacity / 100.0 dist_threshold = int( math.ceil((total_lines - 1) * trailFadePerc / 100.0)) if count_distance > dist_threshold: color.setAlphaF(min_alpha_f) else: alpha_diff = color.alphaF() - min_alpha_f gradient = alpha_diff / float(dist_threshold + 1) result_alpha = color.alphaF() - gradient * count_distance # If alpha is out of bounds, clip it. result_alpha = min(1.0, max(0.0, result_alpha)) color.setAlphaF(result_alpha) return color
def paint( self, painter: gui.Painter, rect: QtCore.QRect, mode: QtGui.QIcon.Mode, state: QtGui.QIcon.State, options: list[dict[str, Any]], ): color_str, char = COLOR_OPTIONS[state][mode] for opt in options: painter.save() color = gui.Color(opt[color_str]) painter.setPen(color) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason why the glyph size is smaller than the icon size is to # account for font bearing. draw_size = round(0.875 * rect.height() * opt["scale_factor"]) # Animation setup hook if (animation := opt.get("animation")) is not None: animation.setup(painter, rect) font = self.fonts[opt["prefix"]].get_font(draw_size) painter.setFont(font) if "offset" in opt: rect.translate( round(opt["offset"][0] * rect.width()), round(opt["offset"][1] * rect.height()), ) x_center = rect.width() * 0.5 y_center = rect.height() * 0.5 painter.translate(x_center, y_center) transform = gui.Transform() if opt.get("vflip") is True: transform.scale(1, -1) if opt.get("hflip") is True: transform.scale(-1, 1) if "rotated" in opt: transform.rotate(opt["rotated"]) painter.setTransform(transform, True) painter.translate(-x_center, -y_center) if (opacity := opt.get("opacity")) is not None: painter.setOpacity(opacity)
def __init__(self, parent, modality=QtCore.Qt.NonModal): super().__init__(parent=parent) # WAS IN initialize() self._color = gui.Color("black") self._roundness = 100.0 self._minimum_trail_opacity = 3.14159265358979323846 self._trail_fade_percentage = 80.0 self._revolutions_per_second = 1.57079632679489661923 self._line_num = 20 self._line_length = 10 self._line_width = 2 self._inner_radius = 10 self._current_counter = 0 self._is_spinning = False self._timer = core.Timer(self) self._timer.timeout.connect(self.rotate) self.update_size() self.update_timer() self.hide() # END initialize() self.setWindowModality(modality)
def _current_line_color( self, count_distance: int, total_lines: int, fade_perc: float, min_opacity: float, color: gui.Color, ) -> gui.Color: color = gui.Color(color) if count_distance == 0: return color min_alpha_f = min_opacity / 100 dist_threshold = int(math.ceil((total_lines - 1) * fade_perc / 100)) if count_distance > dist_threshold: color.setAlphaF(min_alpha_f) else: alpha = color.alphaF() alpha_diff = alpha - min_alpha_f gradient = alpha_diff / (dist_threshold + 1) result_alpha = alpha - gradient * count_distance # If alpha is out of bounds, clip it. result_alpha = min(1.0, max(0.0, result_alpha)) color.setAlphaF(result_alpha) return color
def test_spanslider(qtbot): slider = custom_widgets.SpanSlider() qtbot.addWidget(slider) slider.set_lower_value(10) slider.set_upper_value(20) slider.set_lower_pos(15) slider.set_upper_pos(25) assert slider.lower_value == 15 assert slider.upper_value == 25 slider.set_lower_value(12) slider.set_upper_pos(20) color = gui.Color("blue") slider.set_left_color(color) slider.set_right_color(color) slider.swap_controls() slider.trigger_action(slider.SliderNoAction, True) slider.trigger_action(slider.SliderSingleStepAdd, True) slider.paintEvent(None) slider.pixel_pos_to_value(100) slider.draw_span(gui.Painter(), core.Rect()) slider.move_pressed_handle() qtbot.mouseClick(slider, QtCore.Qt.LeftButton) qtbot.mouseMove(slider, core.Point(20, 20)) assert slider.movement_mode == "free"
def serialize_fields(self): return dict(strength=self.strength(), color=gui.Color(self.color()))
def get_color(self, role: RoleStr, group: GroupStr = "active") -> gui.Color: return gui.Color(self.color(GROUP[group], ROLE[role]))
def set_foreground_color(self, color_name): color = gui.Color() color.set_color(color_name) self.setForeground(color)
def set_color(self, color): if isinstance(color, str): color = gui.Color(color) self.setColor(color)