diff --git a/search/search_index.json b/search/search_index.json index 5eee7ca..db14c8e 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"superqt","text":""},{"location":"#missing-widgets-and-components-for-pyqtpyside","title":"\"missing\" widgets and components for PyQt/PySide","text":"

This repository aims to provide high-quality community-contributed Qt widgets and components for PyQt & PySide that are not provided in the native QtWidgets module.

Components are tested on:

"},{"location":"#installation","title":"Installation","text":"
pip install superqt\n
conda install -c conda-forge superqt\n
"},{"location":"#usage","title":"Usage","text":"

See the Widgets and Utilities pages for features offered by superqt.

"},{"location":"faq/","title":"FAQ","text":""},{"location":"faq/#sliders-not-dragging-properly-on-macos-12","title":"Sliders not dragging properly on MacOS 12+","text":"Details

On MacOS Monterey, with Qt5, there is a bug that causes all sliders (including native Qt sliders) to not respond properly to drag events. See:

Superqt includes a workaround for this issue, but it is not perfect, and it requires using a custom stylesheet (which may interfere with your own styles). Note that you may not see this issue if you're already using custom stylesheets.

To opt in to the workaround, do any of the following:

from superqt.sliders import MONTEREY_SLIDER_STYLES_FIX\n\nslider.setStyleSheet(MONTEREY_SLIDER_STYLES_FIX)\n
"},{"location":"utilities/","title":"Utilities","text":""},{"location":"utilities/#font-icons","title":"Font Icons","text":"Object Description addFont Add an OTF/TTF file at to the font registry. font Create QFont for a given font-icon font family key icon Create a QIcon for font-con glyph key setTextIcon Set text on a QWidget to a specific font & glyph. IconFont Helper class that provides a standard way to create an IconFont. IconOpts Options for rendering an icon Animation Base class for adding animations to a font-icon."},{"location":"utilities/#threading-tools","title":"Threading tools","text":"Object Description ensure_main_thread Decorator that ensures a function is called in the main QApplication thread. ensure_object_thread Decorator that ensures a QObject method is called in the object's thread. FunctionWorker QRunnable with signals that wraps a simple long-running function. GeneratorWorker QRunnable with signals that wraps a long-running generator. create_worker Create a worker to run a target function in another thread. thread_worker Decorator for create_worker, turn a function into a worker."},{"location":"utilities/#miscellaneous","title":"Miscellaneous","text":"Object Description QMessageHandler A context manager to intercept messages from Qt. CodeSyntaxHighlight A QSyntaxHighlighter for code syntax highlighting. draw_colormap Function that draws a colormap into any QPaintDevice."},{"location":"utilities/cmap/","title":"Colormap utilities","text":"

See also:

"},{"location":"utilities/cmap/#superqt.cmap.draw_colormap","title":"superqt.cmap.draw_colormap(painter_or_device, cmap, rect=None, border_color=None, border_width=1, lighter=100, checkerboard_size=4)","text":"

Draw a colormap onto a QPainter or QPaintDevice.

Parameters:

Name Type Description Default painter_or_device QPainter | QPaintDevice

A QPainter instance or a QPaintDevice (e.g. a QWidget or QPixmap) onto which to paint the colormap.

required cmap Colormap | Any

cmap.Colormap instance, or anything that can be converted to one (such as a string name of a colormap in the cmap catalog). https://cmap-docs.readthedocs.io/en/latest/colormaps/#colormaplike-objects

required rect QRect | QRectF | None

A rect onto which to draw. If None, the painter.viewport() will be used. by default None

None border_color QColor | str | None

If not None, a border of color border_color and width border_width is included around the edge, by default None.

None border_width int

The width of the border to draw (provided border_color is not None), by default 2

1 lighter int

Percentage by which to lighten (or darken) the colors. Greater than 100 lightens, less than 100 darkens, by default 100 (i.e. no change).

100 checkerboard_size bool

Size (in pixels) of the checkerboard pattern to draw, by default 5. If 0, no checkerboard is drawn.

4

Examples:

from qtpy.QtGui import QPixmap\nfrom qtpy.QtWidgets import QWidget\nfrom superqt.utils import draw_colormap\n\nviridis = 'viridis'  # or cmap.Colormap('viridis')\n\nclass W(QWidget):\n    def paintEvent(self, event) -> None:\n        draw_colormap(self, viridis, event.rect())\n\n# or draw onto a QPixmap\npm = QPixmap(200, 200)\ndraw_colormap(pm, viridis)\n
"},{"location":"utilities/cmap/#superqt.cmap.QColormapLineEdit","title":"superqt.cmap.QColormapLineEdit","text":"

Bases: QLineEdit

A QLineEdit that shows a colormap swatch.

When the current text is a valid colormap name from the cmap package, a swatch of the colormap will be shown to the left of the text (if fractionalColormapWidth is less than .75) or behind the text (for when the colormap fills the full width).

If the current text is not a valid colormap name, a swatch of the fallback colormap will be shown instead (by default, a gray colormap) if fractionalColormapWidth is less than .75.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None fractional_colormap_width float

The fraction of the widget width to use for the colormap swatch. If the colormap is full width (greater than 0.75), the swatch will be drawn behind the text. Otherwise, the swatch will be drawn to the left of the text. Default is 0.33.

0.33 fallback_cmap Colormap | str | None

The colormap to use when the current text is not a recognized colormap. by default \"gray\".

'gray' missing_icon QIcon | StandardPixmap

The icon to show when the current text is not a recognized colormap and fractionalColormapWidth is less than .75. Default is a question mark.

MISSING checkerboard_size int

Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.

4"},{"location":"utilities/cmap/#superqt.cmap.QColormapItemDelegate","title":"superqt.cmap.QColormapItemDelegate","text":"

Bases: QStyledItemDelegate

Delegate that draws colormaps into a QAbstractItemView item.

Parameters:

Name Type Description Default parent QObject

The parent object.

None item_size QSize

The size hint for each item, by default QSize(80, 22).

DEFAULT_SIZE fractional_colormap_width float

The fraction of the widget width to use for the colormap swatch. If the colormap is full width (greater than 0.75), the swatch will be drawn behind the text. Otherwise, the swatch will be drawn to the left of the text. Default is 0.33.

1 padding int

The padding (in pixels) around the edge of the item, by default 1.

1 checkerboard_size int

Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.

4"},{"location":"utilities/code_syntax_highlight/","title":"CodeSyntaxHighlight","text":"

A code highlighter subclass of QSyntaxHighlighter that can be used to highlight code in a QTextEdit.

Code lexer and available styles are from pygments python library

List of available languages are available here.

List of available styles are available here.

"},{"location":"utilities/code_syntax_highlight/#example","title":"Example","text":"
from qtpy.QtGui import QColor, QPalette\nfrom qtpy.QtWidgets import QApplication, QTextEdit\n\nfrom superqt.utils import CodeSyntaxHighlight\n\napp = QApplication([])\n\ntext_area = QTextEdit()\n\nhighlight = CodeSyntaxHighlight(text_area.document(), \"python\", \"monokai\")\n\npalette = text_area.palette()\npalette.setColor(QPalette.Base, QColor(highlight.background_color))\ntext_area.setPalette(palette)\ntext_area.setText(\n\"\"\"from argparse import ArgumentParser\n\ndef main():\n    parser = ArgumentParser()\n    parser.add_argument(\"name\", help=\"Your name\")\n    args = parser.parse_args()\n    print(f\"Hello {args.name}\")\n\n\nif __name__ == \"__main__\":\n    main()\n\"\"\"\n)\n\ntext_area.show()\ntext_area.resize(400, 200)\n\napp.exec_()\n
"},{"location":"utilities/code_syntax_highlight/#qt-class","title":"Qt Class","text":"

QSyntaxHighlighter

"},{"location":"utilities/code_syntax_highlight/#methods","title":"Methods","text":""},{"location":"utilities/code_syntax_highlight/#superqt.utils.CodeSyntaxHighlight.background_color","title":"background_color property","text":""},{"location":"utilities/error_dialog_contexts/","title":"Error message context manager","text":""},{"location":"utilities/error_dialog_contexts/#superqt.utils.exceptions_as_dialog","title":"superqt.utils.exceptions_as_dialog","text":"

Bases: AbstractContextManager

Context manager that shows a dialog when an exception is raised.

See examples below for common usage patterns.

To determine whether an exception was raised or not, check the exception attribute after the context manager has exited. If use_error_message is False (the default), you can also access the dialog attribute to get/manipulate the QMessageBox instance.

Parameters:

Name Type Description Default exceptions type[BaseException] | tuple[type[BaseException], ...]

The exception(s) to catch, by default Exception (i.e. all exceptions).

Exception icon Icon

The icon to show in the QMessageBox, by default QMessageBox.Icon.Critical

Critical title str

The title of the QMessageBox, by default \"An error occurred\".

'An error occurred' msg_template str

The message to show in the QMessageBox. The message will be formatted using three variables:

The default template is the content of the exception: \"{exc_value}\"

'{exc_value}' buttons StandardButton

The buttons to show in the QMessageBox, by default QMessageBox.StandardButton.Ok

Ok parent QWidget | None

The parent widget of the QMessageBox, by default None

None use_error_message bool | QErrorMessage

Whether to use a QErrorMessage instead of a QMessageBox. By default False. QErrorMessage shows a checkbox that the user can check to prevent seeing the message again (based on the text of the formatted msg_template.) If True, the global QMessageError.qtHandler() instance is used to maintain a history of dismissed messages. You may also pass a QErrorMessage instance to use a specific instance. If use_error_message is True, or if you pass your own QErrorMessage instance, the parent argument is ignored.

False

Attributes:

Name Type Description dialog QMessageBox | None

The QMessageBox instance that was created (if use_error_message was False). This can be used, among other things, to determine the result of the dialog (e.g. dialog.result()) or to manipulate the dialog (e.g. dialog.setDetailedText(\"some text\")).

exception BaseException | None

Will hold the exception instance if an exception was raised and caught.

"},{"location":"utilities/error_dialog_contexts/#superqt.utils.exceptions_as_dialog--examplez","title":"Examplez","text":"
from qtpy.QtWidgets import QApplication\nfrom superqt.utils import exceptions_as_dialog\n\napp = QApplication([])\n\nwith exceptions_as_dialog() as ctx:\n    raise Exception(\"This will be caught and shown in a QMessageBox\")\n\n# you can access the exception instance here\nassert ctx.exception is not None\n\n# with exceptions_as_dialog(ValueError):\n#     1 / 0  # ZeroDivisionError is not caught, so this will raise\n\nwith exceptions_as_dialog(msg_template=\"Error: {exc_value}\"):\n    raise Exception(\"This message will be inserted at 'exc_value'\")\n\nfor _i in range(3):\n    with exceptions_as_dialog(AssertionError, use_error_message=True):\n        assert False, \"Uncheck the checkbox to ignore this in the future\"\n\n# use ctx.dialog to get the result of the dialog\nbtns = QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel\nwith exceptions_as_dialog(buttons=btns) as ctx:\n    raise Exception(\"This will be caught and shown in a QMessageBox\")\nprint(ctx.dialog.result())  # prints which button was clicked\n\napp.exec()  # needed only for the use_error_message example to show\n
"},{"location":"utilities/fonticon/","title":"Font icons","text":"

The superqt.fonticon module provides a set of utilities for working with font icons such as Font Awesome or Material Design Icons.

"},{"location":"utilities/fonticon/#basic-example","title":"Basic Example","text":"
from fonticon_fa5 import FA5S\n\nfrom qtpy.QtCore import QSize\nfrom qtpy.QtWidgets import QApplication, QPushButton\n\nfrom superqt.fonticon import icon, pulse\n\napp = QApplication([])\n\nbtn2 = QPushButton()\nbtn2.setIcon(icon(FA5S.smile, color=\"blue\"))\nbtn2.setIconSize(QSize(225, 225))\nbtn2.show()\n\napp.exec()\n
"},{"location":"utilities/fonticon/#font-icon-plugins","title":"Font Icon plugins","text":"

Ready-made fonticon packs are available as plugins.

A great way to search across most available icons libraries from a single search interface is to use glyphsearch: https://glyphsearch.com/

If a font library you'd like to use is unavailable as a superqt plugin, please open a feature request

"},{"location":"utilities/fonticon/#font-awesome-6","title":"Font Awesome 6","text":"

Browse available icons at https://fontawesome.com/v6/search

pip install fonticon-fontawesome6\n
"},{"location":"utilities/fonticon/#font-awesome-5","title":"Font Awesome 5","text":"

Browse available icons at https://fontawesome.com/v5/search

pip install fonticon-fontawesome5\n
"},{"location":"utilities/fonticon/#material-design-icons-7","title":"Material Design Icons 7","text":"

Browse available icons at https://materialdesignicons.com/

pip install fonticon-materialdesignicons7\n
"},{"location":"utilities/fonticon/#material-design-icons-6","title":"Material Design Icons 6","text":"

Browse available icons at https://materialdesignicons.com/ (note that the search defaults to v7, see changes from v6 in the changelog)

pip install fonticon-materialdesignicons6\n
"},{"location":"utilities/fonticon/#see-also","title":"See also","text":"

superqt.fonticon is a pluggable system, and font icon packs may use the \"superqt.fonticon\" entry point to register themselves with superqt. See fonticon-cookiecutter for a template, or look through the following repos for examples:

"},{"location":"utilities/fonticon/#api","title":"API","text":"

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

"},{"location":"utilities/fonticon/#superqt.fonticon.icon","title":"superqt.fonticon.icon(glyph_key, scale_factor=DEFAULT_SCALING_FACTOR, color=None, opacity=1, animation=None, transform=None, states=None)","text":"

Create a QIcon for glyph_key, with a number of optional settings.

The glyph_key (e.g. 'fa5s.smile') represents a Font-family & style, and a glyph. In most cases, the key should be provided by a plugin in the environment, like:

...but fonts can also be added manually using addFont.

Parameters:

Name Type Description Default glyph_key str

String encapsulating a font-family, style, and glyph. e.g. 'fa5s.smile'.

required scale_factor float

Scale factor (fraction of widget height), When widget icon is painted on widget, it will use font.setPixelSize(round(wdg.height() * scale_factor)). by default 0.875.

DEFAULT_SCALING_FACTOR color ValidColor

Color for the font, by default None. (e.g. The default QColor) Valid color types include QColor, int, str, Qt.GlobalColor, tuple (of integer: RGB[A]) (anything that can be passed to QColor).

None opacity float

Opacity of icon, by default 1

1 animation Animation

Animation for the icon. A subclass of superqt.fonticon.Animation, that provides a concrete animate method. (see \"spin\" and \"pulse\" for examples). by default None.

None transform QTransform

A QTransform to apply when painting the icon, by default None

None states dict

Provide additional styling for the icon in different states. states must be a mapping of string to dict, where:

Missing keys in the state dicts will be taken from the default options, provided by the parameters above.

None

Returns:

Type Description QFontIcon

A subclass of QIcon. Can be used wherever QIcons are used, such as widget.setIcon()

Examples:

simple example (using the string 'fa5s.smile' assumes the fonticon-fontawesome5 plugin is installed)

>>> btn = QPushButton()\n>>> btn.setIcon(icon('fa5s.smile'))\n

can also directly import from fonticon_fa5

>>> from fonticon_fa5 import FA5S\n>>> btn.setIcon(icon(FA5S.smile))\n

with animation

>>> btn2 = QPushButton()\n>>> btn2.setIcon(icon(FA5S.spinner, animation=pulse(btn2)))\n

complicated example

>>> btn = QPushButton()\n>>> btn.setIcon(\n...     icon(\n...         FA5S.ambulance,\n...         color=\"blue\",\n...         states={\n...             \"active\": {\n...                 \"glyph\": FA5S.bath,\n...                 \"color\": \"red\",\n...                 \"scale_factor\": 0.5,\n...                 \"animation\": pulse(btn),\n...             },\n...             \"disabled\": {\n...                 \"color\": \"green\",\n...                 \"scale_factor\": 0.8,\n...                 \"animation\": spin(btn)\n...             },\n...         },\n...     )\n... )\n>>> btn.setIconSize(QSize(256, 256))\n>>> btn.show()\n
"},{"location":"utilities/fonticon/#superqt.fonticon.setTextIcon","title":"superqt.fonticon.setTextIcon(widget, glyph_key, size=None)","text":"

Set text on a widget to a specific font & glyph.

This is an alternative to setting a QIcon with a pixmap. It may be easier to combine with dynamic stylesheets.

Parameters:

Name Type Description Default widget QWidget

A widget supporting a setText method.

required glyph_key str

String encapsulating a font-family, style, and glyph. e.g. 'fa5s.smile'.

required size int

Size for QFont. passed to setPixelSize, by default None

None"},{"location":"utilities/fonticon/#superqt.fonticon.font","title":"superqt.fonticon.font(font_prefix, size=None)","text":"

Create QFont for font_prefix.

Parameters:

Name Type Description Default font_prefix str

Font_prefix, such as 'fa5s' or 'mdi6', representing a font-family and style.

required size int

Size for QFont. passed to setPixelSize, by default None

None

Returns:

Type Description QFont

QFont instance that can be used to add fonticons to widgets.

"},{"location":"utilities/fonticon/#superqt.fonticon.IconOpts","title":"superqt.fonticon.IconOpts dataclass","text":"

Options for rendering an icon.

Parameters:

Name Type Description Default glyph_key str

The key of the glyph to use, e.g. 'fa5s.smile', by default None

_Unset scale_factor float

The scale factor to use, by default None

_Unset color ValidColor

The color to use, by default None. Colors may be specified as a string, QColor, Qt.GlobalColor, or a 3 or 4-tuple of integers.

_Unset opacity float

The opacity to use, by default None

_Unset animation Animation

The animation to use, by default None

_Unset"},{"location":"utilities/fonticon/#superqt.fonticon.addFont","title":"superqt.fonticon.addFont(filepath, prefix, charmap=None)","text":"

Add OTF/TTF file at filepath to the registry under prefix.

If you'd like to later use a fontkey in the form of prefix.some-name, then charmap must be provided and provide a mapping for all of the glyph names to their unicode numbers. If a charmap is not provided, glyphs must be directly accessed with their unicode as something like key.\uffff.

Note

in most cases, users will not need this. Instead, they should install a font plugin, like:

Parameters:

Name Type Description Default filepath str

Path to an OTF or TTF file containing the fonts

required prefix str

A prefix that will represent this font file when used for lookup. For example, 'fa5s' for 'Font-Awesome 5 Solid'.

required charmap Dict[str, str]

optional mapping for all of the glyph names to their unicode numbers. See note above.

None

Returns:

Type Description (Tuple[str, str], optional)

font-family and font-style for the file just registered, or None if something goes wrong.

"},{"location":"utilities/fonticon/#animations","title":"Animations","text":"

the animation parameter to icon() accepts a subclass of Animation that will be

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

"},{"location":"utilities/fonticon/#superqt.fonticon.Animation","title":"superqt.fonticon.Animation","text":"

Bases: ABC

Base icon animation class.

"},{"location":"utilities/fonticon/#superqt.fonticon.Animation.animate","title":"animate(painter) abstractmethod","text":"

Setup and start the timer for the animation.

"},{"location":"utilities/fonticon/#superqt.fonticon.pulse","title":"superqt.fonticon.pulse","text":"

Bases: spin

Animation that spins an icon in slower, discrete steps.

"},{"location":"utilities/fonticon/#superqt.fonticon.spin","title":"superqt.fonticon.spin","text":"

Bases: Animation

Animation that smoothly spins an icon.

"},{"location":"utilities/qmessagehandler/","title":"QMessageHandler","text":""},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler","title":"superqt.utils.QMessageHandler","text":"

A context manager to intercept messages from Qt.

Parameters:

Name Type Description Default logger Logger

If provided, intercepted messages will be logged with logger at the corresponding python log level, by default None

None

Attributes:

Name Type Description records list of tuple

Captured messages. This is a 3-tuple of: (log_level: int, message: str, context: dict)

Examples:

>>> handler = QMessageHandler()\n>>> handler.install()  # now all Qt output will be available at mh.records\n
>>> with QMessageHandler() as handler:  # temporarily install\n...     ...\n
>>> logger = logging.getLogger(__name__)\n>>> with QMessageHandler(logger):  # re-reoute Qt messages to a python logger.\n...    ...\n
"},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler.__enter__","title":"__enter__()","text":"

Enter a context with this handler installed.

"},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler.install","title":"install()","text":"

Install this handler (override the current QtMessageHandler).

"},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler.uninstall","title":"uninstall()","text":"

Uninstall this handler, restoring the previous handler.

"},{"location":"utilities/signal_utils/","title":"Signal Utilities","text":""},{"location":"utilities/signal_utils/#superqt.utils.signals_blocked","title":"superqt.utils.signals_blocked(obj)","text":"

Context manager to temporarily block signals emitted by QObject: obj.

Parameters:

Name Type Description Default obj QObject

The QObject whose signals should be blocked.

required

Examples:

from qtpy.QtWidgets import QSpinBox\nfrom superqt import signals_blocked\n\nspinbox = QSpinBox()\nwith signals_blocked(spinbox):\n    spinbox.setValue(10)\n
"},{"location":"utilities/thread_decorators/","title":"Threading decorators","text":"

superqt provides two decorators that help to ensure that given function is running in the desired thread:

"},{"location":"utilities/thread_decorators/#ensure_main_thread","title":"ensure_main_thread","text":"

ensure_main_thread ensures that the decorated function/method runs in the main thread

"},{"location":"utilities/thread_decorators/#ensure_object_thread","title":"ensure_object_thread","text":"

ensure_object_thread ensures that a decorated bound method of a QObject runs in the thread in which the instance lives (see qt documentation for details).

"},{"location":"utilities/thread_decorators/#usage","title":"Usage","text":"

By default, functions are executed asynchronously (they return immediately with an instance of concurrent.futures.Future).

To block and wait for the result, see Synchronous mode

from qtpy.QtCore import QObject\nfrom superqt import ensure_main_thread, ensure_object_thread\n\n@ensure_main_thread\ndef sample_function():\n    print(\"This function will run in main thread\")\n\n\nclass SampleObject(QObject):\n    def __init__(self):\n        super().__init__()\n        self._value = 1\n\n    @ensure_main_thread\n    def sample_method1(self):\n        print(\"This method will run in main thread\")\n\n    @ensure_object_thread\n    def sample_method3(self):\n        import time\n        print(\"sleeping\")\n        time.sleep(1)\n        print(\"This method will run in object thread\")\n\n    @property\n    def value(self):\n        print(\"return value\")\n        return self._value\n\n    @value.setter\n    @ensure_object_thread\n    def value(self, value):\n        print(\"this setter will run in object thread\")\n        self._value = value\n

As can be seen in this example these decorators can also be used for setters.

These decorators should not be used as replacement of Qt Signals but rather to interact with Qt objects from non Qt code.

"},{"location":"utilities/thread_decorators/#synchronous-mode","title":"Synchronous mode","text":"

If you'd like for the program to block and wait for the result of your function call, use the await_return=True parameter, and optionally specify a timeout.

Important

Using synchronous mode may significantly impact performance.

from superqt import ensure_main_thread\n\n@ensure_main_thread\ndef sample_function1():\n    return 1\n\n@ensure_main_thread(await_return=True)\ndef sample_function2():\n    return 2\n\nassert sample_function1() is None\nassert sample_function2() == 2\n\n# optionally, specify a timeout\n@ensure_main_thread(await_return=True, timeout=10000)\ndef sample_function():\n    return 1\n
"},{"location":"utilities/threading/","title":"Thread workers","text":"

The objects in this module provide utilities for running tasks in a separate thread. In general (with the exception of new_worker_qthread), everything here wraps Qt's QRunnable API.

The highest level object is the @thread_worker decorator. It was originally written for napari, and was later extracted into superqt. You may also be interested in reading the napari documentation on this feature, which provides a more in-depth/introductory usage guide.

For additional control, you can create your own FunctionWorker or GeneratorWorker objects.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase","title":"superqt.utils.WorkerBase","text":"

Bases: QRunnable, Generic[_R]

Base class for creating a Worker that can run in another thread.

Parameters:

Name Type Description Default SignalsClass type

A QObject subclass that contains signals, by default WorkerBaseSignals

WorkerBaseSignals

Attributes:

Name Type Description signals WorkerBaseSignals

signal emitter object. To allow identify which worker thread emitted signal.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.abort_requested","title":"abort_requested: bool property","text":"

Whether the worker has been requested to stop.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.is_running","title":"is_running: bool property","text":"

Whether the worker has been started.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.__getattr__","title":"__getattr__(name)","text":"

Pass through attr requests to signals to simplify connection API.

The goal is to enable worker.yielded.connect instead of worker.signals.yielded.connect. Because multiple inheritance of Qt classes is not well supported in PyQt, we have to use composition here (signals are provided by QObjects, and QRunnable is not a QObject). So this passthrough allows us to connect to signals on the _signals object.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.await_workers","title":"await_workers(msecs=None) classmethod","text":"

Ask all workers to quit, and wait up to msec for quit.

Attempts to clean up all running workers by calling worker.quit() method. Any workers in the WorkerBase._worker_set set will have this method.

By default, this function will block indefinitely, until worker threads finish. If a timeout is provided, a RuntimeError will be raised if the workers do not gracefully exit in the time requests, but the threads will NOT be killed. It is (currently) left to the user to use their OS to force-quit rogue threads.

Important

If the user does not put any yields in their function, and the function is super long, it will just hang... For instance, there's no graceful way to kill this thread in python:

@thread_worker\ndef ZZZzzz():\n    time.sleep(10000000)\n

This is why it's always advisable to use a generator that periodically yields for long-running computations in another thread.

See this stack-overflow post for a good discussion on the difficulty of killing a rogue python thread:

Parameters:

Name Type Description Default msecs int

Waits up to msecs milliseconds for all threads to exit and removes all threads from the thread pool. If msecs is None (the default), the timeout is ignored (waits for the last thread to exit).

None

Raises:

Type Description RuntimeError

If a timeout is provided and workers do not quit successfully within the time allotted.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.quit","title":"quit()","text":"

Send a request to abort the worker.

Note

It is entirely up to subclasses to honor this method by checking self.abort_requested periodically in their worker.work method, and exiting if True.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.run","title":"run()","text":"

Start the worker.

The end-user should never need to call this function. But it cannot be made private or renamed, since it is called by Qt.

The order of method calls when starting a worker is:

   calls QThreadPool.globalInstance().start(worker)\n   |               triggered by the QThreadPool.start() method\n   |               |             called by worker.run\n   |               |             |\n   V               V             V\n   worker.start -> worker.run -> worker.work\n

This is the function that actually gets called when calling QThreadPool.start(worker). It simply wraps the work() method, and emits a few signals. Subclasses should NOT override this method (except with good reason), and instead should implement work().

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.start","title":"start()","text":"

Start this worker in a thread and add it to the global threadpool.

The order of method calls when starting a worker is:

   calls QThreadPool.globalInstance().start(worker)\n   |               triggered by the QThreadPool.start() method\n   |               |             called by worker.run\n   |               |             |\n   V               V             V\n   worker.start -> worker.run -> worker.work\n
"},{"location":"utilities/threading/#superqt.utils.WorkerBase.work","title":"work()","text":"

Main method to execute the worker.

The end-user should never need to call this function. But subclasses must implement this method (See GeneratorFunction.work for an example implementation). Minimally, it should check self.abort_requested periodically and exit if True.

Examples:

class MyWorker(WorkerBase):\n\n    def work(self):\n        i = 0\n        while True:\n            if self.abort_requested:\n                self.aborted.emit()\n                break\n            i += 1\n            if i > max_iters:\n                break\n            time.sleep(0.5)\n
"},{"location":"utilities/threading/#superqt.utils.FunctionWorker","title":"superqt.utils.FunctionWorker","text":"

Bases: WorkerBase[_R]

QRunnable with signals that wraps a simple long-running function.

Note

FunctionWorker does not provide a way to stop a very long-running function (e.g. time.sleep(10000)). So whenever possible, it is better to implement your long running function as a generator that yields periodically, and use the GeneratorWorker instead.

Parameters:

Name Type Description Default func Callable

A function to call in another thread

required *args

will be passed to the function

() **kwargs

will be passed to the function

{}

Raises:

Type Description TypeError

If func is a generator function and not a regular function.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker","title":"superqt.utils.GeneratorWorker","text":"

Bases: WorkerBase, Generic[_Y, _S, _R]

QRunnable with signals that wraps a long-running generator.

Provides a convenient way to run a generator function in another thread, while allowing 2-way communication between threads, using plain-python generator syntax in the original function.

Parameters:

Name Type Description Default func callable

The function being run in another thread. May be a generator function.

required SignalsClass type

A QObject subclass that contains signals, by default GeneratorWorkerSignals

GeneratorWorkerSignals *args

Will be passed to func on instantiation

() **kwargs

Will be passed to func on instantiation

{}"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.is_paused","title":"is_paused: bool property","text":"

Whether the worker is currently paused.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.pause","title":"pause()","text":"

Request to pause the worker.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.resume","title":"resume()","text":"

Send a request to resume the worker.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.send","title":"send(value)","text":"

Send a value into the function (if a generator was used).

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.toggle_pause","title":"toggle_pause()","text":"

Request to pause the worker if playing or resume if paused.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.work","title":"work()","text":"

Core event loop that calls the original function.

Enters a continual loop, yielding and returning from the original function. Checks for various events (quit, pause, resume, etc...). (To clarify: we are creating a rudimentary event loop here because there IS NO Qt event loop running in the other thread to hook into)

"},{"location":"utilities/threading/#convenience-functions","title":"Convenience functions","text":""},{"location":"utilities/threading/#superqt.utils.thread_worker","title":"superqt.utils.thread_worker(function=None, start_thread=None, connect=None, worker_class=None, ignore_errors=False)","text":"

Decorator that runs a function in a separate thread when called.

When called, the decorated function returns a WorkerBase. See create_worker for additional keyword arguments that can be used when calling the function.

The returned worker will have these signals:

It will also have a worker.start() method that can be used to start execution of the function in another thread. (useful if you need to connect callbacks to signals prior to execution)

If the decorated function is a generator, the returned worker will also provide these signals:

And these methods:

Parameters:

Name Type Description Default function callable

Function to call in another thread. For communication between threads may be a generator function.

None start_thread bool

Whether to immediaetly start the thread. If False, the returned worker must be manually started with worker.start(). by default it will be False if the _connect argument is None, otherwise True.

None connect Dict[str, Union[Callable, Sequence]]

A mapping of \"signal_name\" -> callable or list of callable: callback functions to connect to the various signals offered by the worker class. by default None

None worker_class Type[WorkerBase]

The WorkerBase to instantiate, by default FunctionWorker will be used if func is a regular function, and GeneratorWorker will be used if it is a generator.

None ignore_errors bool

If False (the default), errors raised in the other thread will be reraised in the main thread (makes debugging significantly easier).

False

Returns:

Type Description callable

function that creates a worker, puts it in a new thread and returns the worker instance.

Examples:

@thread_worker\ndef long_function(start, end):\n    # do work, periodically yielding\n    i = start\n    while i <= end:\n        time.sleep(0.1)\n        yield i\n\n    # do teardown\n    return 'anything'\n\n# call the function to start running in another thread.\nworker = long_function()\n\n# connect signals here if desired... or they may be added using the\n# `connect` argument in the `@thread_worker` decorator... in which\n# case the worker will start immediately when long_function() is called\nworker.start()\n
"},{"location":"utilities/threading/#superqt.utils.create_worker","title":"superqt.utils.create_worker(func, *args, _start_thread=None, _connect=None, _worker_class=None, _ignore_errors=False, **kwargs)","text":"

Convenience function to start a function in another thread.

By default, uses FunctionWorker for functions and GeneratorWorker for generators, but a custom WorkerBase subclass may be provided. If so, it must be a subclass of WorkerBase, which defines a standard set of signals and a run method.

Parameters:

Name Type Description Default func Callable

The function to call in another thread.

required _start_thread bool

Whether to immediaetly start the thread. If False, the returned worker must be manually started with worker.start(). by default it will be False if the _connect argument is None, otherwise True.

None _connect Dict[str, Union[Callable, Sequence]]

A mapping of \"signal_name\" -> callable or list of callable: callback functions to connect to the various signals offered by the worker class. by default None

None _worker_class type of `GeneratorWorker` or `FunctionWorker`

The WorkerBase to instantiate, by default FunctionWorker will be used if func is a regular function, and GeneratorWorker will be used if it is a generator.

None _ignore_errors bool

If False (the default), errors raised in the other thread will be reraised in the main thread (makes debugging significantly easier).

False *args

will be passed to func

() **kwargs

will be passed to func

{}

Returns:

Name Type Description worker WorkerBase

An instantiated worker. If _start_thread was False, the worker will have a .start() method that can be used to start the thread.

Raises:

Type Description TypeError

If a worker_class is provided that is not a subclass of WorkerBase.

TypeError

If _connect is provided and is not a dict of {str: callable}

Examples:

def long_function(duration):\n    import time\n    time.sleep(duration)\n\nworker = create_worker(long_function, 10)\n
"},{"location":"utilities/threading/#superqt.utils.new_worker_qthread","title":"superqt.utils.new_worker_qthread(Worker, *args, _start_thread=False, _connect=None, **kwargs)","text":"

Convenience function to start a worker in a QThread.

thread, not as the actual code or object that runs in that thread. The QThread object is created on the main thread and lives there.

Worker objects which derive from QObject are the things that actually do the work. They can be moved to a QThread as is done here.

Mostly ignorable detail

While the signals/slots syntax of the worker looks very similar to standard \"single-threaded\" signals & slots, note that inter-thread signals and slots (automatically) use an event-based QueuedConnection, while intra-thread signals use a DirectConnection. See Signals and Slots Across Threads

Parameters:

Name Type Description Default Worker QObject

QObject type that implements a work() method. The Worker should also emit a finished signal when the work is done.

required _start_thread bool

If True, thread will be started immediately, otherwise, thread must be manually started with thread.start().

False _connect dict

Optional dictionary of {signal: function} to connect to the new worker. for instance: _connect = {'incremented': myfunc} will result in: worker.incremented.connect(myfunc)

None *args

will be passed to the Worker class on instantiation.

() **kwargs

will be passed to the Worker class on instantiation.

{}

Returns:

Name Type Description worker WorkerBase

The created worker.

thread QThread

The thread on which the worker is running.

Examples:

Create some QObject that has a long-running work method:

class Worker(QObject):\n\n    finished = Signal()\n    increment = Signal(int)\n\n    def __init__(self, argument):\n        super().__init__()\n        self.argument = argument\n\n    @Slot()\n    def work(self):\n        # some long running task...\n        import time\n        for i in range(10):\n            time.sleep(1)\n            self.increment.emit(i)\n        self.finished.emit()\n\nworker, thread = new_worker_qthread(\n    Worker,\n    'argument',\n    _start_thread=True,\n    _connect={'increment': print},\n)\n
"},{"location":"utilities/throttling/","title":"Throttling & Debouncing","text":"

These utilities allow you to throttle or debounce a function. This is useful when you have a function that is called multiple times in a short period of time, and you want to make sure it is only \"actually\" called once (or at least no more than a certain frequency).

For background on throttling and debouncing, see:

"},{"location":"utilities/throttling/#superqt.utils.qdebounced","title":"superqt.utils.qdebounced(func=None, timeout=100, leading=False, timer_type=Qt.TimerType.PreciseTimer, parent=None)","text":"

Creates a debounced function that delays invoking func.

func will not be invoked until timeout ms have elapsed since the last time the debounced function was invoked.

The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Options indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

This decorator may be used with or without parameters.

Parameters:

Name Type Description Default func Callable

A function to throttle

None timeout int

Timeout in milliseconds to wait before allowing another call, by default 100

100 leading bool

Whether to invoke the function on the leading edge of the wait timer, by default False

False timer_type TimerType

The timer type. by default Qt.TimerType.PreciseTimer One of: - Qt.PreciseTimer: Precise timers try to keep millisecond accuracy - Qt.CoarseTimer: Coarse timers try to keep accuracy within 5% of the desired interval - Qt.VeryCoarseTimer: Very coarse timers only keep full second accuracy

PreciseTimer parent QObject | None

Parent object for timer. If using qthrottled as function it may be usefull for cleaning data

None"},{"location":"utilities/throttling/#superqt.utils.qthrottled","title":"superqt.utils.qthrottled(func=None, timeout=100, leading=True, timer_type=Qt.TimerType.PreciseTimer, parent=None)","text":"

Creates a throttled function that invokes func at most once per timeout.

The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

This decorator may be used with or without parameters.

Parameters:

Name Type Description Default func Callable

A function to throttle

None timeout int

Timeout in milliseconds to wait before allowing another call, by default 100

100 leading bool

Whether to invoke the function on the leading edge of the wait timer, by default True

True timer_type TimerType

The timer type. by default Qt.TimerType.PreciseTimer One of: - Qt.PreciseTimer: Precise timers try to keep millisecond accuracy - Qt.CoarseTimer: Coarse timers try to keep accuracy within 5% of the desired interval - Qt.VeryCoarseTimer: Very coarse timers only keep full second accuracy

PreciseTimer parent QObject | None

Parent object for timer. If using qthrottled as function it may be usefull for cleaning data

None"},{"location":"utilities/throttling/#superqt.utils.QSignalDebouncer","title":"superqt.utils.QSignalDebouncer","text":"

Bases: GenericSignalThrottler

A Signal Debouncer.

This object's triggered signal will not be emitted until self.timeout() milliseconds have elapsed since the last time triggered was emitted.

"},{"location":"utilities/throttling/#superqt.utils.QSignalThrottler","title":"superqt.utils.QSignalThrottler","text":"

Bases: GenericSignalThrottler

A Signal Throttler.

This object's triggered signal will emit at most once per timeout (set with setTimeout()).

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler","title":"superqt.utils._throttler.GenericSignalThrottler","text":"

Bases: QObject

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.cancel","title":"cancel()","text":"

Cancel any pending emissions.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.emissionPolicy","title":"emissionPolicy()","text":"

Return the emission policy (trailing or leading).

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.flush","title":"flush()","text":"

Force emission of any pending emissions.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.kind","title":"kind()","text":"

Return the kind of throttler (throttler or debouncer).

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.setTimeout","title":"setTimeout(timeout)","text":"

Set timeout in milliseconds.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.setTimerType","title":"setTimerType(timerType)","text":"

Set current Qt.TimerType.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.throttle","title":"throttle()","text":"

Emit triggered if not running, then start timer.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.timeout","title":"timeout()","text":"

Return current timeout in milliseconds.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.timerType","title":"timerType()","text":"

Return current Qt.TimerType.

"},{"location":"widgets/","title":"Widgets","text":"

The following are QWidget subclasses:

"},{"location":"widgets/#sliders-and-numerical-inputs","title":"Sliders and Numerical Inputs","text":"Widget Description QDoubleRangeSlider Multi-handle slider for float values QDoubleSlider Slider for float values QLabeledDoubleRangeSlider QDoubleRangeSlider variant with editable labels for each handle QLabeledDoubleSlider QSlider for float values with editable QSpinBox with the current value QLabeledRangeSlider QRangeSlider variant, with editable labels for each handle QLabeledSlider QSlider with editable QSpinBox that shows the current value QLargeIntSpinBox QSpinbox that accepts arbitrarily large integers QRangeSlider Multi-handle slider QQuantity Pint-backed quantity widget (magnitude combined with unit dropdown)"},{"location":"widgets/#labels-and-categorical-inputs","title":"Labels and categorical inputs","text":"Widget Description QElidingLabel A QLabel variant that will elide text (add \u2026) to fit width. QEnumComboBox QComboBox that populates the combobox from a python Enum QSearchableComboBox QComboBox variant that filters available options based on text input QSearchableListWidget QListWidget variant with search field that filters available options QSearchableTreeWidget QTreeWidget variant with search field that filters available options QColorComboBox QComboBox to select from a specified set of colors QColormapComboBox QComboBox to select from a specified set of colormaps."},{"location":"widgets/#frames-and-containers","title":"Frames and containers","text":"Widget Description QCollapsible A collapsible widget to hide and unhide child widgets."},{"location":"widgets/colormap_catalog/","title":"CmapCatalogComboBox","text":"

Searchable QComboBox variant that contains the entire cmap colormap catalog

requires cmap

This widget uses the cmap library to provide colormaps. You can install it with:

# use the `cmap` extra to include colormap support\npip install superqt[cmap]\n

You can limit the colormaps shown by setting the categories or interpolation keyword arguments.

from qtpy.QtWidgets import QApplication\n\nfrom superqt.cmap import CmapCatalogComboBox\n\napp = QApplication([])\n\ncatalog_combo = CmapCatalogComboBox(interpolation=\"linear\")\ncatalog_combo.setCurrentText(\"viridis\")\ncatalog_combo.show()\n\napp.exec()\n

"},{"location":"widgets/colormap_catalog/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/colormap_catalog/#signals","title":"Signals","text":""},{"location":"widgets/colormap_catalog/#currentcolormapchanged","title":"currentColormapChanged","text":""},{"location":"widgets/colormap_catalog/#methods","title":"Methods","text":"

A combo box for selecting a colormap from the entire cmap catalog.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None prefer_short_names bool

If True (default), short names (without the namespace prefix) will be preferred over fully qualified names. In cases where the same short name is used in multiple namespaces, they will all be referred to by their fully qualified (namespaced) name.

True categories Container[Category]

If provided, only return names from the given categories.

() interpolation Interpolation

If provided, only return names that have the given interpolation method.

None"},{"location":"widgets/colormap_catalog/#superqt.cmap.CmapCatalogComboBox.currentColormap","title":"currentColormap() -> Colormap | None","text":"

Returns the currently selected Colormap or None if not yet selected.

"},{"location":"widgets/qcollapsible/","title":"QCollapsible","text":"

Collapsible QFrame that can be expanded or collapsed by clicking on the header.

from qtpy.QtWidgets import QApplication, QLabel, QPushButton\n\nfrom superqt import QCollapsible\n\napp = QApplication([])\n\ncollapsible = QCollapsible(\"Advanced analysis\")\ncollapsible.addWidget(QLabel(\"This is the inside of the collapsible frame\"))\nfor i in range(10):\n    collapsible.addWidget(QPushButton(f\"Content button {i + 1}\"))\n\ncollapsible.expand(animate=False)\ncollapsible.show()\napp.exec_()\n

"},{"location":"widgets/qcollapsible/#qt-class","title":"Qt Class","text":"

QFrame

"},{"location":"widgets/qcollapsible/#signals","title":"Signals","text":""},{"location":"widgets/qcollapsible/#toggled","title":"toggled","text":""},{"location":"widgets/qcollapsible/#methods","title":"Methods","text":"

A collapsible widget to hide and unhide child widgets.

A signal is emitted when the widget is expanded (True) or collapsed (False).

Based on https://stackoverflow.com/a/68141638

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.addWidget","title":"addWidget(widget: QWidget) -> None","text":"

Add a widget to the central content widget's layout.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.collapse","title":"collapse(animate: bool = True) -> None","text":"

Collapse (hide) the collapsible section.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.collapsedIcon","title":"collapsedIcon() -> QIcon","text":"

Returns the icon used when the widget is collapsed.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.content","title":"content() -> QWidget","text":"

Return the current content widget.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.expand","title":"expand(animate: bool = True) -> None","text":"

Expand (show) the collapsible section.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.expandedIcon","title":"expandedIcon() -> QIcon","text":"

Returns the icon used when the widget is expanded.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.isExpanded","title":"isExpanded() -> bool","text":"

Return whether the collapsible section is visible.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.locked","title":"locked() -> bool","text":"

Return True if collapse/expand is disabled.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.removeWidget","title":"removeWidget(widget: QWidget) -> None","text":"

Remove widget from the central content widget's layout.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setCollapsedIcon","title":"setCollapsedIcon(icon: Optional[Union[QIcon, str]] = None) -> None","text":"

Set the icon on the toggle button when the widget is collapsed.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setContent","title":"setContent(content: QWidget) -> None","text":"

Replace central widget (the widget that gets expanded/collapsed).

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setDuration","title":"setDuration(msecs: int) -> None","text":"

Set duration of the collapse/expand animation.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setEasingCurve","title":"setEasingCurve(easing: QEasingCurve) -> None","text":"

Set the easing curve for the collapse/expand animation.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setExpandedIcon","title":"setExpandedIcon(icon: Optional[Union[QIcon, str]] = None) -> None","text":"

Set the icon on the toggle button when the widget is expanded.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setLocked","title":"setLocked(locked: bool = True) -> None","text":"

Set whether collapse/expand is disabled.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setText","title":"setText(text: str) -> None","text":"

Set the text of the toggle button.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.text","title":"text() -> str","text":"

Return the text of the toggle button.

"},{"location":"widgets/qcolorcombobox/","title":"QColorComboBox","text":"

QComboBox designed to select from a specific set of colors.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QColorComboBox\n\napp = QApplication([])\n\ncolors = QColorComboBox()\ncolors.addColors(['red', 'green', 'blue'])\n\n# show an \"Add Color\" item that opens a QColorDialog when clicked\ncolors.setUserColorsAllowed(True)\n\n# emits a QColor when changed\ncolors.currentColorChanged.connect(print)\ncolors.show()\n\napp.exec_()\n

"},{"location":"widgets/qcolorcombobox/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qcolorcombobox/#signals","title":"Signals","text":""},{"location":"widgets/qcolorcombobox/#currentcolorchanged","title":"currentColorChanged","text":""},{"location":"widgets/qcolorcombobox/#enums","title":"Enums","text":""},{"location":"widgets/qcolorcombobox/#qcolorcomboboxinvalidcolorpolicy","title":"QColorComboBox.InvalidColorPolicy","text":""},{"location":"widgets/qcolorcombobox/#methods","title":"Methods","text":"

A drop down menu for selecting colors.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None allow_user_colors bool

Whether to show an \"Add Color\" item that opens a QColorDialog when clicked. Whether the user can add custom colors by clicking the \"Add Color\" item. Default is False. Can also be set with setUserColorsAllowed.

False add_color_text str

The text to display for the \"Add Color\" item. Default is \"Add Color...\".

'Add Color...'"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.addColor","title":"addColor(color: Any) -> None","text":"

Adds the color to the QComboBox.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.addColors","title":"addColors(colors: Sequence[Any]) -> None","text":"

Adds colors to the QComboBox.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.currentColor","title":"currentColor() -> QColor | None","text":"

Returns the currently selected QColor or None if not yet selected.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.currentColorName","title":"currentColorName() -> str | None","text":"

Returns the name of the currently selected QColor or black if None.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.invalidColorPolicy","title":"invalidColorPolicy() -> InvalidColorPolicy","text":"

Returns the policy for handling invalid colors.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.itemColor","title":"itemColor(index: int) -> QColor | None","text":"

Returns the color of the item at the given index.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.setCurrentColor","title":"setCurrentColor(color: Any) -> None","text":"

Adds the color to the QComboBox and selects it.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.setInvalidColorPolicy","title":"setInvalidColorPolicy(policy: InvalidColorPolicy | int | Literal['Raise', 'Ignore', 'Warn']) -> None","text":"

Sets the policy for handling invalid colors.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.setUserColorsAllowed","title":"setUserColorsAllowed(allow: bool) -> None","text":"

Sets whether the user can add custom colors.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.userColorsAllowed","title":"userColorsAllowed() -> bool","text":"

Returns whether the user can add custom colors.

"},{"location":"widgets/qcolormap/","title":"QColormapComboBox","text":"

QComboBox variant to select from a specific set of colormaps.

requires cmap

This widget uses the cmap library to provide colormaps. You can install it with:

# use the `cmap` extra to include colormap support\npip install superqt[cmap]\n
"},{"location":"widgets/qcolormap/#colormaplike-objects","title":"ColorMapLike objects","text":"

Colormaps may be specified in a variety of ways, such as by name (string), an iterable of a color/color-like objects, or as a cmap.Colormap instance. See cmap documentation for details on all ColormapLike types

"},{"location":"widgets/qcolormap/#example","title":"Example","text":"
from cmap import Colormap\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QColormapComboBox\n\napp = QApplication([])\n\ncmap_combo = QColormapComboBox()\n# see note above about colormap-like objects\n# as names from the cmap catalog\ncmap_combo.addColormaps([\"viridis\", \"plasma\", \"magma\", \"gray\"])\n# as a sequence of colors, linearly interpolated\ncmap_combo.addColormap((\"#0f0\", \"slateblue\", \"#F3A003A0\"))\n# as a `cmap.Colormap` instance with custom name:\ncmap_combo.addColormap(Colormap((\"green\", \"white\", \"orange\"), name=\"MyMap\"))\n\ncmap_combo.show()\napp.exec()\n
"},{"location":"widgets/qcolormap/#style-customization","title":"Style Customization","text":"

Note that both the LineEdit and the dropdown can be styled to have the colormap on the left, or fill the entire width of the widget.

To make the CombBox label colormap fill the entire width of the widget:

from superqt.cmap import QColormapLineEdit\ncmap_combo.setLineEdit(QColormapLineEdit())\n

To make the CombBox dropdown colormaps fill less than the entire width of the widget:

from superqt.cmap import QColormapItemDelegate\ndelegate = QColormapItemDelegate(fractional_colormap_width=0.33)\ncmap_combo.setItemDelegate(delegate)\n
"},{"location":"widgets/qcolormap/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qcolormap/#signals","title":"Signals","text":""},{"location":"widgets/qcolormap/#currentcolormapchanged","title":"currentColormapChanged","text":""},{"location":"widgets/qcolormap/#methods","title":"Methods","text":"

A drop down menu for selecting colors.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None allow_user_colormaps bool

Whether the user can add custom colormaps by clicking the \"Add Colormap...\" item. Default is False. Can also be set with setUserAdditionsAllowed.

False add_colormap_text str

The text to display for the \"Add Colormap...\" item. Default is \"Add Colormap...\".

'Add Colormap...'"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.addColormap","title":"addColormap(cmap: ColorStopsLike) -> None","text":"

Adds the colormap to the QComboBox.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.addColormaps","title":"addColormaps(colors: Sequence[Any]) -> None","text":"

Adds colors to the QComboBox.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.currentColormap","title":"currentColormap() -> Colormap | None","text":"

Returns the currently selected Colormap or None if not yet selected.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.itemColormap","title":"itemColormap(index: int) -> Colormap | None","text":"

Returns the color of the item at the given index.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.setCurrentColormap","title":"setCurrentColormap(color: Any) -> None","text":"

Adds the color to the QComboBox and selects it.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.setUserAdditionsAllowed","title":"setUserAdditionsAllowed(allow: bool) -> None","text":"

Sets whether the user can add custom colors.

If enabled, an \"Add Colormap...\" item will be added to the end of the list. When clicked, a dialog will be shown to allow the user to select a colormap from the cmap catalog.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.userAdditionsAllowed","title":"userAdditionsAllowed() -> bool","text":"

Returns whether the user can add custom colors.

"},{"location":"widgets/qdoublerangeslider/","title":"QDoubleRangeSlider","text":"

Float variant of QRangeSlider. (see that page for more details).

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QDoubleRangeSlider\n\napp = QApplication([])\n\nslider = QDoubleRangeSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 1)\nslider.setValue((0.2, 0.8))\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qdoublerangeslider/#qt-class","title":"Qt Class","text":"

QSlider

"},{"location":"widgets/qdoublerangeslider/#methods","title":"Methods","text":""},{"location":"widgets/qdoubleslider/","title":"QDoubleSlider","text":"

QSlider variant that accepts floating point values.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QDoubleSlider\n\napp = QApplication([])\n\nslider = QDoubleSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 1)\nslider.setValue(0.5)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qdoubleslider/#qt-class","title":"Qt Class","text":"

QSlider

"},{"location":"widgets/qdoubleslider/#methods","title":"Methods","text":""},{"location":"widgets/qelidinglabel/","title":"QElidingLabel","text":"

QLabel variant that will elide text (i.e. add an ellipsis) if it is too long to fit in the available space.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QElidingLabel\n\napp = QApplication([])\n\nwidget = QElidingLabel(\n    \"a skj skjfskfj sdlf sdfl sdlfk jsdf sdlkf jdsf dslfksdl sdlfk sdf sdl \"\n    \"fjsdlf kjsdlfk laskdfsal as lsdfjdsl kfjdslf asfd dslkjfldskf sdlkfj\"\n)\nwidget.setWordWrap(True)\nwidget.resize(300, 20)\nwidget.show()\n\napp.exec_()\n

"},{"location":"widgets/qelidinglabel/#qt-class","title":"Qt Class","text":"

QLabel

"},{"location":"widgets/qelidinglabel/#methods","title":"Methods","text":"

A QLabel variant that will elide text (could add '\u2026') to fit width.

QElidingLabel() QElidingLabel(parent: Optional[QWidget], f: Qt.WindowFlags = ...) QElidingLabel(text: str, parent: Optional[QWidget] = None, f: Qt.WindowFlags = ...)

For a multiline eliding label, use setWordWrap(True). In this case, text will wrap to fit the width, and only the last line will be elided. When wordWrap() is True, sizeHint() will return the size required to fit the full text.

"},{"location":"widgets/qelidinglabel/#superqt.QElidingLabel.setElideMode","title":"setElideMode(mode: Qt.TextElideMode) -> None","text":"

Set the elide mode to a Qt.TextElideMode.

"},{"location":"widgets/qelidinglabel/#superqt.QElidingLabel.setEllipsesWidth","title":"setEllipsesWidth(width: int) -> None","text":"

A width value to take into account ellipses width when eliding text.

The value is deducted from the widget width when computing the elided version of the text.

"},{"location":"widgets/qenumcombobox/","title":"QEnumComboBox","text":"

QEnumComboBox is a variant of QComboBox that populates the items in the combobox based on a python Enum class. In addition to all the methods provided by QComboBox, this subclass adds the methods enumClass/setEnumClass to get/set the current Enum class represented by the combobox, and currentEnum/setCurrentEnum to get/set the current Enum member in the combobox. There is also a new signal currentEnumChanged(enum) analogous to currentIndexChanged and currentTextChanged.

Method like insertItem and addItem are blocked and try of its usage will end with RuntimeError

from enum import Enum\n\nfrom qtpy.QtWidgets import QApplication\nfrom superqt import QEnumComboBox\n\n\nclass SampleEnum(Enum):\n    first = 1\n    second = 2\n    third = 3\n\napp = QApplication([])\n\ncombo = QEnumComboBox()\ncombo.setEnumClass(SampleEnum)\ncombo.show()\n\napp.exec_()\n

Another option is to use optional enum_class argument of constructor and change

# option A:\ncombo = QEnumComboBox()\ncombo.setEnumClass(SampleEnum)\n# option B:\ncombo = QEnumComboBox(enum_class=SampleEnum)\n
"},{"location":"widgets/qenumcombobox/#allow-none","title":"Allow None","text":"

QEnumComboBox also allows using Optional type annotation:

from enum import Enum\n\nfrom superqt import QEnumComboBox\n\nclass SampleEnum(Enum):\n    first = 1\n    second = 2\n    third = 3\n\n# as usual:\n# you must create a QApplication before create a widget.\n\ncombo = QEnumComboBox()\ncombo.setEnumClass(SampleEnum, allow_none=True)\n

In this case there is added option ---- and the currentEnum() method will return None when it is selected.

"},{"location":"widgets/qenumcombobox/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qenumcombobox/#signals","title":"Signals","text":""},{"location":"widgets/qenumcombobox/#currentenumchanged","title":"currentEnumChanged","text":""},{"location":"widgets/qenumcombobox/#methods","title":"Methods","text":"

ComboBox presenting options from a python Enum.

If the Enum class does not implement __str__ then a human readable name is created from the name of the enum member, replacing underscores with spaces.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.currentEnum","title":"currentEnum() -> Optional[EnumType]","text":"

Current value as Enum member.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.enumClass","title":"enumClass() -> Optional[EnumMeta]","text":"

Return current Enum class.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.isOptional","title":"isOptional() -> bool","text":"

Return if current enum is with optional annotation.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.setCurrentEnum","title":"setCurrentEnum(value: Optional[EnumType]) -> None","text":"

Set value with Enum.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.setEnumClass","title":"setEnumClass(enum: Optional[EnumMeta], allow_none: Optional[EnumMeta] = False)","text":"

Set enum class from which members value should be selected.

"},{"location":"widgets/qlabeleddoublerangeslider/","title":"QLabeledDoubleRangeSlider","text":"

Labeled Float variant of QRangeSlider. (see that page for more details).

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledDoubleRangeSlider\n\napp = QApplication([])\n\nslider = QLabeledDoubleRangeSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 1)\nslider.setValue((0.2, 0.8))\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeleddoublerangeslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeleddoublerangeslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeleddoublerangeslider/#qlabeleddoublerangesliderlabelposition","title":"QLabeledDoubleRangeSlider.LabelPosition","text":""},{"location":"widgets/qlabeleddoublerangeslider/#qlabeleddoublerangeslideredgelabelmode","title":"QLabeledDoubleRangeSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeleddoublerangeslider/#methods","title":"Methods","text":""},{"location":"widgets/qlabeleddoublerangeslider/#superqt.QLabeledDoubleRangeSlider.decimals","title":"decimals() -> int","text":""},{"location":"widgets/qlabeleddoublerangeslider/#superqt.QLabeledDoubleRangeSlider.setDecimals","title":"setDecimals(prec: int) -> None","text":""},{"location":"widgets/qlabeleddoubleslider/","title":"QLabeledDoubleSlider","text":"

QDoubleSlider variant that shows an editable (SpinBox) label next to the slider.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledDoubleSlider\n\napp = QApplication([])\n\nslider = QLabeledDoubleSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 2.5)\nslider.setValue(1.3)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeleddoubleslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeleddoubleslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeleddoubleslider/#qlabeleddoubleslideredgelabelmode","title":"QLabeledDoubleSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeleddoubleslider/#methods","title":"Methods","text":""},{"location":"widgets/qlabeleddoubleslider/#superqt.QLabeledDoubleSlider.decimals","title":"decimals() -> int","text":""},{"location":"widgets/qlabeleddoubleslider/#superqt.QLabeledDoubleSlider.setDecimals","title":"setDecimals(prec: int) -> None","text":""},{"location":"widgets/qlabeledrangeslider/","title":"QLabeledRangeSlider","text":"

Labeled variant of QRangeSlider. (see that page for more details).

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledRangeSlider\n\napp = QApplication([])\n\nslider = QLabeledRangeSlider(Qt.Orientation.Horizontal)\nslider.setValue((20, 80))\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeledrangeslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeledrangeslider/#signals","title":"Signals","text":""},{"location":"widgets/qlabeledrangeslider/#editingfinished","title":"editingFinished","text":""},{"location":"widgets/qlabeledrangeslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeledrangeslider/#qlabeledrangesliderlabelposition","title":"QLabeledRangeSlider.LabelPosition","text":""},{"location":"widgets/qlabeledrangeslider/#qlabeledrangeslideredgelabelmode","title":"QLabeledRangeSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeledrangeslider/#methods","title":"Methods","text":"

If you find that you need to fine tune the position of the handle labels:

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.edgeLabelMode","title":"edgeLabelMode() -> EdgeLabelMode","text":"

Return current EdgeLabelMode.

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.handleLabelPosition","title":"handleLabelPosition() -> LabelPosition","text":"

Return where/whether labels are shown adjacent to slider handles.

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.setEdgeLabelMode","title":"setEdgeLabelMode(opt: EdgeLabelMode) -> None","text":"

Set EdgeLabelMode, controls what is shown at the min/max labels.

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.setHandleLabelPosition","title":"setHandleLabelPosition(opt: LabelPosition) -> None","text":"

Set where/whether labels are shown adjacent to slider handles.

"},{"location":"widgets/qlabeledslider/","title":"QLabeledSlider","text":"

QSlider variant that shows an editable (SpinBox) label next to the slider.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledSlider\n\napp = QApplication([])\n\nslider = QLabeledSlider(Qt.Orientation.Horizontal)\nslider.setValue(42)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeledslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeledslider/#signals","title":"Signals","text":""},{"location":"widgets/qlabeledslider/#editingfinished","title":"editingFinished","text":""},{"location":"widgets/qlabeledslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeledslider/#qlabeledslideredgelabelmode","title":"QLabeledSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeledslider/#methods","title":"Methods","text":""},{"location":"widgets/qlabeledslider/#superqt.QLabeledSlider.edgeLabelMode","title":"edgeLabelMode() -> EdgeLabelMode","text":"

Return current EdgeLabelMode.

"},{"location":"widgets/qlabeledslider/#superqt.QLabeledSlider.setEdgeLabelMode","title":"setEdgeLabelMode(opt: EdgeLabelMode) -> None","text":"

Set the EdgeLabelMode.

Parameters:

Name Type Description Default opt EdgeLabelMode

To show no label, use EdgeLabelMode.NoLabel. To show the value of the slider, use EdgeLabelMode.LabelIsValue. To show value / maximum, use EdgeLabelMode.LabelIsValue | EdgeLabelMode.LabelIsRange.

required"},{"location":"widgets/qlargeintspinbox/","title":"QLargeIntSpinBox","text":"

QSpinBox variant that allows to enter large integers, without overflow.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLargeIntSpinBox\n\napp = QApplication([])\n\nslider = QLargeIntSpinBox()\nslider.setRange(0, 4.53e8)\nslider.setValue(4.53e8)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlargeintspinbox/#qt-class","title":"Qt Class","text":"

QAbstractSpinBox

"},{"location":"widgets/qlargeintspinbox/#signals","title":"Signals","text":""},{"location":"widgets/qlargeintspinbox/#textchanged","title":"textChanged","text":""},{"location":"widgets/qlargeintspinbox/#valuechanged","title":"valueChanged","text":""},{"location":"widgets/qlargeintspinbox/#methods","title":"Methods","text":"

An integer spinboxes backed by unbound python integer.

Qt's built-in QSpinBox is backed by a signed 32-bit integer. This could become limiting, particularly in large dense segmentations. This class behaves like a QSpinBox backed by an unbound python int.

Does not yet support \"prefix\", \"suffix\" or \"specialValue\" like QSpinBox.

"},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.maximum","title":"maximum()","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.minimum","title":"minimum()","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setMaximum","title":"setMaximum(max)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setMinimum","title":"setMinimum(min)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setRange","title":"setRange(minimum, maximum)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setSingleStep","title":"setSingleStep(step)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setStepType","title":"setStepType(stepType: QAbstractSpinBox.StepType) -> None","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setValue","title":"setValue(value)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.singleStep","title":"singleStep()","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.stepType","title":"stepType() -> QAbstractSpinBox.StepType","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.value","title":"value()","text":""},{"location":"widgets/qquantity/","title":"QQuantity","text":"

A widget that allows the user to edit a quantity (a magnitude associated with a unit).

Note

This widget requires pint:

pip install pint\n

or

pip install superqt[quantity]\n
from qtpy.QtWidgets import QApplication\n\nfrom superqt import QQuantity\n\napp = QApplication([])\nw = QQuantity(\"1m\")\nw.show()\n\napp.exec()\n

"},{"location":"widgets/qquantity/#qt-class","title":"Qt Class","text":"

QWidget

"},{"location":"widgets/qquantity/#signals","title":"Signals","text":""},{"location":"widgets/qquantity/#unitschanged","title":"unitsChanged","text":""},{"location":"widgets/qquantity/#dimensionalitychanged","title":"dimensionalityChanged","text":""},{"location":"widgets/qquantity/#valuechanged","title":"valueChanged","text":""},{"location":"widgets/qquantity/#methods","title":"Methods","text":"

A combination QDoubleSpinBox and QComboBox for entering quantities.

For this widget, value() returns a pint.Quantity object, while setValue() accepts either a number, pint.Quantity, a string that can be parsed by pint.

Parameters:

Name Type Description Default value Union[str, Quantity, Number]

The initial value to display. If a string, it will be parsed by pint.

0 units Union[UnitsContainer, str, Quantity]

The units to use if value is a number. If a string, it will be parsed by pint. If a pint.Quantity, the units will be extracted from it.

None ureg UnitRegistry

The unit registry to use. If not provided, the registry will be extracted from value if it is a pint.Quantity, otherwise the default registry will be used.

None parent QWidget

The parent widget, by default None

None"},{"location":"widgets/qquantity/#superqt.QQuantity.dimensionality","title":"dimensionality() -> UnitsContainer","text":"

Return the current dimensionality (cast to str for nice repr).

"},{"location":"widgets/qquantity/#superqt.QQuantity.isDimensionless","title":"isDimensionless() -> bool","text":"

Return True if the current value is dimensionless.

"},{"location":"widgets/qquantity/#superqt.QQuantity.magnitude","title":"magnitude() -> Union[float, int]","text":"

Return the magnitude of the current value.

"},{"location":"widgets/qquantity/#superqt.QQuantity.magnitudeSpinBox","title":"magnitudeSpinBox() -> QDoubleSpinBox","text":"

Return the QSpinBox widget used to edit the magnitude.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setDecimals","title":"setDecimals(decimals: int) -> None","text":"

Set the number of decimals to display in the spinbox.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setMagnitude","title":"setMagnitude(magnitude: Number) -> None","text":"

Set the magnitude of the current value.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setUnits","title":"setUnits(units: Union[str, Unit, Quantity]) -> None","text":"

Set the units of the current value.

If units is None, will convert to a dimensionless quantity. Otherwise, units must be compatible with the current dimensionality.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setValue","title":"setValue(value: Union[str, Quantity, Number], units: Optional[Union[UnitsContainer, str, Quantity]] = None) -> None","text":"

Set the current value (will cast to a pint Quantity).

"},{"location":"widgets/qquantity/#superqt.QQuantity.text","title":"text() -> str","text":""},{"location":"widgets/qquantity/#superqt.QQuantity.unitRegistry","title":"unitRegistry() -> UnitRegistry","text":"

Return the pint UnitRegistry used by this widget.

"},{"location":"widgets/qquantity/#superqt.QQuantity.units","title":"units() -> Unit","text":"

Return the current units.

"},{"location":"widgets/qquantity/#superqt.QQuantity.unitsComboBox","title":"unitsComboBox() -> QComboBox","text":"

Return the QCombBox widget used to edit the units.

"},{"location":"widgets/qquantity/#superqt.QQuantity.value","title":"value() -> Quantity","text":"

Return the current value as a pint.Quantity.

"},{"location":"widgets/qrangeslider/","title":"QRangeSlider","text":"

A multi-handle slider widget than can be used to select a range of values.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QRangeSlider\n\napp = QApplication([])\n\nslider = QRangeSlider(Qt.Orientation.Horizontal)\nslider.setValue((20, 80))\nslider.show()\n\napp.exec_()\n

As QRangeSlider inherits from QtWidgets.QSlider, you can use all of the same methods available in the QSlider API. The major difference is that value() and sliderPosition() are reimplemented as tuples of int (where the length of the tuple is equal to the number of handles in the slider.)

These options are in addition to the Qt QSlider API, and control the behavior of the bar between handles.

getter setter type default description barIsVisible setBarIsVisible hideBar / showBar bool True Whether the bar between handles is visible. barMovesAllHandles setBarMovesAllHandles bool True Whether clicking on the bar moves all handles or just the nearest barIsRigid setBarIsRigid bool True Whether bar length is constant or \"elastic\" when dragging the bar beyond min/max."},{"location":"widgets/qrangeslider/#screenshots","title":"Screenshots","text":"code that generates the images below
import os\n\nfrom qtpy import QtCore\nfrom qtpy import QtWidgets as QtW\n\n# patch for Qt 5.15 on macos >= 12\nos.environ[\"USE_MAC_SLIDER_PATCH\"] = \"1\"\n\nfrom superqt import QRangeSlider  # noqa\n\nQSS = \"\"\"\nQSlider {\n    min-height: 20px;\n}\n\nQSlider::groove:horizontal {\n    border: 0px;\n    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #888, stop:1 #ddd);\n    height: 20px;\n    border-radius: 10px;\n}\n\nQSlider::handle {\n    background: qradialgradient(cx:0, cy:0, radius: 1.2, fx:0.35,\n                                fy:0.3, stop:0 #eef, stop:1 #002);\n    height: 20px;\n    width: 20px;\n    border-radius: 10px;\n}\n\nQSlider::sub-page:horizontal {\n    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #227, stop:1 #77a);\n    border-top-left-radius: 10px;\n    border-bottom-left-radius: 10px;\n}\n\nQRangeSlider {\n    qproperty-barColor: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #227, stop:1 #77a);\n}\n\"\"\"\n\nHorizontal = QtCore.Qt.Orientation.Horizontal\n\n\nclass DemoWidget(QtW.QWidget):\n    def __init__(self) -> None:\n        super().__init__()\n\n        reg_hslider = QtW.QSlider(Horizontal)\n        reg_hslider.setValue(50)\n        range_hslider = QRangeSlider(Horizontal)\n        range_hslider.setValue((20, 80))\n        multi_range_hslider = QRangeSlider(Horizontal)\n        multi_range_hslider.setValue((11, 33, 66, 88))\n        multi_range_hslider.setTickPosition(QtW.QSlider.TickPosition.TicksAbove)\n\n        styled_reg_hslider = QtW.QSlider(Horizontal)\n        styled_reg_hslider.setValue(50)\n        styled_reg_hslider.setStyleSheet(QSS)\n        styled_range_hslider = QRangeSlider(Horizontal)\n        styled_range_hslider.setValue((20, 80))\n        styled_range_hslider.setStyleSheet(QSS)\n\n        reg_vslider = QtW.QSlider(QtCore.Qt.Orientation.Vertical)\n        reg_vslider.setValue(50)\n        range_vslider = QRangeSlider(QtCore.Qt.Orientation.Vertical)\n        range_vslider.setValue((22, 77))\n\n        tick_vslider = QtW.QSlider(QtCore.Qt.Orientation.Vertical)\n        tick_vslider.setValue(55)\n        tick_vslider.setTickPosition(QtW.QSlider.TicksRight)\n        range_tick_vslider = QRangeSlider(QtCore.Qt.Orientation.Vertical)\n        range_tick_vslider.setValue((22, 77))\n        range_tick_vslider.setTickPosition(QtW.QSlider.TicksLeft)\n\n        szp = QtW.QSizePolicy.Maximum\n        left = QtW.QWidget()\n        left.setLayout(QtW.QVBoxLayout())\n        left.setContentsMargins(2, 2, 2, 2)\n        label1 = QtW.QLabel(\"Regular QSlider Unstyled\")\n        label2 = QtW.QLabel(\"QRangeSliders Unstyled\")\n        label3 = QtW.QLabel(\"Styled Sliders (using same stylesheet)\")\n        label1.setSizePolicy(szp, szp)\n        label2.setSizePolicy(szp, szp)\n        label3.setSizePolicy(szp, szp)\n        left.layout().addWidget(label1)\n        left.layout().addWidget(reg_hslider)\n        left.layout().addWidget(label2)\n        left.layout().addWidget(range_hslider)\n        left.layout().addWidget(multi_range_hslider)\n        left.layout().addWidget(label3)\n        left.layout().addWidget(styled_reg_hslider)\n        left.layout().addWidget(styled_range_hslider)\n\n        right = QtW.QWidget()\n        right.setLayout(QtW.QHBoxLayout())\n        right.setContentsMargins(15, 5, 5, 0)\n        right.layout().setSpacing(30)\n        right.layout().addWidget(reg_vslider)\n        right.layout().addWidget(range_vslider)\n        right.layout().addWidget(tick_vslider)\n        right.layout().addWidget(range_tick_vslider)\n\n        self.setLayout(QtW.QHBoxLayout())\n        self.layout().addWidget(left)\n        self.layout().addWidget(right)\n        self.setGeometry(600, 300, 580, 300)\n        self.activateWindow()\n        self.show()\n\n\nif __name__ == \"__main__\":\n\n    import sys\n    from pathlib import Path\n\n    dest = Path(\"screenshots\")\n    dest.mkdir(exist_ok=True)\n\n    app = QtW.QApplication([])\n    demo = DemoWidget()\n\n    if \"-snap\" in sys.argv:\n        import platform\n\n        QtW.QApplication.processEvents()\n        demo.grab().save(str(dest / f\"demo_{platform.system().lower()}.png\"))\n    else:\n        app.exec_()\n
"},{"location":"widgets/qrangeslider/#macos","title":"macOS","text":""},{"location":"widgets/qrangeslider/#catalina","title":"Catalina","text":""},{"location":"widgets/qrangeslider/#big-sur","title":"Big Sur","text":""},{"location":"widgets/qrangeslider/#windows","title":"Windows","text":""},{"location":"widgets/qrangeslider/#linux","title":"Linux","text":""},{"location":"widgets/qrangeslider/#qt-class","title":"Qt Class","text":"

QSlider

"},{"location":"widgets/qrangeslider/#methods","title":"Methods","text":"

MultiHandle Range Slider widget.

Same API as QSlider, but value, setValue, sliderPosition, and setSliderPosition are all sequences of integers.

The valueChanged and sliderMoved signals also both emit a tuple of integers.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barColor","title":"barColor = Property(QtGui.QBrush, _getBarColor, _setBarColor) class-attribute instance-attribute","text":"

The color of the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.applyMacStylePatch","title":"applyMacStylePatch() -> str","text":"

Apply a QSS patch to fix sliders on macos>=12 with QT < 6.

see FAQ for more details.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barIsRigid","title":"barIsRigid() -> bool","text":"

Whether bar length is constant when dragging the bar.

If False, the bar can shorten when dragged beyond min/max. Default is True.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barIsVisible","title":"barIsVisible() -> bool","text":"

Whether to show the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barMovesAllHandles","title":"barMovesAllHandles() -> bool","text":"

Whether clicking on the bar moves all handles, or just the nearest.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.hideBar","title":"hideBar() -> None","text":"

Hide the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.setBarIsRigid","title":"setBarIsRigid(val: bool = True) -> None","text":"

Whether bar length is constant when dragging the bar.

If False, the bar can shorten when dragged beyond min/max. Default is True.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.setBarMovesAllHandles","title":"setBarMovesAllHandles(val: bool = True) -> None","text":"

Whether clicking on the bar moves all handles, or just the nearest.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.setBarVisible","title":"setBarVisible(val: bool = True) -> None","text":"

Whether to show the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.showBar","title":"showBar() -> None","text":"

Show the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#type-changes","title":"Type changes","text":"

Note the following changes in types compared to the QSlider API:

value() -> Tuple[int, ...]\n
setValue(val: Sequence[int]) -> None\n
# Signal\nvalueChanged(Tuple[int, ...])\n
sliderPosition() -> Tuple[int, ...]\n
setSliderPosition(val: Sequence[int]) -> None\n
sliderMoved(Tuple[int, ...])\n
"},{"location":"widgets/qsearchablecombobox/","title":"QSearchableComboBox","text":"

QSearchableComboBox is a variant of QComboBox that allow to filter list of options by enter part of text. It could be drop in replacement for QComboBox.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QSearchableComboBox\n\napp = QApplication([])\n\ncombo = QSearchableComboBox()\ncombo.addItems([\"foo\", \"bar\", \"baz\", \"foobar\", \"foobaz\", \"barbaz\"])\ncombo.show()\n\napp.exec_()\n

"},{"location":"widgets/qsearchablecombobox/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qsearchablelistwidget/","title":"QSearchableListWidget","text":"

QSearchableListWidget is a variant of QListWidget that add text entry above list widget that allow to filter list of available options.

Due to implementation details, this widget it does not inherit directly from QListWidget but it does fully satisfy its api. The only limitation is that it cannot be used as argument of QListWidgetItem constructor.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QSearchableListWidget\n\napp = QApplication([])\n\nslider = QSearchableListWidget()\nslider.addItems([\"foo\", \"bar\", \"baz\", \"foobar\", \"foobaz\", \"barbaz\"])\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qsearchablelistwidget/#qt-class","title":"Qt Class","text":"

QWidget

"},{"location":"widgets/qsearchablelistwidget/#methods","title":"Methods","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.addItem","title":"addItem(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.addItems","title":"addItems(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.insertItem","title":"insertItem(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.insertItems","title":"insertItems(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.update_visible","title":"update_visible(text)","text":""},{"location":"widgets/qsearchabletreewidget/","title":"QSearchableTreeWidget","text":"

QSearchableTreeWidget combines a QTreeWidget and a QLineEdit for showing a mapping that can be searched by key.

This is intended to be used with a read-only mapping and be conveniently created using QSearchableTreeWidget.fromData(data). If the mapping changes, the easiest way to update this is by calling setData.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QSearchableTreeWidget\n\napp = QApplication([])\n\ndata = {\n    \"none\": None,\n    \"str\": \"test\",\n    \"int\": 42,\n    \"list\": [2, 3, 5],\n    \"dict\": {\n        \"float\": 0.5,\n        \"tuple\": (22, 99),\n        \"bool\": False,\n    },\n}\ntree = QSearchableTreeWidget.fromData(data)\ntree.show()\n\napp.exec_()\n

"},{"location":"widgets/qsearchabletreewidget/#qt-class","title":"Qt Class","text":"

QWidget

"},{"location":"widgets/qsearchabletreewidget/#methods","title":"Methods","text":"

A tree widget for showing a mapping that can be searched by key.

This is intended to be used with a read-only mapping and be conveniently created using QSearchableTreeWidget.fromData(data). If the mapping changes, the easiest way to update this is by calling setData.

The tree can be searched by entering a regular expression pattern into the filter line edit. An item is only shown if its, any of its ancestors', or any of its descendants' keys or values match this pattern. The regular expression follows the conventions described by the Qt docs: https://doc.qt.io/qt-5/qregularexpression.html#details

Attributes:

Name Type Description tree QTreeWidget

Shows the mapping as a tree of items.

filter QLineEdit

Used to filter items in the tree by matching their key against a regular expression.

"},{"location":"widgets/qsearchabletreewidget/#superqt.QSearchableTreeWidget.fromData","title":"fromData(data: Mapping, *, parent: QWidget = None) -> QSearchableTreeWidget classmethod","text":"

Make a searchable tree widget from a mapping.

"},{"location":"widgets/qsearchabletreewidget/#superqt.QSearchableTreeWidget.setData","title":"setData(data: Mapping) -> None","text":"

Update the mapping data shown by the tree.

"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"superqt","text":""},{"location":"#missing-widgets-and-components-for-pyqtpyside","title":"\"missing\" widgets and components for PyQt/PySide","text":"

This repository aims to provide high-quality community-contributed Qt widgets and components for PyQt & PySide that are not provided in the native QtWidgets module.

Components are tested on:

"},{"location":"#installation","title":"Installation","text":"
pip install superqt\n
conda install -c conda-forge superqt\n
"},{"location":"#usage","title":"Usage","text":"

See the Widgets and Utilities pages for features offered by superqt.

"},{"location":"faq/","title":"FAQ","text":""},{"location":"faq/#sliders-not-dragging-properly-on-macos-12","title":"Sliders not dragging properly on MacOS 12+","text":"Details

On MacOS Monterey, with Qt5, there is a bug that causes all sliders (including native Qt sliders) to not respond properly to drag events. See:

Superqt includes a workaround for this issue, but it is not perfect, and it requires using a custom stylesheet (which may interfere with your own styles). Note that you may not see this issue if you're already using custom stylesheets.

To opt in to the workaround, do any of the following:

from superqt.sliders import MONTEREY_SLIDER_STYLES_FIX\n\nslider.setStyleSheet(MONTEREY_SLIDER_STYLES_FIX)\n
"},{"location":"utilities/","title":"Utilities","text":""},{"location":"utilities/#font-icons","title":"Font Icons","text":"Object Description addFont Add an OTF/TTF file at to the font registry. font Create QFont for a given font-icon font family key icon Create a QIcon for font-con glyph key setTextIcon Set text on a QWidget to a specific font & glyph. IconFont Helper class that provides a standard way to create an IconFont. IconOpts Options for rendering an icon Animation Base class for adding animations to a font-icon."},{"location":"utilities/#threading-tools","title":"Threading tools","text":"Object Description ensure_main_thread Decorator that ensures a function is called in the main QApplication thread. ensure_object_thread Decorator that ensures a QObject method is called in the object's thread. FunctionWorker QRunnable with signals that wraps a simple long-running function. GeneratorWorker QRunnable with signals that wraps a long-running generator. create_worker Create a worker to run a target function in another thread. thread_worker Decorator for create_worker, turn a function into a worker."},{"location":"utilities/#miscellaneous","title":"Miscellaneous","text":"Object Description QMessageHandler A context manager to intercept messages from Qt. CodeSyntaxHighlight A QSyntaxHighlighter for code syntax highlighting. draw_colormap Function that draws a colormap into any QPaintDevice."},{"location":"utilities/cmap/","title":"Colormap utilities","text":"

See also:

"},{"location":"utilities/cmap/#superqt.cmap.draw_colormap","title":"superqt.cmap.draw_colormap(painter_or_device, cmap, rect=None, border_color=None, border_width=1, lighter=100, checkerboard_size=4)","text":"

Draw a colormap onto a QPainter or QPaintDevice.

Parameters:

Name Type Description Default painter_or_device QPainter | QPaintDevice

A QPainter instance or a QPaintDevice (e.g. a QWidget or QPixmap) onto which to paint the colormap.

required cmap Colormap | Any

cmap.Colormap instance, or anything that can be converted to one (such as a string name of a colormap in the cmap catalog). https://cmap-docs.readthedocs.io/en/latest/colormaps/#colormaplike-objects

required rect QRect | QRectF | None

A rect onto which to draw. If None, the painter.viewport() will be used. by default None

None border_color QColor | str | None

If not None, a border of color border_color and width border_width is included around the edge, by default None.

None border_width int

The width of the border to draw (provided border_color is not None), by default 2

1 lighter int

Percentage by which to lighten (or darken) the colors. Greater than 100 lightens, less than 100 darkens, by default 100 (i.e. no change).

100 checkerboard_size bool

Size (in pixels) of the checkerboard pattern to draw, by default 5. If 0, no checkerboard is drawn.

4

Examples:

from qtpy.QtGui import QPixmap\nfrom qtpy.QtWidgets import QWidget\nfrom superqt.utils import draw_colormap\n\nviridis = 'viridis'  # or cmap.Colormap('viridis')\n\nclass W(QWidget):\n    def paintEvent(self, event) -> None:\n        draw_colormap(self, viridis, event.rect())\n\n# or draw onto a QPixmap\npm = QPixmap(200, 200)\ndraw_colormap(pm, viridis)\n
"},{"location":"utilities/cmap/#superqt.cmap.QColormapLineEdit","title":"superqt.cmap.QColormapLineEdit","text":"

Bases: QLineEdit

A QLineEdit that shows a colormap swatch.

When the current text is a valid colormap name from the cmap package, a swatch of the colormap will be shown to the left of the text (if fractionalColormapWidth is less than .75) or behind the text (for when the colormap fills the full width).

If the current text is not a valid colormap name, a swatch of the fallback colormap will be shown instead (by default, a gray colormap) if fractionalColormapWidth is less than .75.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None fractional_colormap_width float

The fraction of the widget width to use for the colormap swatch. If the colormap is full width (greater than 0.75), the swatch will be drawn behind the text. Otherwise, the swatch will be drawn to the left of the text. Default is 0.33.

0.33 fallback_cmap Colormap | str | None

The colormap to use when the current text is not a recognized colormap. by default \"gray\".

'gray' missing_icon QIcon | StandardPixmap

The icon to show when the current text is not a recognized colormap and fractionalColormapWidth is less than .75. Default is a question mark.

MISSING checkerboard_size int

Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.

4"},{"location":"utilities/cmap/#superqt.cmap.QColormapItemDelegate","title":"superqt.cmap.QColormapItemDelegate","text":"

Bases: QStyledItemDelegate

Delegate that draws colormaps into a QAbstractItemView item.

Parameters:

Name Type Description Default parent QObject

The parent object.

None item_size QSize

The size hint for each item, by default QSize(80, 22).

DEFAULT_SIZE fractional_colormap_width float

The fraction of the widget width to use for the colormap swatch. If the colormap is full width (greater than 0.75), the swatch will be drawn behind the text. Otherwise, the swatch will be drawn to the left of the text. Default is 0.33.

1 padding int

The padding (in pixels) around the edge of the item, by default 1.

1 checkerboard_size int

Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.

4"},{"location":"utilities/code_syntax_highlight/","title":"CodeSyntaxHighlight","text":"

A code highlighter subclass of QSyntaxHighlighter that can be used to highlight code in a QTextEdit.

Code lexer and available styles are from pygments python library

List of available languages are available here.

List of available styles are available here.

"},{"location":"utilities/code_syntax_highlight/#example","title":"Example","text":"
from qtpy.QtGui import QColor, QPalette\nfrom qtpy.QtWidgets import QApplication, QTextEdit\n\nfrom superqt.utils import CodeSyntaxHighlight\n\napp = QApplication([])\n\ntext_area = QTextEdit()\n\nhighlight = CodeSyntaxHighlight(text_area.document(), \"python\", \"monokai\")\n\npalette = text_area.palette()\npalette.setColor(QPalette.Base, QColor(highlight.background_color))\ntext_area.setPalette(palette)\ntext_area.setText(\n\"\"\"from argparse import ArgumentParser\n\ndef main():\n    parser = ArgumentParser()\n    parser.add_argument(\"name\", help=\"Your name\")\n    args = parser.parse_args()\n    print(f\"Hello {args.name}\")\n\n\nif __name__ == \"__main__\":\n    main()\n\"\"\"\n)\n\ntext_area.show()\ntext_area.resize(400, 200)\n\napp.exec_()\n
"},{"location":"utilities/code_syntax_highlight/#qt-class","title":"Qt Class","text":"

QSyntaxHighlighter

"},{"location":"utilities/code_syntax_highlight/#methods","title":"Methods","text":""},{"location":"utilities/code_syntax_highlight/#superqt.utils.CodeSyntaxHighlight.background_color","title":"background_color property","text":""},{"location":"utilities/error_dialog_contexts/","title":"Error message context manager","text":""},{"location":"utilities/error_dialog_contexts/#superqt.utils.exceptions_as_dialog","title":"superqt.utils.exceptions_as_dialog","text":"

Bases: AbstractContextManager

Context manager that shows a dialog when an exception is raised.

See examples below for common usage patterns.

To determine whether an exception was raised or not, check the exception attribute after the context manager has exited. If use_error_message is False (the default), you can also access the dialog attribute to get/manipulate the QMessageBox instance.

Parameters:

Name Type Description Default exceptions type[BaseException] | tuple[type[BaseException], ...]

The exception(s) to catch, by default Exception (i.e. all exceptions).

Exception icon Icon

The icon to show in the QMessageBox, by default QMessageBox.Icon.Critical

Critical title str

The title of the QMessageBox, by default \"An error occurred\".

'An error occurred' msg_template str

The message to show in the QMessageBox. The message will be formatted using three variables:

The default template is the content of the exception: \"{exc_value}\"

'{exc_value}' buttons StandardButton

The buttons to show in the QMessageBox, by default QMessageBox.StandardButton.Ok

Ok parent QWidget | None

The parent widget of the QMessageBox, by default None

None use_error_message bool | QErrorMessage

Whether to use a QErrorMessage instead of a QMessageBox. By default False. QErrorMessage shows a checkbox that the user can check to prevent seeing the message again (based on the text of the formatted msg_template.) If True, the global QMessageError.qtHandler() instance is used to maintain a history of dismissed messages. You may also pass a QErrorMessage instance to use a specific instance. If use_error_message is True, or if you pass your own QErrorMessage instance, the parent argument is ignored.

False

Attributes:

Name Type Description dialog QMessageBox | None

The QMessageBox instance that was created (if use_error_message was False). This can be used, among other things, to determine the result of the dialog (e.g. dialog.result()) or to manipulate the dialog (e.g. dialog.setDetailedText(\"some text\")).

exception BaseException | None

Will hold the exception instance if an exception was raised and caught.

"},{"location":"utilities/error_dialog_contexts/#superqt.utils.exceptions_as_dialog--examplez","title":"Examplez","text":"
from qtpy.QtWidgets import QApplication\nfrom superqt.utils import exceptions_as_dialog\n\napp = QApplication([])\n\nwith exceptions_as_dialog() as ctx:\n    raise Exception(\"This will be caught and shown in a QMessageBox\")\n\n# you can access the exception instance here\nassert ctx.exception is not None\n\n# with exceptions_as_dialog(ValueError):\n#     1 / 0  # ZeroDivisionError is not caught, so this will raise\n\nwith exceptions_as_dialog(msg_template=\"Error: {exc_value}\"):\n    raise Exception(\"This message will be inserted at 'exc_value'\")\n\nfor _i in range(3):\n    with exceptions_as_dialog(AssertionError, use_error_message=True):\n        assert False, \"Uncheck the checkbox to ignore this in the future\"\n\n# use ctx.dialog to get the result of the dialog\nbtns = QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel\nwith exceptions_as_dialog(buttons=btns) as ctx:\n    raise Exception(\"This will be caught and shown in a QMessageBox\")\nprint(ctx.dialog.result())  # prints which button was clicked\n\napp.exec()  # needed only for the use_error_message example to show\n
"},{"location":"utilities/fonticon/","title":"Font icons","text":"

The superqt.fonticon module provides a set of utilities for working with font icons such as Font Awesome or Material Design Icons.

"},{"location":"utilities/fonticon/#basic-example","title":"Basic Example","text":"
from fonticon_fa5 import FA5S\n\nfrom qtpy.QtCore import QSize\nfrom qtpy.QtWidgets import QApplication, QPushButton\n\nfrom superqt.fonticon import icon, pulse\n\napp = QApplication([])\n\nbtn2 = QPushButton()\nbtn2.setIcon(icon(FA5S.smile, color=\"blue\"))\nbtn2.setIconSize(QSize(225, 225))\nbtn2.show()\n\napp.exec()\n
"},{"location":"utilities/fonticon/#font-icon-plugins","title":"Font Icon plugins","text":"

Ready-made fonticon packs are available as plugins.

A great way to search across most available icons libraries from a single search interface is to use glyphsearch: https://glyphsearch.com/

If a font library you'd like to use is unavailable as a superqt plugin, please open a feature request

"},{"location":"utilities/fonticon/#font-awesome-6","title":"Font Awesome 6","text":"

Browse available icons at https://fontawesome.com/v6/search

pip install fonticon-fontawesome6\n
"},{"location":"utilities/fonticon/#font-awesome-5","title":"Font Awesome 5","text":"

Browse available icons at https://fontawesome.com/v5/search

pip install fonticon-fontawesome5\n
"},{"location":"utilities/fonticon/#material-design-icons-7","title":"Material Design Icons 7","text":"

Browse available icons at https://materialdesignicons.com/

pip install fonticon-materialdesignicons7\n
"},{"location":"utilities/fonticon/#material-design-icons-6","title":"Material Design Icons 6","text":"

Browse available icons at https://materialdesignicons.com/ (note that the search defaults to v7, see changes from v6 in the changelog)

pip install fonticon-materialdesignicons6\n
"},{"location":"utilities/fonticon/#see-also","title":"See also","text":"

superqt.fonticon is a pluggable system, and font icon packs may use the \"superqt.fonticon\" entry point to register themselves with superqt. See fonticon-cookiecutter for a template, or look through the following repos for examples:

"},{"location":"utilities/fonticon/#api","title":"API","text":"

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

"},{"location":"utilities/fonticon/#superqt.fonticon.icon","title":"superqt.fonticon.icon(glyph_key, scale_factor=DEFAULT_SCALING_FACTOR, color=None, opacity=1, animation=None, transform=None, states=None)","text":"

Create a QIcon for glyph_key, with a number of optional settings.

The glyph_key (e.g. 'fa5s.smile') represents a Font-family & style, and a glyph. In most cases, the key should be provided by a plugin in the environment, like:

...but fonts can also be added manually using addFont.

Parameters:

Name Type Description Default glyph_key str

String encapsulating a font-family, style, and glyph. e.g. 'fa5s.smile'.

required scale_factor float

Scale factor (fraction of widget height), When widget icon is painted on widget, it will use font.setPixelSize(round(wdg.height() * scale_factor)). by default 0.875.

DEFAULT_SCALING_FACTOR color ValidColor

Color for the font, by default None. (e.g. The default QColor) Valid color types include QColor, int, str, Qt.GlobalColor, tuple (of integer: RGB[A]) (anything that can be passed to QColor).

None opacity float

Opacity of icon, by default 1

1 animation Animation

Animation for the icon. A subclass of superqt.fonticon.Animation, that provides a concrete animate method. (see \"spin\" and \"pulse\" for examples). by default None.

None transform QTransform

A QTransform to apply when painting the icon, by default None

None states dict

Provide additional styling for the icon in different states. states must be a mapping of string to dict, where:

Missing keys in the state dicts will be taken from the default options, provided by the parameters above.

None

Returns:

Type Description QFontIcon

A subclass of QIcon. Can be used wherever QIcons are used, such as widget.setIcon()

Examples:

simple example (using the string 'fa5s.smile' assumes the fonticon-fontawesome5 plugin is installed)

>>> btn = QPushButton()\n>>> btn.setIcon(icon('fa5s.smile'))\n

can also directly import from fonticon_fa5

>>> from fonticon_fa5 import FA5S\n>>> btn.setIcon(icon(FA5S.smile))\n

with animation

>>> btn2 = QPushButton()\n>>> btn2.setIcon(icon(FA5S.spinner, animation=pulse(btn2)))\n

complicated example

>>> btn = QPushButton()\n>>> btn.setIcon(\n...     icon(\n...         FA5S.ambulance,\n...         color=\"blue\",\n...         states={\n...             \"active\": {\n...                 \"glyph\": FA5S.bath,\n...                 \"color\": \"red\",\n...                 \"scale_factor\": 0.5,\n...                 \"animation\": pulse(btn),\n...             },\n...             \"disabled\": {\n...                 \"color\": \"green\",\n...                 \"scale_factor\": 0.8,\n...                 \"animation\": spin(btn)\n...             },\n...         },\n...     )\n... )\n>>> btn.setIconSize(QSize(256, 256))\n>>> btn.show()\n
"},{"location":"utilities/fonticon/#superqt.fonticon.setTextIcon","title":"superqt.fonticon.setTextIcon(widget, glyph_key, size=None)","text":"

Set text on a widget to a specific font & glyph.

This is an alternative to setting a QIcon with a pixmap. It may be easier to combine with dynamic stylesheets.

Parameters:

Name Type Description Default widget QWidget

A widget supporting a setText method.

required glyph_key str

String encapsulating a font-family, style, and glyph. e.g. 'fa5s.smile'.

required size int

Size for QFont. passed to setPixelSize, by default None

None"},{"location":"utilities/fonticon/#superqt.fonticon.font","title":"superqt.fonticon.font(font_prefix, size=None)","text":"

Create QFont for font_prefix.

Parameters:

Name Type Description Default font_prefix str

Font_prefix, such as 'fa5s' or 'mdi6', representing a font-family and style.

required size int

Size for QFont. passed to setPixelSize, by default None

None

Returns:

Type Description QFont

QFont instance that can be used to add fonticons to widgets.

"},{"location":"utilities/fonticon/#superqt.fonticon.IconOpts","title":"superqt.fonticon.IconOpts dataclass","text":"

Options for rendering an icon.

Parameters:

Name Type Description Default glyph_key str

The key of the glyph to use, e.g. 'fa5s.smile', by default None

_Unset scale_factor float

The scale factor to use, by default None

_Unset color ValidColor

The color to use, by default None. Colors may be specified as a string, QColor, Qt.GlobalColor, or a 3 or 4-tuple of integers.

_Unset opacity float

The opacity to use, by default None

_Unset animation Animation

The animation to use, by default None

_Unset"},{"location":"utilities/fonticon/#superqt.fonticon.addFont","title":"superqt.fonticon.addFont(filepath, prefix, charmap=None)","text":"

Add OTF/TTF file at filepath to the registry under prefix.

If you'd like to later use a fontkey in the form of prefix.some-name, then charmap must be provided and provide a mapping for all of the glyph names to their unicode numbers. If a charmap is not provided, glyphs must be directly accessed with their unicode as something like key.\uffff.

Note

in most cases, users will not need this. Instead, they should install a font plugin, like:

Parameters:

Name Type Description Default filepath str

Path to an OTF or TTF file containing the fonts

required prefix str

A prefix that will represent this font file when used for lookup. For example, 'fa5s' for 'Font-Awesome 5 Solid'.

required charmap Dict[str, str]

optional mapping for all of the glyph names to their unicode numbers. See note above.

None

Returns:

Type Description (Tuple[str, str], optional)

font-family and font-style for the file just registered, or None if something goes wrong.

"},{"location":"utilities/fonticon/#animations","title":"Animations","text":"

the animation parameter to icon() accepts a subclass of Animation that will be

options: heading_level: 3

options: heading_level: 3

options: heading_level: 3

"},{"location":"utilities/fonticon/#superqt.fonticon.Animation","title":"superqt.fonticon.Animation","text":"

Bases: ABC

Base icon animation class.

"},{"location":"utilities/fonticon/#superqt.fonticon.Animation.animate","title":"animate(painter) abstractmethod","text":"

Setup and start the timer for the animation.

"},{"location":"utilities/fonticon/#superqt.fonticon.pulse","title":"superqt.fonticon.pulse","text":"

Bases: spin

Animation that spins an icon in slower, discrete steps.

"},{"location":"utilities/fonticon/#superqt.fonticon.spin","title":"superqt.fonticon.spin","text":"

Bases: Animation

Animation that smoothly spins an icon.

"},{"location":"utilities/qmessagehandler/","title":"QMessageHandler","text":""},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler","title":"superqt.utils.QMessageHandler","text":"

A context manager to intercept messages from Qt.

Parameters:

Name Type Description Default logger Logger

If provided, intercepted messages will be logged with logger at the corresponding python log level, by default None

None

Attributes:

Name Type Description records list of tuple

Captured messages. This is a 3-tuple of: (log_level: int, message: str, context: dict)

Examples:

>>> handler = QMessageHandler()\n>>> handler.install()  # now all Qt output will be available at mh.records\n
>>> with QMessageHandler() as handler:  # temporarily install\n...     ...\n
>>> logger = logging.getLogger(__name__)\n>>> with QMessageHandler(logger):  # re-reoute Qt messages to a python logger.\n...    ...\n
"},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler.__enter__","title":"__enter__()","text":"

Enter a context with this handler installed.

"},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler.install","title":"install()","text":"

Install this handler (override the current QtMessageHandler).

"},{"location":"utilities/qmessagehandler/#superqt.utils.QMessageHandler.uninstall","title":"uninstall()","text":"

Uninstall this handler, restoring the previous handler.

"},{"location":"utilities/signal_utils/","title":"Signal Utilities","text":""},{"location":"utilities/signal_utils/#superqt.utils.signals_blocked","title":"superqt.utils.signals_blocked(obj)","text":"

Context manager to temporarily block signals emitted by QObject: obj.

Parameters:

Name Type Description Default obj QObject

The QObject whose signals should be blocked.

required

Examples:

from qtpy.QtWidgets import QSpinBox\nfrom superqt import signals_blocked\n\nspinbox = QSpinBox()\nwith signals_blocked(spinbox):\n    spinbox.setValue(10)\n
"},{"location":"utilities/thread_decorators/","title":"Threading decorators","text":"

superqt provides two decorators that help to ensure that given function is running in the desired thread:

"},{"location":"utilities/thread_decorators/#ensure_main_thread","title":"ensure_main_thread","text":"

ensure_main_thread ensures that the decorated function/method runs in the main thread

"},{"location":"utilities/thread_decorators/#ensure_object_thread","title":"ensure_object_thread","text":"

ensure_object_thread ensures that a decorated bound method of a QObject runs in the thread in which the instance lives (see qt documentation for details).

"},{"location":"utilities/thread_decorators/#usage","title":"Usage","text":"

By default, functions are executed asynchronously (they return immediately with an instance of concurrent.futures.Future).

To block and wait for the result, see Synchronous mode

from qtpy.QtCore import QObject\nfrom superqt import ensure_main_thread, ensure_object_thread\n\n@ensure_main_thread\ndef sample_function():\n    print(\"This function will run in main thread\")\n\n\nclass SampleObject(QObject):\n    def __init__(self):\n        super().__init__()\n        self._value = 1\n\n    @ensure_main_thread\n    def sample_method1(self):\n        print(\"This method will run in main thread\")\n\n    @ensure_object_thread\n    def sample_method3(self):\n        import time\n        print(\"sleeping\")\n        time.sleep(1)\n        print(\"This method will run in object thread\")\n\n    @property\n    def value(self):\n        print(\"return value\")\n        return self._value\n\n    @value.setter\n    @ensure_object_thread\n    def value(self, value):\n        print(\"this setter will run in object thread\")\n        self._value = value\n

As can be seen in this example these decorators can also be used for setters.

These decorators should not be used as replacement of Qt Signals but rather to interact with Qt objects from non Qt code.

"},{"location":"utilities/thread_decorators/#synchronous-mode","title":"Synchronous mode","text":"

If you'd like for the program to block and wait for the result of your function call, use the await_return=True parameter, and optionally specify a timeout.

Important

Using synchronous mode may significantly impact performance.

from superqt import ensure_main_thread\n\n@ensure_main_thread\ndef sample_function1():\n    return 1\n\n@ensure_main_thread(await_return=True)\ndef sample_function2():\n    return 2\n\nassert sample_function1() is None\nassert sample_function2() == 2\n\n# optionally, specify a timeout\n@ensure_main_thread(await_return=True, timeout=10000)\ndef sample_function():\n    return 1\n
"},{"location":"utilities/threading/","title":"Thread workers","text":"

The objects in this module provide utilities for running tasks in a separate thread. In general (with the exception of new_worker_qthread), everything here wraps Qt's QRunnable API.

The highest level object is the @thread_worker decorator. It was originally written for napari, and was later extracted into superqt. You may also be interested in reading the napari documentation on this feature, which provides a more in-depth/introductory usage guide.

For additional control, you can create your own FunctionWorker or GeneratorWorker objects.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase","title":"superqt.utils.WorkerBase","text":"

Bases: QRunnable, Generic[_R]

Base class for creating a Worker that can run in another thread.

Parameters:

Name Type Description Default SignalsClass type

A QObject subclass that contains signals, by default WorkerBaseSignals

WorkerBaseSignals

Attributes:

Name Type Description signals WorkerBaseSignals

signal emitter object. To allow identify which worker thread emitted signal.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.abort_requested","title":"abort_requested: bool property","text":"

Whether the worker has been requested to stop.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.is_running","title":"is_running: bool property","text":"

Whether the worker has been started.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.__getattr__","title":"__getattr__(name)","text":"

Pass through attr requests to signals to simplify connection API.

The goal is to enable worker.yielded.connect instead of worker.signals.yielded.connect. Because multiple inheritance of Qt classes is not well supported in PyQt, we have to use composition here (signals are provided by QObjects, and QRunnable is not a QObject). So this passthrough allows us to connect to signals on the _signals object.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.await_workers","title":"await_workers(msecs=None) classmethod","text":"

Ask all workers to quit, and wait up to msec for quit.

Attempts to clean up all running workers by calling worker.quit() method. Any workers in the WorkerBase._worker_set set will have this method.

By default, this function will block indefinitely, until worker threads finish. If a timeout is provided, a RuntimeError will be raised if the workers do not gracefully exit in the time requests, but the threads will NOT be killed. It is (currently) left to the user to use their OS to force-quit rogue threads.

Important

If the user does not put any yields in their function, and the function is super long, it will just hang... For instance, there's no graceful way to kill this thread in python:

@thread_worker\ndef ZZZzzz():\n    time.sleep(10000000)\n

This is why it's always advisable to use a generator that periodically yields for long-running computations in another thread.

See this stack-overflow post for a good discussion on the difficulty of killing a rogue python thread:

Parameters:

Name Type Description Default msecs int

Waits up to msecs milliseconds for all threads to exit and removes all threads from the thread pool. If msecs is None (the default), the timeout is ignored (waits for the last thread to exit).

None

Raises:

Type Description RuntimeError

If a timeout is provided and workers do not quit successfully within the time allotted.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.quit","title":"quit()","text":"

Send a request to abort the worker.

Note

It is entirely up to subclasses to honor this method by checking self.abort_requested periodically in their worker.work method, and exiting if True.

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.run","title":"run()","text":"

Start the worker.

The end-user should never need to call this function. But it cannot be made private or renamed, since it is called by Qt.

The order of method calls when starting a worker is:

   calls QThreadPool.globalInstance().start(worker)\n   |               triggered by the QThreadPool.start() method\n   |               |             called by worker.run\n   |               |             |\n   V               V             V\n   worker.start -> worker.run -> worker.work\n

This is the function that actually gets called when calling QThreadPool.start(worker). It simply wraps the work() method, and emits a few signals. Subclasses should NOT override this method (except with good reason), and instead should implement work().

"},{"location":"utilities/threading/#superqt.utils.WorkerBase.start","title":"start()","text":"

Start this worker in a thread and add it to the global threadpool.

The order of method calls when starting a worker is:

   calls QThreadPool.globalInstance().start(worker)\n   |               triggered by the QThreadPool.start() method\n   |               |             called by worker.run\n   |               |             |\n   V               V             V\n   worker.start -> worker.run -> worker.work\n
"},{"location":"utilities/threading/#superqt.utils.WorkerBase.work","title":"work()","text":"

Main method to execute the worker.

The end-user should never need to call this function. But subclasses must implement this method (See GeneratorFunction.work for an example implementation). Minimally, it should check self.abort_requested periodically and exit if True.

Examples:

class MyWorker(WorkerBase):\n\n    def work(self):\n        i = 0\n        while True:\n            if self.abort_requested:\n                self.aborted.emit()\n                break\n            i += 1\n            if i > max_iters:\n                break\n            time.sleep(0.5)\n
"},{"location":"utilities/threading/#superqt.utils.FunctionWorker","title":"superqt.utils.FunctionWorker","text":"

Bases: WorkerBase[_R]

QRunnable with signals that wraps a simple long-running function.

Note

FunctionWorker does not provide a way to stop a very long-running function (e.g. time.sleep(10000)). So whenever possible, it is better to implement your long running function as a generator that yields periodically, and use the GeneratorWorker instead.

Parameters:

Name Type Description Default func Callable

A function to call in another thread

required *args

will be passed to the function

() **kwargs

will be passed to the function

{}

Raises:

Type Description TypeError

If func is a generator function and not a regular function.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker","title":"superqt.utils.GeneratorWorker","text":"

Bases: WorkerBase, Generic[_Y, _S, _R]

QRunnable with signals that wraps a long-running generator.

Provides a convenient way to run a generator function in another thread, while allowing 2-way communication between threads, using plain-python generator syntax in the original function.

Parameters:

Name Type Description Default func callable

The function being run in another thread. May be a generator function.

required SignalsClass type

A QObject subclass that contains signals, by default GeneratorWorkerSignals

GeneratorWorkerSignals *args

Will be passed to func on instantiation

() **kwargs

Will be passed to func on instantiation

{}"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.is_paused","title":"is_paused: bool property","text":"

Whether the worker is currently paused.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.pause","title":"pause()","text":"

Request to pause the worker.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.resume","title":"resume()","text":"

Send a request to resume the worker.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.send","title":"send(value)","text":"

Send a value into the function (if a generator was used).

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.toggle_pause","title":"toggle_pause()","text":"

Request to pause the worker if playing or resume if paused.

"},{"location":"utilities/threading/#superqt.utils.GeneratorWorker.work","title":"work()","text":"

Core event loop that calls the original function.

Enters a continual loop, yielding and returning from the original function. Checks for various events (quit, pause, resume, etc...). (To clarify: we are creating a rudimentary event loop here because there IS NO Qt event loop running in the other thread to hook into)

"},{"location":"utilities/threading/#convenience-functions","title":"Convenience functions","text":""},{"location":"utilities/threading/#superqt.utils.thread_worker","title":"superqt.utils.thread_worker(function=None, start_thread=None, connect=None, worker_class=None, ignore_errors=False)","text":"

Decorator that runs a function in a separate thread when called.

When called, the decorated function returns a WorkerBase. See create_worker for additional keyword arguments that can be used when calling the function.

The returned worker will have these signals:

It will also have a worker.start() method that can be used to start execution of the function in another thread. (useful if you need to connect callbacks to signals prior to execution)

If the decorated function is a generator, the returned worker will also provide these signals:

And these methods:

Parameters:

Name Type Description Default function callable

Function to call in another thread. For communication between threads may be a generator function.

None start_thread bool

Whether to immediaetly start the thread. If False, the returned worker must be manually started with worker.start(). by default it will be False if the _connect argument is None, otherwise True.

None connect Dict[str, Union[Callable, Sequence]]

A mapping of \"signal_name\" -> callable or list of callable: callback functions to connect to the various signals offered by the worker class. by default None

None worker_class Type[WorkerBase]

The WorkerBase to instantiate, by default FunctionWorker will be used if func is a regular function, and GeneratorWorker will be used if it is a generator.

None ignore_errors bool

If False (the default), errors raised in the other thread will be reraised in the main thread (makes debugging significantly easier).

False

Returns:

Type Description callable

function that creates a worker, puts it in a new thread and returns the worker instance.

Examples:

@thread_worker\ndef long_function(start, end):\n    # do work, periodically yielding\n    i = start\n    while i <= end:\n        time.sleep(0.1)\n        yield i\n\n    # do teardown\n    return 'anything'\n\n# call the function to start running in another thread.\nworker = long_function()\n\n# connect signals here if desired... or they may be added using the\n# `connect` argument in the `@thread_worker` decorator... in which\n# case the worker will start immediately when long_function() is called\nworker.start()\n
"},{"location":"utilities/threading/#superqt.utils.create_worker","title":"superqt.utils.create_worker(func, *args, _start_thread=None, _connect=None, _worker_class=None, _ignore_errors=False, **kwargs)","text":"

Convenience function to start a function in another thread.

By default, uses FunctionWorker for functions and GeneratorWorker for generators, but a custom WorkerBase subclass may be provided. If so, it must be a subclass of WorkerBase, which defines a standard set of signals and a run method.

Parameters:

Name Type Description Default func Callable

The function to call in another thread.

required _start_thread bool

Whether to immediaetly start the thread. If False, the returned worker must be manually started with worker.start(). by default it will be False if the _connect argument is None, otherwise True.

None _connect Dict[str, Union[Callable, Sequence]]

A mapping of \"signal_name\" -> callable or list of callable: callback functions to connect to the various signals offered by the worker class. by default None

None _worker_class type of `GeneratorWorker` or `FunctionWorker`

The WorkerBase to instantiate, by default FunctionWorker will be used if func is a regular function, and GeneratorWorker will be used if it is a generator.

None _ignore_errors bool

If False (the default), errors raised in the other thread will be reraised in the main thread (makes debugging significantly easier).

False *args

will be passed to func

() **kwargs

will be passed to func

{}

Returns:

Name Type Description worker WorkerBase

An instantiated worker. If _start_thread was False, the worker will have a .start() method that can be used to start the thread.

Raises:

Type Description TypeError

If a worker_class is provided that is not a subclass of WorkerBase.

TypeError

If _connect is provided and is not a dict of {str: callable}

Examples:

def long_function(duration):\n    import time\n    time.sleep(duration)\n\nworker = create_worker(long_function, 10)\n
"},{"location":"utilities/threading/#superqt.utils.new_worker_qthread","title":"superqt.utils.new_worker_qthread(Worker, *args, _start_thread=False, _connect=None, **kwargs)","text":"

Convenience function to start a worker in a QThread.

thread, not as the actual code or object that runs in that thread. The QThread object is created on the main thread and lives there.

Worker objects which derive from QObject are the things that actually do the work. They can be moved to a QThread as is done here.

Mostly ignorable detail

While the signals/slots syntax of the worker looks very similar to standard \"single-threaded\" signals & slots, note that inter-thread signals and slots (automatically) use an event-based QueuedConnection, while intra-thread signals use a DirectConnection. See Signals and Slots Across Threads

Parameters:

Name Type Description Default Worker QObject

QObject type that implements a work() method. The Worker should also emit a finished signal when the work is done.

required _start_thread bool

If True, thread will be started immediately, otherwise, thread must be manually started with thread.start().

False _connect dict

Optional dictionary of {signal: function} to connect to the new worker. for instance: _connect = {'incremented': myfunc} will result in: worker.incremented.connect(myfunc)

None *args

will be passed to the Worker class on instantiation.

() **kwargs

will be passed to the Worker class on instantiation.

{}

Returns:

Name Type Description worker WorkerBase

The created worker.

thread QThread

The thread on which the worker is running.

Examples:

Create some QObject that has a long-running work method:

class Worker(QObject):\n\n    finished = Signal()\n    increment = Signal(int)\n\n    def __init__(self, argument):\n        super().__init__()\n        self.argument = argument\n\n    @Slot()\n    def work(self):\n        # some long running task...\n        import time\n        for i in range(10):\n            time.sleep(1)\n            self.increment.emit(i)\n        self.finished.emit()\n\nworker, thread = new_worker_qthread(\n    Worker,\n    'argument',\n    _start_thread=True,\n    _connect={'increment': print},\n)\n
"},{"location":"utilities/throttling/","title":"Throttling & Debouncing","text":"

These utilities allow you to throttle or debounce a function. This is useful when you have a function that is called multiple times in a short period of time, and you want to make sure it is only \"actually\" called once (or at least no more than a certain frequency).

For background on throttling and debouncing, see:

"},{"location":"utilities/throttling/#superqt.utils.qdebounced","title":"superqt.utils.qdebounced(func=None, timeout=100, leading=False, timer_type=Qt.TimerType.PreciseTimer, parent=None)","text":"

Creates a debounced function that delays invoking func.

func will not be invoked until timeout ms have elapsed since the last time the debounced function was invoked.

The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Options indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

This decorator may be used with or without parameters.

Parameters:

Name Type Description Default func Callable

A function to throttle

None timeout int

Timeout in milliseconds to wait before allowing another call, by default 100

100 leading bool

Whether to invoke the function on the leading edge of the wait timer, by default False

False timer_type TimerType

The timer type. by default Qt.TimerType.PreciseTimer One of: - Qt.PreciseTimer: Precise timers try to keep millisecond accuracy - Qt.CoarseTimer: Coarse timers try to keep accuracy within 5% of the desired interval - Qt.VeryCoarseTimer: Very coarse timers only keep full second accuracy

PreciseTimer parent QObject | None

Parent object for timer. If using qthrottled as function it may be usefull for cleaning data

None"},{"location":"utilities/throttling/#superqt.utils.qthrottled","title":"superqt.utils.qthrottled(func=None, timeout=100, leading=True, timer_type=Qt.TimerType.PreciseTimer, parent=None)","text":"

Creates a throttled function that invokes func at most once per timeout.

The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

This decorator may be used with or without parameters.

Parameters:

Name Type Description Default func Callable

A function to throttle

None timeout int

Timeout in milliseconds to wait before allowing another call, by default 100

100 leading bool

Whether to invoke the function on the leading edge of the wait timer, by default True

True timer_type TimerType

The timer type. by default Qt.TimerType.PreciseTimer One of: - Qt.PreciseTimer: Precise timers try to keep millisecond accuracy - Qt.CoarseTimer: Coarse timers try to keep accuracy within 5% of the desired interval - Qt.VeryCoarseTimer: Very coarse timers only keep full second accuracy

PreciseTimer parent QObject | None

Parent object for timer. If using qthrottled as function it may be usefull for cleaning data

None"},{"location":"utilities/throttling/#superqt.utils.QSignalDebouncer","title":"superqt.utils.QSignalDebouncer","text":"

Bases: GenericSignalThrottler

A Signal Debouncer.

This object's triggered signal will not be emitted until self.timeout() milliseconds have elapsed since the last time triggered was emitted.

"},{"location":"utilities/throttling/#superqt.utils.QSignalThrottler","title":"superqt.utils.QSignalThrottler","text":"

Bases: GenericSignalThrottler

A Signal Throttler.

This object's triggered signal will emit at most once per timeout (set with setTimeout()).

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler","title":"superqt.utils._throttler.GenericSignalThrottler","text":"

Bases: QObject

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.cancel","title":"cancel()","text":"

Cancel any pending emissions.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.emissionPolicy","title":"emissionPolicy()","text":"

Return the emission policy (trailing or leading).

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.flush","title":"flush()","text":"

Force emission of any pending emissions.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.kind","title":"kind()","text":"

Return the kind of throttler (throttler or debouncer).

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.setTimeout","title":"setTimeout(timeout)","text":"

Set timeout in milliseconds.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.setTimerType","title":"setTimerType(timerType)","text":"

Set current Qt.TimerType.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.throttle","title":"throttle()","text":"

Emit triggered if not running, then start timer.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.timeout","title":"timeout()","text":"

Return current timeout in milliseconds.

"},{"location":"utilities/throttling/#superqt.utils._throttler.GenericSignalThrottler.timerType","title":"timerType()","text":"

Return current Qt.TimerType.

"},{"location":"widgets/","title":"Widgets","text":"

The following are QWidget subclasses:

"},{"location":"widgets/#sliders-and-numerical-inputs","title":"Sliders and Numerical Inputs","text":"Widget Description QDoubleRangeSlider Multi-handle slider for float values QDoubleSlider Slider for float values QLabeledDoubleRangeSlider QDoubleRangeSlider variant with editable labels for each handle QLabeledDoubleSlider QSlider for float values with editable QSpinBox with the current value QLabeledRangeSlider QRangeSlider variant, with editable labels for each handle QLabeledSlider QSlider with editable QSpinBox that shows the current value QLargeIntSpinBox QSpinbox that accepts arbitrarily large integers QRangeSlider Multi-handle slider QQuantity Pint-backed quantity widget (magnitude combined with unit dropdown)"},{"location":"widgets/#labels-and-categorical-inputs","title":"Labels and categorical inputs","text":"Widget Description QElidingLabel A QLabel variant that will elide text (add \u2026) to fit width. QEnumComboBox QComboBox that populates the combobox from a python Enum QSearchableComboBox QComboBox variant that filters available options based on text input QSearchableListWidget QListWidget variant with search field that filters available options QSearchableTreeWidget QTreeWidget variant with search field that filters available options QColorComboBox QComboBox to select from a specified set of colors QColormapComboBox QComboBox to select from a specified set of colormaps."},{"location":"widgets/#frames-and-containers","title":"Frames and containers","text":"Widget Description QCollapsible A collapsible widget to hide and unhide child widgets."},{"location":"widgets/colormap_catalog/","title":"CmapCatalogComboBox","text":"

Searchable QComboBox variant that contains the entire cmap colormap catalog

requires cmap

This widget uses the cmap library to provide colormaps. You can install it with:

# use the `cmap` extra to include colormap support\npip install superqt[cmap]\n

You can limit the colormaps shown by setting the categories or interpolation keyword arguments.

from qtpy.QtWidgets import QApplication\n\nfrom superqt.cmap import CmapCatalogComboBox\n\napp = QApplication([])\n\ncatalog_combo = CmapCatalogComboBox(interpolation=\"linear\")\ncatalog_combo.setCurrentText(\"viridis\")\ncatalog_combo.show()\n\napp.exec()\n

"},{"location":"widgets/colormap_catalog/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/colormap_catalog/#signals","title":"Signals","text":""},{"location":"widgets/colormap_catalog/#currentcolormapchanged","title":"currentColormapChanged","text":""},{"location":"widgets/colormap_catalog/#methods","title":"Methods","text":"

A combo box for selecting a colormap from the entire cmap catalog.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None prefer_short_names bool

If True (default), short names (without the namespace prefix) will be preferred over fully qualified names. In cases where the same short name is used in multiple namespaces, they will all be referred to by their fully qualified (namespaced) name.

True categories Container[Category]

If provided, only return names from the given categories.

() interpolation Interpolation

If provided, only return names that have the given interpolation method.

None"},{"location":"widgets/colormap_catalog/#superqt.cmap.CmapCatalogComboBox.currentColormap","title":"currentColormap() -> Colormap | None","text":"

Returns the currently selected Colormap or None if not yet selected.

"},{"location":"widgets/qcollapsible/","title":"QCollapsible","text":"

Collapsible QFrame that can be expanded or collapsed by clicking on the header.

from qtpy.QtWidgets import QApplication, QLabel, QPushButton\n\nfrom superqt import QCollapsible\n\napp = QApplication([])\n\ncollapsible = QCollapsible(\"Advanced analysis\")\ncollapsible.addWidget(QLabel(\"This is the inside of the collapsible frame\"))\nfor i in range(10):\n    collapsible.addWidget(QPushButton(f\"Content button {i + 1}\"))\n\ncollapsible.expand(animate=False)\ncollapsible.show()\napp.exec_()\n

"},{"location":"widgets/qcollapsible/#qt-class","title":"Qt Class","text":"

QFrame

"},{"location":"widgets/qcollapsible/#signals","title":"Signals","text":""},{"location":"widgets/qcollapsible/#toggled","title":"toggled","text":""},{"location":"widgets/qcollapsible/#methods","title":"Methods","text":"

A collapsible widget to hide and unhide child widgets.

A signal is emitted when the widget is expanded (True) or collapsed (False).

Based on https://stackoverflow.com/a/68141638

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.addWidget","title":"addWidget(widget: QWidget) -> None","text":"

Add a widget to the central content widget's layout.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.collapse","title":"collapse(animate: bool = True) -> None","text":"

Collapse (hide) the collapsible section.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.collapsedIcon","title":"collapsedIcon() -> QIcon","text":"

Returns the icon used when the widget is collapsed.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.content","title":"content() -> QWidget","text":"

Return the current content widget.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.expand","title":"expand(animate: bool = True) -> None","text":"

Expand (show) the collapsible section.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.expandedIcon","title":"expandedIcon() -> QIcon","text":"

Returns the icon used when the widget is expanded.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.isExpanded","title":"isExpanded() -> bool","text":"

Return whether the collapsible section is visible.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.locked","title":"locked() -> bool","text":"

Return True if collapse/expand is disabled.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.removeWidget","title":"removeWidget(widget: QWidget) -> None","text":"

Remove widget from the central content widget's layout.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setCollapsedIcon","title":"setCollapsedIcon(icon: Optional[Union[QIcon, str]] = None) -> None","text":"

Set the icon on the toggle button when the widget is collapsed.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setContent","title":"setContent(content: QWidget) -> None","text":"

Replace central widget (the widget that gets expanded/collapsed).

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setDuration","title":"setDuration(msecs: int) -> None","text":"

Set duration of the collapse/expand animation.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setEasingCurve","title":"setEasingCurve(easing: QEasingCurve) -> None","text":"

Set the easing curve for the collapse/expand animation.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setExpandedIcon","title":"setExpandedIcon(icon: Optional[Union[QIcon, str]] = None) -> None","text":"

Set the icon on the toggle button when the widget is expanded.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setLocked","title":"setLocked(locked: bool = True) -> None","text":"

Set whether collapse/expand is disabled.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.setText","title":"setText(text: str) -> None","text":"

Set the text of the toggle button.

"},{"location":"widgets/qcollapsible/#superqt.QCollapsible.text","title":"text() -> str","text":"

Return the text of the toggle button.

"},{"location":"widgets/qcolorcombobox/","title":"QColorComboBox","text":"

QComboBox designed to select from a specific set of colors.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QColorComboBox\n\napp = QApplication([])\n\ncolors = QColorComboBox()\ncolors.addColors(['red', 'green', 'blue'])\n\n# show an \"Add Color\" item that opens a QColorDialog when clicked\ncolors.setUserColorsAllowed(True)\n\n# emits a QColor when changed\ncolors.currentColorChanged.connect(print)\ncolors.show()\n\napp.exec_()\n

"},{"location":"widgets/qcolorcombobox/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qcolorcombobox/#signals","title":"Signals","text":""},{"location":"widgets/qcolorcombobox/#currentcolorchanged","title":"currentColorChanged","text":""},{"location":"widgets/qcolorcombobox/#enums","title":"Enums","text":""},{"location":"widgets/qcolorcombobox/#qcolorcomboboxinvalidcolorpolicy","title":"QColorComboBox.InvalidColorPolicy","text":""},{"location":"widgets/qcolorcombobox/#methods","title":"Methods","text":"

A drop down menu for selecting colors.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None allow_user_colors bool

Whether to show an \"Add Color\" item that opens a QColorDialog when clicked. Whether the user can add custom colors by clicking the \"Add Color\" item. Default is False. Can also be set with setUserColorsAllowed.

False add_color_text str

The text to display for the \"Add Color\" item. Default is \"Add Color...\".

'Add Color...'"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.addColor","title":"addColor(color: Any) -> None","text":"

Adds the color to the QComboBox.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.addColors","title":"addColors(colors: Sequence[Any]) -> None","text":"

Adds colors to the QComboBox.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.currentColor","title":"currentColor() -> QColor | None","text":"

Returns the currently selected QColor or None if not yet selected.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.currentColorName","title":"currentColorName() -> str | None","text":"

Returns the name of the currently selected QColor or black if None.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.invalidColorPolicy","title":"invalidColorPolicy() -> InvalidColorPolicy","text":"

Returns the policy for handling invalid colors.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.itemColor","title":"itemColor(index: int) -> QColor | None","text":"

Returns the color of the item at the given index.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.setCurrentColor","title":"setCurrentColor(color: Any) -> None","text":"

Adds the color to the QComboBox and selects it.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.setInvalidColorPolicy","title":"setInvalidColorPolicy(policy: InvalidColorPolicy | int | Literal['Raise', 'Ignore', 'Warn']) -> None","text":"

Sets the policy for handling invalid colors.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.setUserColorsAllowed","title":"setUserColorsAllowed(allow: bool) -> None","text":"

Sets whether the user can add custom colors.

"},{"location":"widgets/qcolorcombobox/#superqt.QColorComboBox.userColorsAllowed","title":"userColorsAllowed() -> bool","text":"

Returns whether the user can add custom colors.

"},{"location":"widgets/qcolormap/","title":"QColormapComboBox","text":"

QComboBox variant to select from a specific set of colormaps.

requires cmap

This widget uses the cmap library to provide colormaps. You can install it with:

# use the `cmap` extra to include colormap support\npip install superqt[cmap]\n
"},{"location":"widgets/qcolormap/#colormaplike-objects","title":"ColorMapLike objects","text":"

Colormaps may be specified in a variety of ways, such as by name (string), an iterable of a color/color-like objects, or as a cmap.Colormap instance. See cmap documentation for details on all ColormapLike types

"},{"location":"widgets/qcolormap/#example","title":"Example","text":"
from cmap import Colormap\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QColormapComboBox\n\napp = QApplication([])\n\ncmap_combo = QColormapComboBox()\n# see note above about colormap-like objects\n# as names from the cmap catalog\ncmap_combo.addColormaps([\"viridis\", \"plasma\", \"magma\", \"gray\"])\n# as a sequence of colors, linearly interpolated\ncmap_combo.addColormap((\"#0f0\", \"slateblue\", \"#F3A003A0\"))\n# as a `cmap.Colormap` instance with custom name:\ncmap_combo.addColormap(Colormap((\"green\", \"white\", \"orange\"), name=\"MyMap\"))\n\ncmap_combo.show()\napp.exec()\n
"},{"location":"widgets/qcolormap/#style-customization","title":"Style Customization","text":"

Note that both the LineEdit and the dropdown can be styled to have the colormap on the left, or fill the entire width of the widget.

To make the CombBox label colormap fill the entire width of the widget:

from superqt.cmap import QColormapLineEdit\ncmap_combo.setLineEdit(QColormapLineEdit())\n

To make the CombBox dropdown colormaps fill less than the entire width of the widget:

from superqt.cmap import QColormapItemDelegate\ndelegate = QColormapItemDelegate(fractional_colormap_width=0.33)\ncmap_combo.setItemDelegate(delegate)\n
"},{"location":"widgets/qcolormap/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qcolormap/#signals","title":"Signals","text":""},{"location":"widgets/qcolormap/#currentcolormapchanged","title":"currentColormapChanged","text":""},{"location":"widgets/qcolormap/#methods","title":"Methods","text":"

A drop down menu for selecting colors.

Parameters:

Name Type Description Default parent QWidget

The parent widget.

None allow_user_colormaps bool

Whether the user can add custom colormaps by clicking the \"Add Colormap...\" item. Default is False. Can also be set with setUserAdditionsAllowed.

False add_colormap_text str

The text to display for the \"Add Colormap...\" item. Default is \"Add Colormap...\".

'Add Colormap...'"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.addColormap","title":"addColormap(cmap: ColorStopsLike) -> None","text":"

Adds the colormap to the QComboBox.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.addColormaps","title":"addColormaps(colors: Sequence[Any]) -> None","text":"

Adds colors to the QComboBox.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.currentColormap","title":"currentColormap() -> Colormap | None","text":"

Returns the currently selected Colormap or None if not yet selected.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.itemColormap","title":"itemColormap(index: int) -> Colormap | None","text":"

Returns the color of the item at the given index.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.setCurrentColormap","title":"setCurrentColormap(color: Any) -> None","text":"

Adds the color to the QComboBox and selects it.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.setUserAdditionsAllowed","title":"setUserAdditionsAllowed(allow: bool) -> None","text":"

Sets whether the user can add custom colors.

If enabled, an \"Add Colormap...\" item will be added to the end of the list. When clicked, a dialog will be shown to allow the user to select a colormap from the cmap catalog.

"},{"location":"widgets/qcolormap/#superqt.QColormapComboBox.userAdditionsAllowed","title":"userAdditionsAllowed() -> bool","text":"

Returns whether the user can add custom colors.

"},{"location":"widgets/qdoublerangeslider/","title":"QDoubleRangeSlider","text":"

Float variant of QRangeSlider. (see that page for more details).

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QDoubleRangeSlider\n\napp = QApplication([])\n\nslider = QDoubleRangeSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 1)\nslider.setValue((0.2, 0.8))\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qdoublerangeslider/#qt-class","title":"Qt Class","text":"

QSlider

"},{"location":"widgets/qdoublerangeslider/#methods","title":"Methods","text":""},{"location":"widgets/qdoubleslider/","title":"QDoubleSlider","text":"

QSlider variant that accepts floating point values.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QDoubleSlider\n\napp = QApplication([])\n\nslider = QDoubleSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 1)\nslider.setValue(0.5)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qdoubleslider/#qt-class","title":"Qt Class","text":"

QSlider

"},{"location":"widgets/qdoubleslider/#methods","title":"Methods","text":""},{"location":"widgets/qelidinglabel/","title":"QElidingLabel","text":"

QLabel variant that will elide text (i.e. add an ellipsis) if it is too long to fit in the available space.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QElidingLabel\n\napp = QApplication([])\n\nwidget = QElidingLabel(\n    \"a skj skjfskfj sdlf sdfl sdlfk jsdf sdlkf jdsf dslfksdl sdlfk sdf sdl \"\n    \"fjsdlf kjsdlfk laskdfsal as lsdfjdsl kfjdslf asfd dslkjfldskf sdlkfj\"\n)\nwidget.setWordWrap(True)\nwidget.resize(300, 20)\nwidget.show()\n\napp.exec_()\n

"},{"location":"widgets/qelidinglabel/#qt-class","title":"Qt Class","text":"

QLabel

"},{"location":"widgets/qelidinglabel/#methods","title":"Methods","text":"

A QLabel variant that will elide text (could add '\u2026') to fit width.

QElidingLabel() QElidingLabel(parent: Optional[QWidget], f: Qt.WindowFlags = ...) QElidingLabel(text: str, parent: Optional[QWidget] = None, f: Qt.WindowFlags = ...)

For a multiline eliding label, use setWordWrap(True). In this case, text will wrap to fit the width, and only the last line will be elided. When wordWrap() is True, sizeHint() will return the size required to fit the full text.

"},{"location":"widgets/qelidinglabel/#superqt.QElidingLabel.setElideMode","title":"setElideMode(mode: Qt.TextElideMode) -> None","text":"

Set the elide mode to a Qt.TextElideMode.

"},{"location":"widgets/qelidinglabel/#superqt.QElidingLabel.setEllipsesWidth","title":"setEllipsesWidth(width: int) -> None","text":"

A width value to take into account ellipses width when eliding text.

The value is deducted from the widget width when computing the elided version of the text.

"},{"location":"widgets/qenumcombobox/","title":"QEnumComboBox","text":"

QEnumComboBox is a variant of QComboBox that populates the items in the combobox based on a python Enum class. In addition to all the methods provided by QComboBox, this subclass adds the methods enumClass/setEnumClass to get/set the current Enum class represented by the combobox, and currentEnum/setCurrentEnum to get/set the current Enum member in the combobox. There is also a new signal currentEnumChanged(enum) analogous to currentIndexChanged and currentTextChanged.

Method like insertItem and addItem are blocked and try of its usage will end with RuntimeError

from enum import Enum\n\nfrom qtpy.QtWidgets import QApplication\nfrom superqt import QEnumComboBox\n\n\nclass SampleEnum(Enum):\n    first = 1\n    second = 2\n    third = 3\n\napp = QApplication([])\n\ncombo = QEnumComboBox()\ncombo.setEnumClass(SampleEnum)\ncombo.show()\n\napp.exec_()\n

Another option is to use optional enum_class argument of constructor and change

# option A:\ncombo = QEnumComboBox()\ncombo.setEnumClass(SampleEnum)\n# option B:\ncombo = QEnumComboBox(enum_class=SampleEnum)\n
"},{"location":"widgets/qenumcombobox/#allow-none","title":"Allow None","text":"

QEnumComboBox also allows using Optional type annotation:

from enum import Enum\n\nfrom superqt import QEnumComboBox\n\nclass SampleEnum(Enum):\n    first = 1\n    second = 2\n    third = 3\n\n# as usual:\n# you must create a QApplication before create a widget.\n\ncombo = QEnumComboBox()\ncombo.setEnumClass(SampleEnum, allow_none=True)\n

In this case there is added option ---- and the currentEnum() method will return None when it is selected.

"},{"location":"widgets/qenumcombobox/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qenumcombobox/#signals","title":"Signals","text":""},{"location":"widgets/qenumcombobox/#currentenumchanged","title":"currentEnumChanged","text":""},{"location":"widgets/qenumcombobox/#methods","title":"Methods","text":"

ComboBox presenting options from a python Enum.

If the Enum class does not implement __str__ then a human readable name is created from the name of the enum member, replacing underscores with spaces.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.currentEnum","title":"currentEnum() -> Optional[EnumType]","text":"

Current value as Enum member.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.enumClass","title":"enumClass() -> Optional[EnumMeta]","text":"

Return current Enum class.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.isOptional","title":"isOptional() -> bool","text":"

Return if current enum is with optional annotation.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.setCurrentEnum","title":"setCurrentEnum(value: Optional[EnumType]) -> None","text":"

Set value with Enum.

"},{"location":"widgets/qenumcombobox/#superqt.QEnumComboBox.setEnumClass","title":"setEnumClass(enum: Optional[EnumMeta], allow_none: Optional[EnumMeta] = False)","text":"

Set enum class from which members value should be selected.

"},{"location":"widgets/qlabeleddoublerangeslider/","title":"QLabeledDoubleRangeSlider","text":"

Labeled Float variant of QRangeSlider. (see that page for more details).

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledDoubleRangeSlider\n\napp = QApplication([])\n\nslider = QLabeledDoubleRangeSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 1)\nslider.setValue((0.2, 0.8))\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeleddoublerangeslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeleddoublerangeslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeleddoublerangeslider/#qlabeleddoublerangeslideredgelabelmode","title":"QLabeledDoubleRangeSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeleddoublerangeslider/#qlabeleddoublerangesliderlabelposition","title":"QLabeledDoubleRangeSlider.LabelPosition","text":""},{"location":"widgets/qlabeleddoublerangeslider/#methods","title":"Methods","text":""},{"location":"widgets/qlabeleddoublerangeslider/#superqt.QLabeledDoubleRangeSlider.decimals","title":"decimals() -> int","text":""},{"location":"widgets/qlabeleddoublerangeslider/#superqt.QLabeledDoubleRangeSlider.setDecimals","title":"setDecimals(prec: int) -> None","text":""},{"location":"widgets/qlabeleddoubleslider/","title":"QLabeledDoubleSlider","text":"

QDoubleSlider variant that shows an editable (SpinBox) label next to the slider.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledDoubleSlider\n\napp = QApplication([])\n\nslider = QLabeledDoubleSlider(Qt.Orientation.Horizontal)\nslider.setRange(0, 2.5)\nslider.setValue(1.3)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeleddoubleslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeleddoubleslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeleddoubleslider/#qlabeleddoubleslideredgelabelmode","title":"QLabeledDoubleSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeleddoubleslider/#methods","title":"Methods","text":""},{"location":"widgets/qlabeleddoubleslider/#superqt.QLabeledDoubleSlider.decimals","title":"decimals() -> int","text":""},{"location":"widgets/qlabeleddoubleslider/#superqt.QLabeledDoubleSlider.setDecimals","title":"setDecimals(prec: int) -> None","text":""},{"location":"widgets/qlabeledrangeslider/","title":"QLabeledRangeSlider","text":"

Labeled variant of QRangeSlider. (see that page for more details).

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledRangeSlider\n\napp = QApplication([])\n\nslider = QLabeledRangeSlider(Qt.Orientation.Horizontal)\nslider.setValue((20, 80))\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeledrangeslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeledrangeslider/#signals","title":"Signals","text":""},{"location":"widgets/qlabeledrangeslider/#editingfinished","title":"editingFinished","text":""},{"location":"widgets/qlabeledrangeslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeledrangeslider/#qlabeledrangeslideredgelabelmode","title":"QLabeledRangeSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeledrangeslider/#qlabeledrangesliderlabelposition","title":"QLabeledRangeSlider.LabelPosition","text":""},{"location":"widgets/qlabeledrangeslider/#methods","title":"Methods","text":"

If you find that you need to fine tune the position of the handle labels:

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.edgeLabelMode","title":"edgeLabelMode() -> EdgeLabelMode","text":"

Return current EdgeLabelMode.

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.handleLabelPosition","title":"handleLabelPosition() -> LabelPosition","text":"

Return where/whether labels are shown adjacent to slider handles.

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.setEdgeLabelMode","title":"setEdgeLabelMode(opt: EdgeLabelMode) -> None","text":"

Set EdgeLabelMode, controls what is shown at the min/max labels.

"},{"location":"widgets/qlabeledrangeslider/#superqt.QLabeledRangeSlider.setHandleLabelPosition","title":"setHandleLabelPosition(opt: LabelPosition) -> None","text":"

Set where/whether labels are shown adjacent to slider handles.

"},{"location":"widgets/qlabeledslider/","title":"QLabeledSlider","text":"

QSlider variant that shows an editable (SpinBox) label next to the slider.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLabeledSlider\n\napp = QApplication([])\n\nslider = QLabeledSlider(Qt.Orientation.Horizontal)\nslider.setValue(42)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlabeledslider/#qt-class","title":"Qt Class","text":"

QAbstractSlider

"},{"location":"widgets/qlabeledslider/#signals","title":"Signals","text":""},{"location":"widgets/qlabeledslider/#editingfinished","title":"editingFinished","text":""},{"location":"widgets/qlabeledslider/#enums","title":"Enums","text":""},{"location":"widgets/qlabeledslider/#qlabeledslideredgelabelmode","title":"QLabeledSlider.EdgeLabelMode","text":""},{"location":"widgets/qlabeledslider/#methods","title":"Methods","text":""},{"location":"widgets/qlabeledslider/#superqt.QLabeledSlider.edgeLabelMode","title":"edgeLabelMode() -> EdgeLabelMode","text":"

Return current EdgeLabelMode.

"},{"location":"widgets/qlabeledslider/#superqt.QLabeledSlider.setEdgeLabelMode","title":"setEdgeLabelMode(opt: EdgeLabelMode) -> None","text":"

Set the EdgeLabelMode.

Parameters:

Name Type Description Default opt EdgeLabelMode

To show no label, use EdgeLabelMode.NoLabel. To show the value of the slider, use EdgeLabelMode.LabelIsValue. To show value / maximum, use EdgeLabelMode.LabelIsValue | EdgeLabelMode.LabelIsRange.

required"},{"location":"widgets/qlargeintspinbox/","title":"QLargeIntSpinBox","text":"

QSpinBox variant that allows to enter large integers, without overflow.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QLargeIntSpinBox\n\napp = QApplication([])\n\nslider = QLargeIntSpinBox()\nslider.setRange(0, 4.53e8)\nslider.setValue(4.53e8)\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qlargeintspinbox/#qt-class","title":"Qt Class","text":"

QAbstractSpinBox

"},{"location":"widgets/qlargeintspinbox/#signals","title":"Signals","text":""},{"location":"widgets/qlargeintspinbox/#textchanged","title":"textChanged","text":""},{"location":"widgets/qlargeintspinbox/#valuechanged","title":"valueChanged","text":""},{"location":"widgets/qlargeintspinbox/#methods","title":"Methods","text":"

An integer spinboxes backed by unbound python integer.

Qt's built-in QSpinBox is backed by a signed 32-bit integer. This could become limiting, particularly in large dense segmentations. This class behaves like a QSpinBox backed by an unbound python int.

Does not yet support \"prefix\", \"suffix\" or \"specialValue\" like QSpinBox.

"},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.maximum","title":"maximum()","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.minimum","title":"minimum()","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setMaximum","title":"setMaximum(max)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setMinimum","title":"setMinimum(min)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setRange","title":"setRange(minimum, maximum)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setSingleStep","title":"setSingleStep(step)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setStepType","title":"setStepType(stepType: QAbstractSpinBox.StepType) -> None","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.setValue","title":"setValue(value)","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.singleStep","title":"singleStep()","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.stepType","title":"stepType() -> QAbstractSpinBox.StepType","text":""},{"location":"widgets/qlargeintspinbox/#superqt.QLargeIntSpinBox.value","title":"value()","text":""},{"location":"widgets/qquantity/","title":"QQuantity","text":"

A widget that allows the user to edit a quantity (a magnitude associated with a unit).

Note

This widget requires pint:

pip install pint\n

or

pip install superqt[quantity]\n
from qtpy.QtWidgets import QApplication\n\nfrom superqt import QQuantity\n\napp = QApplication([])\nw = QQuantity(\"1m\")\nw.show()\n\napp.exec()\n

"},{"location":"widgets/qquantity/#qt-class","title":"Qt Class","text":"

QWidget

"},{"location":"widgets/qquantity/#signals","title":"Signals","text":""},{"location":"widgets/qquantity/#dimensionalitychanged","title":"dimensionalityChanged","text":""},{"location":"widgets/qquantity/#valuechanged","title":"valueChanged","text":""},{"location":"widgets/qquantity/#unitschanged","title":"unitsChanged","text":""},{"location":"widgets/qquantity/#methods","title":"Methods","text":"

A combination QDoubleSpinBox and QComboBox for entering quantities.

For this widget, value() returns a pint.Quantity object, while setValue() accepts either a number, pint.Quantity, a string that can be parsed by pint.

Parameters:

Name Type Description Default value Union[str, Quantity, Number]

The initial value to display. If a string, it will be parsed by pint.

0 units Union[UnitsContainer, str, Quantity]

The units to use if value is a number. If a string, it will be parsed by pint. If a pint.Quantity, the units will be extracted from it.

None ureg UnitRegistry

The unit registry to use. If not provided, the registry will be extracted from value if it is a pint.Quantity, otherwise the default registry will be used.

None parent QWidget

The parent widget, by default None

None"},{"location":"widgets/qquantity/#superqt.QQuantity.dimensionality","title":"dimensionality() -> UnitsContainer","text":"

Return the current dimensionality (cast to str for nice repr).

"},{"location":"widgets/qquantity/#superqt.QQuantity.isDimensionless","title":"isDimensionless() -> bool","text":"

Return True if the current value is dimensionless.

"},{"location":"widgets/qquantity/#superqt.QQuantity.magnitude","title":"magnitude() -> Union[float, int]","text":"

Return the magnitude of the current value.

"},{"location":"widgets/qquantity/#superqt.QQuantity.magnitudeSpinBox","title":"magnitudeSpinBox() -> QDoubleSpinBox","text":"

Return the QSpinBox widget used to edit the magnitude.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setDecimals","title":"setDecimals(decimals: int) -> None","text":"

Set the number of decimals to display in the spinbox.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setMagnitude","title":"setMagnitude(magnitude: Number) -> None","text":"

Set the magnitude of the current value.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setUnits","title":"setUnits(units: Union[str, Unit, Quantity]) -> None","text":"

Set the units of the current value.

If units is None, will convert to a dimensionless quantity. Otherwise, units must be compatible with the current dimensionality.

"},{"location":"widgets/qquantity/#superqt.QQuantity.setValue","title":"setValue(value: Union[str, Quantity, Number], units: Optional[Union[UnitsContainer, str, Quantity]] = None) -> None","text":"

Set the current value (will cast to a pint Quantity).

"},{"location":"widgets/qquantity/#superqt.QQuantity.text","title":"text() -> str","text":""},{"location":"widgets/qquantity/#superqt.QQuantity.unitRegistry","title":"unitRegistry() -> UnitRegistry","text":"

Return the pint UnitRegistry used by this widget.

"},{"location":"widgets/qquantity/#superqt.QQuantity.units","title":"units() -> Unit","text":"

Return the current units.

"},{"location":"widgets/qquantity/#superqt.QQuantity.unitsComboBox","title":"unitsComboBox() -> QComboBox","text":"

Return the QCombBox widget used to edit the units.

"},{"location":"widgets/qquantity/#superqt.QQuantity.value","title":"value() -> Quantity","text":"

Return the current value as a pint.Quantity.

"},{"location":"widgets/qrangeslider/","title":"QRangeSlider","text":"

A multi-handle slider widget than can be used to select a range of values.

from qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import QApplication\n\nfrom superqt import QRangeSlider\n\napp = QApplication([])\n\nslider = QRangeSlider(Qt.Orientation.Horizontal)\nslider.setValue((20, 80))\nslider.show()\n\napp.exec_()\n

As QRangeSlider inherits from QtWidgets.QSlider, you can use all of the same methods available in the QSlider API. The major difference is that value() and sliderPosition() are reimplemented as tuples of int (where the length of the tuple is equal to the number of handles in the slider.)

These options are in addition to the Qt QSlider API, and control the behavior of the bar between handles.

getter setter type default description barIsVisible setBarIsVisible hideBar / showBar bool True Whether the bar between handles is visible. barMovesAllHandles setBarMovesAllHandles bool True Whether clicking on the bar moves all handles or just the nearest barIsRigid setBarIsRigid bool True Whether bar length is constant or \"elastic\" when dragging the bar beyond min/max."},{"location":"widgets/qrangeslider/#screenshots","title":"Screenshots","text":"code that generates the images below
import os\n\nfrom qtpy import QtCore\nfrom qtpy import QtWidgets as QtW\n\n# patch for Qt 5.15 on macos >= 12\nos.environ[\"USE_MAC_SLIDER_PATCH\"] = \"1\"\n\nfrom superqt import QRangeSlider  # noqa\n\nQSS = \"\"\"\nQSlider {\n    min-height: 20px;\n}\n\nQSlider::groove:horizontal {\n    border: 0px;\n    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #888, stop:1 #ddd);\n    height: 20px;\n    border-radius: 10px;\n}\n\nQSlider::handle {\n    background: qradialgradient(cx:0, cy:0, radius: 1.2, fx:0.35,\n                                fy:0.3, stop:0 #eef, stop:1 #002);\n    height: 20px;\n    width: 20px;\n    border-radius: 10px;\n}\n\nQSlider::sub-page:horizontal {\n    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #227, stop:1 #77a);\n    border-top-left-radius: 10px;\n    border-bottom-left-radius: 10px;\n}\n\nQRangeSlider {\n    qproperty-barColor: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #227, stop:1 #77a);\n}\n\"\"\"\n\nHorizontal = QtCore.Qt.Orientation.Horizontal\n\n\nclass DemoWidget(QtW.QWidget):\n    def __init__(self) -> None:\n        super().__init__()\n\n        reg_hslider = QtW.QSlider(Horizontal)\n        reg_hslider.setValue(50)\n        range_hslider = QRangeSlider(Horizontal)\n        range_hslider.setValue((20, 80))\n        multi_range_hslider = QRangeSlider(Horizontal)\n        multi_range_hslider.setValue((11, 33, 66, 88))\n        multi_range_hslider.setTickPosition(QtW.QSlider.TickPosition.TicksAbove)\n\n        styled_reg_hslider = QtW.QSlider(Horizontal)\n        styled_reg_hslider.setValue(50)\n        styled_reg_hslider.setStyleSheet(QSS)\n        styled_range_hslider = QRangeSlider(Horizontal)\n        styled_range_hslider.setValue((20, 80))\n        styled_range_hslider.setStyleSheet(QSS)\n\n        reg_vslider = QtW.QSlider(QtCore.Qt.Orientation.Vertical)\n        reg_vslider.setValue(50)\n        range_vslider = QRangeSlider(QtCore.Qt.Orientation.Vertical)\n        range_vslider.setValue((22, 77))\n\n        tick_vslider = QtW.QSlider(QtCore.Qt.Orientation.Vertical)\n        tick_vslider.setValue(55)\n        tick_vslider.setTickPosition(QtW.QSlider.TicksRight)\n        range_tick_vslider = QRangeSlider(QtCore.Qt.Orientation.Vertical)\n        range_tick_vslider.setValue((22, 77))\n        range_tick_vslider.setTickPosition(QtW.QSlider.TicksLeft)\n\n        szp = QtW.QSizePolicy.Maximum\n        left = QtW.QWidget()\n        left.setLayout(QtW.QVBoxLayout())\n        left.setContentsMargins(2, 2, 2, 2)\n        label1 = QtW.QLabel(\"Regular QSlider Unstyled\")\n        label2 = QtW.QLabel(\"QRangeSliders Unstyled\")\n        label3 = QtW.QLabel(\"Styled Sliders (using same stylesheet)\")\n        label1.setSizePolicy(szp, szp)\n        label2.setSizePolicy(szp, szp)\n        label3.setSizePolicy(szp, szp)\n        left.layout().addWidget(label1)\n        left.layout().addWidget(reg_hslider)\n        left.layout().addWidget(label2)\n        left.layout().addWidget(range_hslider)\n        left.layout().addWidget(multi_range_hslider)\n        left.layout().addWidget(label3)\n        left.layout().addWidget(styled_reg_hslider)\n        left.layout().addWidget(styled_range_hslider)\n\n        right = QtW.QWidget()\n        right.setLayout(QtW.QHBoxLayout())\n        right.setContentsMargins(15, 5, 5, 0)\n        right.layout().setSpacing(30)\n        right.layout().addWidget(reg_vslider)\n        right.layout().addWidget(range_vslider)\n        right.layout().addWidget(tick_vslider)\n        right.layout().addWidget(range_tick_vslider)\n\n        self.setLayout(QtW.QHBoxLayout())\n        self.layout().addWidget(left)\n        self.layout().addWidget(right)\n        self.setGeometry(600, 300, 580, 300)\n        self.activateWindow()\n        self.show()\n\n\nif __name__ == \"__main__\":\n\n    import sys\n    from pathlib import Path\n\n    dest = Path(\"screenshots\")\n    dest.mkdir(exist_ok=True)\n\n    app = QtW.QApplication([])\n    demo = DemoWidget()\n\n    if \"-snap\" in sys.argv:\n        import platform\n\n        QtW.QApplication.processEvents()\n        demo.grab().save(str(dest / f\"demo_{platform.system().lower()}.png\"))\n    else:\n        app.exec_()\n
"},{"location":"widgets/qrangeslider/#macos","title":"macOS","text":""},{"location":"widgets/qrangeslider/#catalina","title":"Catalina","text":""},{"location":"widgets/qrangeslider/#big-sur","title":"Big Sur","text":""},{"location":"widgets/qrangeslider/#windows","title":"Windows","text":""},{"location":"widgets/qrangeslider/#linux","title":"Linux","text":""},{"location":"widgets/qrangeslider/#qt-class","title":"Qt Class","text":"

QSlider

"},{"location":"widgets/qrangeslider/#methods","title":"Methods","text":"

MultiHandle Range Slider widget.

Same API as QSlider, but value, setValue, sliderPosition, and setSliderPosition are all sequences of integers.

The valueChanged and sliderMoved signals also both emit a tuple of integers.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barColor","title":"barColor = Property(QtGui.QBrush, _getBarColor, _setBarColor) class-attribute instance-attribute","text":"

The color of the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.applyMacStylePatch","title":"applyMacStylePatch() -> str","text":"

Apply a QSS patch to fix sliders on macos>=12 with QT < 6.

see FAQ for more details.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barIsRigid","title":"barIsRigid() -> bool","text":"

Whether bar length is constant when dragging the bar.

If False, the bar can shorten when dragged beyond min/max. Default is True.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barIsVisible","title":"barIsVisible() -> bool","text":"

Whether to show the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.barMovesAllHandles","title":"barMovesAllHandles() -> bool","text":"

Whether clicking on the bar moves all handles, or just the nearest.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.hideBar","title":"hideBar() -> None","text":"

Hide the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.setBarIsRigid","title":"setBarIsRigid(val: bool = True) -> None","text":"

Whether bar length is constant when dragging the bar.

If False, the bar can shorten when dragged beyond min/max. Default is True.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.setBarMovesAllHandles","title":"setBarMovesAllHandles(val: bool = True) -> None","text":"

Whether clicking on the bar moves all handles, or just the nearest.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.setBarVisible","title":"setBarVisible(val: bool = True) -> None","text":"

Whether to show the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#superqt.sliders._sliders._GenericRangeSlider.showBar","title":"showBar() -> None","text":"

Show the bar between the first and last handle.

"},{"location":"widgets/qrangeslider/#type-changes","title":"Type changes","text":"

Note the following changes in types compared to the QSlider API:

value() -> Tuple[int, ...]\n
setValue(val: Sequence[int]) -> None\n
# Signal\nvalueChanged(Tuple[int, ...])\n
sliderPosition() -> Tuple[int, ...]\n
setSliderPosition(val: Sequence[int]) -> None\n
sliderMoved(Tuple[int, ...])\n
"},{"location":"widgets/qsearchablecombobox/","title":"QSearchableComboBox","text":"

QSearchableComboBox is a variant of QComboBox that allow to filter list of options by enter part of text. It could be drop in replacement for QComboBox.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QSearchableComboBox\n\napp = QApplication([])\n\ncombo = QSearchableComboBox()\ncombo.addItems([\"foo\", \"bar\", \"baz\", \"foobar\", \"foobaz\", \"barbaz\"])\ncombo.show()\n\napp.exec_()\n

"},{"location":"widgets/qsearchablecombobox/#qt-class","title":"Qt Class","text":"

QComboBox

"},{"location":"widgets/qsearchablelistwidget/","title":"QSearchableListWidget","text":"

QSearchableListWidget is a variant of QListWidget that add text entry above list widget that allow to filter list of available options.

Due to implementation details, this widget it does not inherit directly from QListWidget but it does fully satisfy its api. The only limitation is that it cannot be used as argument of QListWidgetItem constructor.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QSearchableListWidget\n\napp = QApplication([])\n\nslider = QSearchableListWidget()\nslider.addItems([\"foo\", \"bar\", \"baz\", \"foobar\", \"foobaz\", \"barbaz\"])\nslider.show()\n\napp.exec_()\n

"},{"location":"widgets/qsearchablelistwidget/#qt-class","title":"Qt Class","text":"

QWidget

"},{"location":"widgets/qsearchablelistwidget/#methods","title":"Methods","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.addItem","title":"addItem(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.addItems","title":"addItems(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.insertItem","title":"insertItem(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.insertItems","title":"insertItems(*args)","text":""},{"location":"widgets/qsearchablelistwidget/#superqt.QSearchableListWidget.update_visible","title":"update_visible(text)","text":""},{"location":"widgets/qsearchabletreewidget/","title":"QSearchableTreeWidget","text":"

QSearchableTreeWidget combines a QTreeWidget and a QLineEdit for showing a mapping that can be searched by key.

This is intended to be used with a read-only mapping and be conveniently created using QSearchableTreeWidget.fromData(data). If the mapping changes, the easiest way to update this is by calling setData.

from qtpy.QtWidgets import QApplication\n\nfrom superqt import QSearchableTreeWidget\n\napp = QApplication([])\n\ndata = {\n    \"none\": None,\n    \"str\": \"test\",\n    \"int\": 42,\n    \"list\": [2, 3, 5],\n    \"dict\": {\n        \"float\": 0.5,\n        \"tuple\": (22, 99),\n        \"bool\": False,\n    },\n}\ntree = QSearchableTreeWidget.fromData(data)\ntree.show()\n\napp.exec_()\n

"},{"location":"widgets/qsearchabletreewidget/#qt-class","title":"Qt Class","text":"

QWidget

"},{"location":"widgets/qsearchabletreewidget/#methods","title":"Methods","text":"

A tree widget for showing a mapping that can be searched by key.

This is intended to be used with a read-only mapping and be conveniently created using QSearchableTreeWidget.fromData(data). If the mapping changes, the easiest way to update this is by calling setData.

The tree can be searched by entering a regular expression pattern into the filter line edit. An item is only shown if its, any of its ancestors', or any of its descendants' keys or values match this pattern. The regular expression follows the conventions described by the Qt docs: https://doc.qt.io/qt-5/qregularexpression.html#details

Attributes:

Name Type Description tree QTreeWidget

Shows the mapping as a tree of items.

filter QLineEdit

Used to filter items in the tree by matching their key against a regular expression.

"},{"location":"widgets/qsearchabletreewidget/#superqt.QSearchableTreeWidget.fromData","title":"fromData(data: Mapping, *, parent: QWidget = None) -> QSearchableTreeWidget classmethod","text":"

Make a searchable tree widget from a mapping.

"},{"location":"widgets/qsearchabletreewidget/#superqt.QSearchableTreeWidget.setData","title":"setData(data: Mapping) -> None","text":"

Update the mapping data shown by the tree.

"}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 3460635..faa5cf2 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ diff --git a/widgets/qlabeleddoublerangeslider/index.html b/widgets/qlabeleddoublerangeslider/index.html index b964e6f..9eef3cd 100644 --- a/widgets/qlabeleddoublerangeslider/index.html +++ b/widgets/qlabeleddoublerangeslider/index.html @@ -826,15 +826,15 @@