def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Set the default font font = gui.Font("Consolas") self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers self.setMarginWidth(0, font.metrics.horizontalAdvance("00000") + 6) self.setMarginLineNumbers(0, True) self.set_margins_background_color("lightgrey") # Clickable margin 1 for showing markers # self.setMarginSensitivity(1, True) # self.marginClicked.connect(self.on_margin_clicked) # self.define_marker("right_arrow", ARROW_MARKER_NUM) # self.set_marker_background_color("red", ARROW_MARKER_NUM) self.set_brace_matching("sloppy") self.highlight_current_line() # Don't want to see the horizontal scrollbar at all # Use raw message to Scintilla here (all messages are documented # here: http://www.scintilla.org/ScintillaDoc.html) # self.SendScintilla(Qsci.QsciScintilla.SCI_SETHSCROLLBAR, 0) self.SendScintilla(self.SCI_SETSCROLLWIDTHTRACKING, True) self.SendScintilla(self.SCI_SETSCROLLWIDTH, 5) self.language = None self._lexer = None
def test_standarditem(): item = gui.StandardItem() with open("data.pkl", "wb") as jar: pickle.dump(item, jar) with open("data.pkl", "rb") as jar: item = pickle.load(jar) # item[constants.USER_ROLE] = "test" # assert item[constants.USER_ROLE] == "test" item.set_icon("mdi.timer") item.set_checkstate("unchecked") with pytest.raises(InvalidParamError): item.set_checkstate("test") assert item.get_checkstate() == "unchecked" item.get_background() item.get_foreground() item.get_font() item.get_icon() bytes(item) item.clone() item.add_item( "Test", icon="mdi.timer", data={1: "Test"}, foreground=gui.Brush(), background=gui.Brush(), font=gui.Font(), selectable=True, status_tip="test", tool_tip="test", whats_this="test", checkstate="unchecked", size_hint=core.Size(10, 10), is_user_type=True, )
def test_standarditemmodel(): model = gui.StandardItemModel() model.add("test") for item in model: pass with open("data.pkl", "wb") as jar: pickle.dump(model, jar) with open("data.pkl", "rb") as jar: model = pickle.load(jar) model += gui.StandardItem("Item") model[0] assert len(model.find_items("test")) == 1 with pytest.raises(InvalidParamError): model.find_items("test", mode="wrong_mode") del model[0] model.add_item( "Test", icon="mdi.timer", data={1: "Test"}, foreground=gui.Brush(), background=gui.Brush(), font=gui.Font(), selectable=True, status_tip="test", tool_tip="test", whats_this="test", checkstate="unchecked", size_hint=core.Size(10, 10), is_user_type=True, )
def test_font(): font = gui.Font("Consolas") font.metrics font = gui.Font.mono() with pytest.raises(InvalidParamError): font.set_style_hint("test") font.set_style_hint("monospace") font.set_weight("thin") with pytest.raises(InvalidParamError): font.set_weight("test") assert font.get_weight() == "thin" font.set_capitalization("small_caps") with pytest.raises(InvalidParamError): font.set_capitalization("test") assert font.get_capitalization() == "small_caps" font.set_style("oblique") with pytest.raises(InvalidParamError): font.set_style("test") assert font.get_style() == "oblique" font.set_hinting_preference("vertical") with pytest.raises(InvalidParamError): font.set_hinting_preference("test") assert font.get_hinting_preference() == "vertical" font.set_letter_spacing("absolute", 20) with pytest.raises(InvalidParamError): font.set_letter_spacing("test", 20) assert font.get_letter_spacing_type() == "absolute"
def set_font(self, font_name: str, font_size: int = -1, weight: int = -1, italic: bool = False): font = gui.Font(font_name, font_size, weight, italic) self.setFont(font)
def test_fontmetricsf(): font = gui.Font("Consolas") fontmetrics = gui.FontMetricsF(font) val = fontmetrics.elided_text("This is a test", mode="right", width=40) with pytest.raises(InvalidParamError): val = fontmetrics.elided_text("This is a test", mode="test", width=40) assert len(val) < 10 fontmetrics.get_bounding_rect("test") fontmetrics.get_tight_bounding_rect("test")
def set_font(self, font_name: Optional[str] = None, font_size: int = -1, weight: int = -1, italic: bool = False) -> gui.Font: if font_name is None: font_name = self.font().family() font = gui.Font(font_name, font_size, weight, italic) self.setFont(font) return font
def __getstate__(self): return dict(text=self.text(), enabled=self.isEnabled(), tooltip=self.toolTip(), statustip=self.statusTip(), font=gui.Font(self.font()), validator=self.validator(), max_length=self.maxLength(), read_only=self.isReadOnly(), input_mask=self.inputMask(), has_frame=self.hasFrame(), placeholder_text=self.placeholderText())
def set_font( self, font_name: str | None = None, font_size: int | None = None, weight: int | None = None, italic: bool = False, ) -> gui.Font: if font_size is None: font_size = -1 if weight is None: weight = -1 if font_name is None: font_name = self.font().family() font = gui.Font(font_name, font_size, weight, italic) self.setFont(font) return font
def test_sciscintilla(qtbot): from prettyqt import gui, scintilla widget = scintilla.SciScintilla() widget.define_marker("circle", 0) with pytest.raises(InvalidParamError): widget.define_marker("test", 0) widget.set_marker_background_color("red", 0) widget.set_margins_background_color("green") widget.highlight_current_line("blue") widget.set_brace_matching("sloppy") with pytest.raises(InvalidParamError): widget.set_brace_matching("test") widget.set_text("test") assert widget.get_value() == "test" widget.set_syntaxhighlighter("python") widget.scroll_to_bottom() widget.append_text("test", newline=False) assert widget.text() == "testtest" widget.append_text("test", newline=True) assert widget.text() == "testtest\ntest" widget.set_font(gui.Font("Consolas")) widget.set_read_only() widget.set_value("test")
from __future__ import annotations from prettyqt import constants, core, gui, iconprovider, widgets from prettyqt.qt import QtCore, QtGui from prettyqt.utils import colors, helpers, types TEXT_COLOR = gui.Color("lightgray") BACKGROUND_COLOR = gui.Color("dimgrey") PEN_COLOR = "cyan" FONT = gui.Font("Decorative", 10) class VideoSample: def __init__( self, duration: float, color: types.ColorType = "yellow", picture: QtGui.QPixmap | None = None, ): self.duration = duration self.color = colors.get_color(color) # Floating color self.def_color = colors.get_color(color) # DefaultColor self.picture = None if picture is None else picture.scaledToHeight(45) self.start_pos = 0.0 # Initial position self.end_pos = self.duration # End position class Timeline(widgets.Widget): position_changed = core.Signal(int)
def __getstate__(self): return dict(text=self.text(), enabled=self.isEnabled(), read_only=self.isReadOnly(), font=gui.Font(self.font()))
def get_font(self) -> gui.Font: return gui.Font(self.font())
def __init__(self, obj, name: str = ""): super().__init__() self.set_title("Object browser") self._instance_nr = self._add_instance() self.set_icon("mdi.language-python") self._attr_cols = DEFAULT_ATTR_COLS self._attr_details = DEFAULT_ATTR_DETAILS logger.debug("Reading model settings for window: %d", self._instance_nr) with core.Settings( settings_id=self._settings_group_name("model")) as settings: self._auto_refresh = settings.get("auto_refresh", False) self._refresh_rate = settings.get("refresh_rate", 2) show_callable_attrs = settings.get("show_callable_attrs", True) show_special_attrs = settings.get("show_special_attrs", True) self._tree_model = objectbrowsertreemodel.ObjectBrowserTreeModel( obj, name, attr_cols=self._attr_cols) self._proxy_tree_model = objectbrowsertreemodel.ObjectBrowserTreeProxyModel( show_callable_attrs=show_callable_attrs, show_special_attrs=show_special_attrs, ) self._proxy_tree_model.setSourceModel(self._tree_model) # self._proxy_tree_model.setSortRole(RegistryTableModel.SORT_ROLE) self._proxy_tree_model.setDynamicSortFilter(True) # self._proxy_tree_model.setSortCaseSensitivity(Qt.CaseInsensitive) # Views self._setup_actions() self.central_splitter = widgets.Splitter( parent=self, orientation=constants.VERTICAL) self.setCentralWidget(self.central_splitter) # Tree widget self.obj_tree = widgets.TreeView() self.obj_tree.setRootIsDecorated(True) self.obj_tree.setAlternatingRowColors(True) self.obj_tree.set_model(self._proxy_tree_model) self.obj_tree.set_selection_behaviour("rows") self.obj_tree.setUniformRowHeights(True) self.obj_tree.setAnimated(True) # Stretch last column? # It doesn't play nice when columns are hidden and then shown again. self.obj_tree.h_header.set_id("table_header") self.obj_tree.h_header.setSectionsMovable(True) self.obj_tree.h_header.setStretchLastSection(False) self.central_splitter.addWidget(self.obj_tree) # Bottom pane bottom_pane_widget = widgets.Widget() bottom_pane_widget.set_layout("horizontal", spacing=0, margin=5) self.central_splitter.addWidget(bottom_pane_widget) group_box = widgets.GroupBox("Details") bottom_pane_widget.box.addWidget(group_box) group_box.set_layout("horizontal", margin=2) # Radio buttons radio_widget = widgets.Widget() radio_widget.set_layout("vertical", margin=0) self.button_group = widgets.ButtonGroup(self) for button_id, attr_detail in enumerate(self._attr_details): radio_button = widgets.RadioButton(attr_detail.name) radio_widget.box.addWidget(radio_button) self.button_group.addButton(radio_button, button_id) self.button_group.buttonClicked.connect(self._change_details_field) self.button_group.button(0).setChecked(True) radio_widget.box.addStretch(1) group_box.box.addWidget(radio_widget) # Editor widget font = gui.Font("Courier") font.setFixedPitch(True) # font.setPointSize(14) self.editor = widgets.PlainTextEdit() self.editor.setReadOnly(True) self.editor.setFont(font) group_box.box.addWidget(self.editor) # Splitter parameters self.central_splitter.setCollapsible(0, False) self.central_splitter.setCollapsible(1, True) self.central_splitter.setSizes([400, 200]) self.central_splitter.setStretchFactor(0, 10) self.central_splitter.setStretchFactor(1, 0) selection_model = self.obj_tree.selectionModel() selection_model.currentChanged.connect(self._update_details) menubar = self.menuBar() file_menu = menubar.add_menu("&File") file_menu.addAction("C&lose", self.close, "Ctrl+W") file_menu.addAction("E&xit", lambda: widgets.app().closeAllWindows(), "Ctrl+Q") view_menu = menubar.add_menu("&View") view_menu.addAction("&Refresh", self._tree_model.refresh_tree, "Ctrl+R") view_menu.addAction(self.toggle_auto_refresh_action) view_menu.addSeparator() self.show_cols_submenu = widgets.Menu("Table columns") view_menu.add_menu(self.show_cols_submenu) actions = self.obj_tree.h_header.get_header_actions() self.show_cols_submenu.add_actions(actions) view_menu.addSeparator() view_menu.addAction(self.toggle_callable_action) view_menu.addAction(self.toggle_special_attribute_action) assert self._refresh_rate > 0 self._refresh_timer = core.Timer(self) self._refresh_timer.setInterval(self._refresh_rate * 1000) self._refresh_timer.timeout.connect(self._tree_model.refresh_tree) # Update views with model self.toggle_special_attribute_action.setChecked(show_special_attrs) self.toggle_callable_action.setChecked(show_callable_attrs) self.toggle_auto_refresh_action.setChecked(self._auto_refresh) # Select first row so that a hidden root node will not be selected. first_row_index = self._proxy_tree_model.first_item_index() self.obj_tree.setCurrentIndex(first_row_index) if self._tree_model.inspected_node_is_visible: self.obj_tree.expand(first_row_index)
def current_font(self) -> gui.Font: return gui.Font(self.currentFont())
def edit_font(self) -> Iterator[gui.Font]: font = gui.Font(self.font()) yield font self.setFont(font)
def get_font(self, size: float) -> gui.Font: font = gui.Font(self.font_name) font.setPixelSize(round(size)) if self.stylename: # solid style font.setStyleName(self.stylename) return font
def get_font(self, column: int = 0) -> gui.Font: return gui.Font(self.font(column))
def set_current_font(self, font: str | QtGui.QFont): if isinstance(font, str): self._current_font = gui.Font(font) else: self._current_font = font self.lineedit.setText(self._current_font.family())
def get_title_font(self) -> gui.Font: return gui.Font(self.titleFont())
def get_label_font(self) -> gui.Font: return gui.Font(self.labelFont())
def get_font(cls) -> gui.Font: return gui.Font(cls.font())
def test_fontinfo(): font = gui.Font("Consolas") fontinfo = gui.FontInfo(font) assert fontinfo.get_style_hint() == "any"
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.anchor = QtCore.QPointF() self.text = None self.text_rect = None self.font = gui.Font()
def get_default_font(self) -> gui.Font: return gui.Font(self.defaultFont())
raise ValueError("Invalid echo mode") self.setEchoMode(ECHO_MODES[mode]) def get_echo_mode(self) -> str: """returns echo mode possible values are "normal", "no_echo", "password", "echo_on_edit" Returns: echo mode """ return ECHO_MODES.inv[self.echoMode()] def set_value(self, value: str): self.setText(value) def get_value(self) -> str: return self.text() def is_valid(self) -> bool: return self.hasAcceptableInput() if __name__ == "__main__": app = widgets.app() widget = LineEdit("This is a test") widget.set_regex_validator("[0-9]+") widget.setFont(gui.Font("Consolas")) widget.show() app.exec_()
if item not in FONT_FILTERS: raise InvalidParamError(item, FONT_FILTERS) flags = helpers.merge_flags(filters, FONT_FILTERS) self.setFontFilters(flags) def get_font_filters(self) -> list[FontFilterStr]: """Return list of font filters. Returns: font filter list """ return [k for k, v in FONT_FILTERS.items() if v & self.fontFilters()] def set_value(self, value: QtGui.QFont): self.setCurrentFont(value) def get_value(self) -> gui.Font: return self.get_current_font() def get_current_font(self) -> gui.Font: return gui.Font(self.currentFont()) if __name__ == "__main__": app = widgets.app() widget = FontComboBox() widget.value_changed.connect(print) widget.set_value(gui.Font("Script")) widget.show() app.main_loop()
def font(self) -> gui.Font: return gui.Font(super().font())
def test_font(): font = gui.Font("Consolas") repr(font) font.metrics font = gui.Font.mono()