def paint( self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex, ): """Override to paint an icon based on given Pixmap / Color / Icon. Pixmap / Color / Icon must be set to 'QtCore.Qt.ItemDataRole.UserRole + 1000' Args: painter (QtGui.QPainter): painter to paint the icon option (QtWidgets.QStyleOptionViewItem): state of the item to be displayed index (QtCore.QModelIndex): index which gets decorated """ super().paint(painter, option, index) value = index.data(DecorationRole2) if not value: return margin = 10 mode = gui.Icon.Mode.Normal if not (option.state & widgets.Style.StateFlag.State_Enabled): mode = gui.Icon.Mode.Disabled elif option.state & widgets.Style.StateFlag.State_Selected: mode = gui.Icon.Mode.Selected if isinstance(value, QtGui.QPixmap): icon = QtGui.QIcon(value) option.decorationSize = int(value.size() / value.devicePixelRatio()) elif isinstance(value, QtGui.QColor): pixmap = QtGui.QPixmap(option.decorationSize) pixmap.fill(value) icon = QtGui.QIcon(pixmap) elif isinstance(value, QtGui.QImage): icon = QtGui.QIcon(QtGui.QPixmap.fromImage(value)) option.decorationSize = int(value.size() / value.devicePixelRatio()) elif isinstance(value, QtGui.QIcon): is_on = option.state & widgets.Style.StateFlag.State_Open state = gui.Icon.State.On if is_on else gui.Icon.State.Off actual_size = option.icon.actualSize(option.decorationSize, mode, state) option.decorationSize = option.decorationSize & actual_size r = core.Rect(core.Point(), option.decorationSize) r.moveCenter(option.rect.center()) r.setRight(option.rect.right() - margin) state = (gui.Icon.State.On if option.state & widgets.Style.StateFlag.State_Open else gui.Icon.State.Off) alignment = constants.ALIGN_RIGHT | constants.ALIGN_V_CENTER # type: ignore icon.paint(painter, r, alignment, mode, state)
def test_application(qapp): assert qapp.get_mainwindow() is None wnd = widgets.MainWindow() mw_widget = widgets.Widget() mw_widget.set_id("test") wnd.setCentralWidget(mw_widget) assert qapp.get_mainwindow() == wnd widget = qapp.get_widget(name="test") assert widget == mw_widget widget = widgets.Application["test"] assert widget == mw_widget with pytest.raises(InvalidParamError): qapp.get_style_icon("testus") icon = qapp.get_style_icon("warning") assert isinstance(icon, QtGui.QIcon) qapp.set_effect_enabled("animate_toolbox") with pytest.raises(InvalidParamError): qapp.set_effect_enabled("test") # assert qapp.is_effect_enabled("animate_toolbox") # qapp.set_navigation_mode("keypad_directional") # with pytest.raises(InvalidParamError): # qapp.set_navigation_mode("test") # assert qapp.get_navigation_mode("keypad_directional") for widget in qapp: pass qapp.store_widget_states() qapp.restore_widget_states() event = QtGui.QKeyEvent( QtCore.QEvent.Type.KeyPress, QtCore.Qt.Key.Key_Down, QtCore.Qt.KeyboardModifier(0) ) assert qapp.send_event("test", event) is True qapp.post_event("test", event) with qapp.edit_stylesheet(): pass
def pixmap(self, size, mode, state) -> QtGui.QPixmap: pm = QtGui.QPixmap(size) pm.fill(QtCore.Qt.GlobalColor.transparent) # type: ignore rect = core.Rect(ZERO_COORD, size) painter = gui.Painter(pm) self.paint(painter, rect, mode, state) return pm
def test_codeeditor(qtbot): editor = custom_widgets.CodeEditor() assert editor.text() == "" editor.line_area_width() editor.set_syntaxhighlighter("python") event = QtGui.QResizeEvent(core.Size(10, 10), core.Size(20, 20)) editor.resizeEvent(event) editor.repaint()
def set_pixmap( self, typ: widgets.wizard.WizardPixmapStr, pixmap: QtGui.QPixmap | None ): if typ not in widgets.wizard.WIZARD_PIXMAP: raise InvalidParamError(typ, widgets.wizard.WIZARD_PIXMAP) if pixmap is None: pixmap = QtGui.QPixmap() self.setPixmap(widgets.wizard.WIZARD_PIXMAP[typ], pixmap)
def set_pixmap(self, pixmap: QtGui.QPixmap | None, mode: ModeStr = "clipboard"): if mode not in MODES: raise InvalidParamError(mode, MODES) if pixmap is None: pixmap = QtGui.QPixmap() self.item.setPixmap(pixmap, MODES[mode])
def set_image(self, image: QtGui.QImage | None, mode: ModeStr = "clipboard"): if mode not in MODES: raise InvalidParamError(mode, MODES) if image is None: image = QtGui.QImage() self.item.setImage(image, MODES[mode])
def pixmap(self, size: QtCore.QSize, mode: QtGui.QIcon.Mode, state: QtGui.QIcon.State) -> QtGui.QPixmap: """Return the icon as a pixmap with requested size, mode, and state.""" img = gui.Image(size, QtGui.QImage.Format.Format_ARGB32) img.fill(QtCore.Qt.GlobalColor.transparent) pixmap = QtGui.QPixmap.fromImage( img, QtCore.Qt.ImageConversionFlag.NoFormatConversion) rect = QtCore.QRect(QtCore.QPoint(0, 0), size) self.paint(QtGui.QPainter(pixmap), rect, mode, state) return pixmap
def icon(self, *names, **kwargs) -> QtGui.QIcon: """Return a QtGui.QIcon object corresponding to the provided icon name.""" cache_key = f"{names}{kwargs}" if cache_key in self.icon_cache: return self.icon_cache[cache_key] opts = kwargs.pop("options", [{}] * len(names)) if len(opts) != len(names): raise TypeError(f'"options" must be a list of size {len(names)}') parsed_options = [ self._parse_options(o, kwargs, n) for o, n in zip(opts, names) ] engine = chariconengine.CharIconEngine(self, parsed_options) icon = QtGui.QIcon(engine) self.icon_cache[cache_key] = icon return icon
def add_pixmap( self, data: QtCore.QByteArray | QtGui.QPixmap | bytes, mode: ModeStr = "normal", state: StateStr = "off", ): if mode not in MODE: raise InvalidParamError(mode, MODE) if state not in STATE: raise InvalidParamError(state, STATE) if isinstance(data, bytes): data = QtCore.QByteArray(data) if isinstance(data, QtCore.QByteArray): pixmap = QtGui.QPixmap() pixmap.loadFromData(data) else: pixmap = data self.addPixmap(pixmap, MODE[mode], STATE[state])
def get_icon( icon: types.IconType, color: str | None = None, as_qicon: bool = False ) -> QtGui.QIcon: """Get icon with given color. Qtawesome already caches icons, but since we construct our own subclassed icon, we cache, too. """ if isinstance(icon, QtGui.QIcon): return icon if as_qicon else gui.Icon(icon) if isinstance(icon, os.PathLike): icon = os.fspath(icon) if (icon, color, as_qicon) in icon_cache: return icon_cache[(icon, color, as_qicon)] if isinstance(icon, str) and icon.startswith("mdi."): if color is not None: new = _icon(icon, color=color) else: new = _icon(icon) else: new = QtGui.QIcon(icon) # type: ignore icon = new if as_qicon else gui.Icon(new) icon_cache[(icon, color, as_qicon)] = icon return icon
def as_qt(self) -> QtGui.QColor: return QtGui.QColor(self)
from __future__ import annotations from prettyqt import constants, core from prettyqt.qt import QtGui from prettyqt.utils import InvalidParamError class FontMetrics(QtGui.QFontMetrics): def elided_text(self, text: str, mode: constants.ElideModeStr, width: int, flags=0) -> str: if mode not in constants.ELIDE_MODE: raise InvalidParamError(mode, constants.ELIDE_MODE) return self.elidedText(text, constants.ELIDE_MODE[mode], width, flags) def get_bounding_rect(self, *args) -> core.Rect: return core.Rect(self.boundingRect(*args)) def get_tight_bounding_rect(self, text: str) -> core.Rect: return core.Rect(self.tightBoundingRect(text)) if __name__ == "__main__": app = QtGui.QGuiApplication([]) font = QtGui.QFont() metrics = FontMetrics(font) print(metrics.get_bounding_rect("test"))
def paintEvent(self, ev): super().paintEvent(ev) p = QtGui.QPainter(self) p.setBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0))) p.drawEllipse(self.spot_pos.x() - 3, self.spot_pos.y() - 3, 6, 6)
def __setstate__(self, ba): px = QtGui.QPixmap() core.DataStream.write_bytearray(ba, px) super().__init__(px)
lines = self.blockCount() assert 1 <= line_no <= lines return self.findBlockByLineNumber(line_no - 1).position() def write_to_file( self, path: types.PathType, fmt: gui.textdocumentwriter.FormatStr | bytes | QtCore.QByteArray = "plaintext", ): writer = gui.TextDocumentWriter() writer.set_format(fmt) writer.set_file_name(path) return writer.write(self) def show_whitespace_and_tabs(self, show: bool): """Set show white spaces flag.""" options = self.get_default_text_option() flag = QtGui.QTextOption.Flag.ShowTabsAndSpaces if show: options.setFlags(options.flags() | flag) # type: ignore else: options.setFlags(options.flags() & ~flag) # type: ignore self.setDefaultTextOption(options) if __name__ == "__main__": doc = TextDocument("This is a test\nHello") doc.set_default_text_option(QtGui.QTextOption()) a = doc.write_to_file("test.a", "plaintext") print(a)
logger = logging.getLogger(__name__) _PRETTY_PRINTER = pprint.PrettyPrinter(indent=4) _ALL_PREDICATES = ( inspect.isgenerator, inspect.istraceback, inspect.isframe, inspect.iscode, inspect.isabstract, inspect.isgetsetdescriptor, inspect.ismemberdescriptor, ) CALLABLE_COLOR = QtGui.QBrush(gui.Color("mediumblue")) REGULAR_COLOR = QtGui.QBrush(gui.Color("black")) REGULAR_FONT = QtGui.QFont() # Font for members (non-functions) SPECIAL_ATTR_FONT = QtGui.QFont() # Font for __special_attributes__ SPECIAL_ATTR_FONT.setItalic(True) TYPE_CHECK: dict[Callable, str] = { inspect.isasyncgen: "Async generator", inspect.ismethoddescriptor: "Method descriptor", inspect.ismethod: "Method", inspect.isfunction: "Function", inspect.isgeneratorfunction: "Generator function", inspect.isclass: "Class", inspect.ismodule: "Module", inspect.isdatadescriptor: "Data descriptor",
if typ not in TEXT_RENDER_TYPE: raise InvalidParamError(typ, TEXT_RENDER_TYPE) QuickWindow.setTextRenderType(TEXT_RENDER_TYPE[typ]) @staticmethod def get_text_render_type() -> TextRenderTypeStr: """Return the render type of text-like elements in Qt Quick. Returns: text render type """ return TEXT_RENDER_TYPE.inverse[QuickWindow.textRenderType()] @contextlib.contextmanager def external_commands(self): self.beginExternalCommands() yield self self.endExternalCommands() def schedule_render_job(self, job: QtCore.QRunnable, render_stage: RenderStageStr): if render_stage not in RENDER_STAGE: raise InvalidParamError(render_stage, RENDER_STAGE) self.scheduleRenderJob(job, RENDER_STAGE[render_stage]) if __name__ == "__main__": app = gui.GuiApplication([]) wnd = QuickWindow() img = QtGui.QImage() texture = wnd.create_texture_from_image(img)