+
+
+
+
diff --git a/objects.inv b/objects.inv
index f1f9d0b..5838a31 100644
Binary files a/objects.inv and b/objects.inv differ
diff --git a/search/search_index.json b/search/search_index.json
index 3d2f9e1..f8ba798 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.
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:
https://bugreports.qt.io/browse/QTBUG-98093
https://github.com/pyapp-kit/superqt/issues/74
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:
set the environment variable USE_MAC_SLIDER_PATCH=1 before importing superqt (note: this is safe to use even if you're targeting more than just MacOS 12, it will only be applied when needed)
call the applyMacStylePatch() method on any of the superqt slider subclasses (note, this will override your slider styles)
apply the stylesheet manually:
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/#svg-icons","title":"SVG Icons","text":"Object Description QIconifyIcon QIcons backed by the Iconify icon library."},{"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. FunctionWorkerQRunnable with signals that wraps a simple long-running function. GeneratorWorkerQRunnable 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":"
Name Type Description Default painter_or_deviceQPainter | QPaintDevice
A QPainter instance or a QPaintDevice (e.g. a QWidget or QPixmap) onto which to paint the colormap.
required cmapColormap | 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 rectQRect | QRectF | None
A rect onto which to draw. If None, the painter.viewport() will be used. by default None
Noneborder_colorQColor | str | None
If not None, a border of color border_color and width border_width is included around the edge, by default None.
Noneborder_widthint
The width of the border to draw (provided border_color is not None), by default 2
1lighterint
Percentage by which to lighten (or darken) the colors. Greater than 100 lightens, less than 100 darkens, by default 100 (i.e. no change).
100checkerboard_sizebool
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\n\nclass W(QWidget):\n def paintEvent(self, event) -> None:\n draw_colormap(self, viridis, event.rect())\n\n\n# or draw onto a QPixmap\npm = QPixmap(200, 200)\ndraw_colormap(pm, viridis)\n
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 parentQWidget
The parent widget.
Nonefractional_colormap_widthfloat
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.33fallback_cmapColormap | str | None
The colormap to use when the current text is not a recognized colormap. by default \"gray\".
'gray'missing_iconQIcon | 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.
MISSINGcheckerboard_sizeint
Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.
Delegate that draws colormaps into a QAbstractItemView item.
Parameters:
Name Type Description Default parentQObject
The parent object.
Noneitem_sizeQSize
The size hint for each item, by default QSize(80, 22).
DEFAULT_SIZEfractional_colormap_widthfloat
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.
1paddingint
The padding (in pixels) around the edge of the item, by default 1.
1checkerboard_sizeint
Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.
Name Type Description Default parentQTextDocument | QObject | None
The parent object. Usually a QTextDocument. To use this class with a QTextArea, pass in text_area.document().
required langstr
The language of the code to highlight. This should be a string that Pygments recognizes, e.g. 'python', 'pytb', 'cpp', 'java', etc.
required themeKnownStyle | str
The name of the Pygments style to use. For a complete list of available styles, use pygments.styles.get_all_styles().
'default'
Examples:
from qtpy.QtWidgets import QTextEdit\nfrom superqt.utils import CodeSyntaxHighlight\n\ntext_area = QTextEdit()\nhighlighter = CodeSyntaxHighlight(text_area.document(), \"python\", \"monokai\")\n\n# then manually apply the background color to the text area.\npalette = text_area.palette()\nbgrd_color = QColor(self._highlight.background_color)\npalette.setColor(QPalette.ColorRole.Base, bgrd_color)\ntext_area.setPalette(palette)\n
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 exceptionstype[BaseException] | tuple[type[BaseException], ...]
The exception(s) to catch, by default Exception (i.e. all exceptions).
ExceptioniconIcon
The icon to show in the QMessageBox, by default QMessageBox.Icon.Critical
Criticaltitlestr
The title of the QMessageBox, by default \"An error occurred\".
'An error occurred'msg_templatestr
The message to show in the QMessageBox. The message will be formatted using three variables:
exc_value: the exception instance
exc_type: the exception type
tb: the traceback as a string
The default template is the content of the exception: \"{exc_value}\"
'{exc_value}'buttonsStandardButton
The buttons to show in the QMessageBox, by default QMessageBox.StandardButton.Ok
OkparentQWidget | None
The parent widget of the QMessageBox, by default None
Noneuse_error_messagebool | 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 dialogQMessageBox | 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\")).
exceptionBaseException | None
Will hold the exception instance if an exception was raised and caught.
Examples:
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
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:
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:
fonticon-fontawesome5 ('fa5s' & 'fa5r' prefixes)
fonticon-materialdesignicons6 ('mdi6' prefix)
...but fonts can also be added manually using addFont.
Parameters:
Name Type Description Default glyph_keystr
String encapsulating a font-family, style, and glyph. e.g. 'fa5s.smile'.
required scale_factorfloat
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_FACTORcolorValidColor
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).
Noneopacityfloat
Opacity of icon, by default 1
1animationAnimation
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.
NonetransformQTransform
A QTransform to apply when painting the icon, by default None
Nonestatesdict
Provide additional styling for the icon in different states. states must be a mapping of string to dict, where:
the key represents a QIcon.State (\"on\", \"off\"), a QIcon.Mode (\"normal\", \"active\", \"selected\", \"disabled\"), or any combination of a state & mode separated by an underscore (e.g. \"off_active\", \"selected_on\", etc...).
the value is a dict with all of the same key/value meanings listed above as parameters to this function (e.g. glyph_key, color,scale_factor, animation, etc...)
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)
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:
fonticon-fontawesome5
fonticon-materialdesignicons6
Parameters:
Name Type Description Default filepathstr
Path to an OTF or TTF file containing the fonts
required prefixstr
A prefix that will represent this font file when used for lookup. For example, 'fa5s' for 'Font-Awesome 5 Solid'.
required charmapDict[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.
Iconify is an icon library that includes 150,000+ icons from most major icon sets including Bootstrap, FontAwesome, Material Design, and many more; each available as individual SVGs. Unlike the superqt.fonticon module, superqt.QIconifyIcon does not require any additional dependencies or font files to be installed. Icons are downloaded (and cached) on-demand from the Iconify API, using pyconify
Search availble icons at https://icon-sets.iconify.design Once you find one you like, use the key in the format \"prefix:name\" to create an icon: QIconifyIcon(\"bi:bell\").
Iconify includes 150,000+ icons from most major icon sets including Bootstrap, FontAwesome, Material Design, and many more.
Search availble icons at https://icon-sets.iconify.design Once you find one you like, use the key in the format \"prefix:name\" to create an icon: QIconifyIcon(\"bi:bell\").
This class is a thin wrapper around the pyconify svg_path function. It pulls SVGs from iconify, creates a temporary SVG file and uses it as the source for a QIcon. SVGs are cached to disk, and persist across sessions (until pyconify.clear_cache() is called).
Parameters are the same as QIconifyIcon.addKey, which can be used to add additional icons for various modes and states to the same QIcon.
Parameters:
Name Type Description Default *keystr
Icon set prefix and name. May be passed as a single string in the format \"prefix:name\" or as two separate strings: 'prefix', 'name'.
()colorstr
Icon color. If not provided, the icon will appear black (the icon fill color will be set to the string \"currentColor\").
Noneflipstr
Flip icon. Must be one of \"horizontal\", \"vertical\", \"horizontal,vertical\"
Nonerotatestr | int
Rotate icon. Must be one of 0, 90, 180, 270, or 0, 1, 2, 3 (equivalent to 0, 90, 180, 270, respectively)
Nonedirstr
If 'dir' is not None, the file will be created in that directory, otherwise a default directory is used.
None
Examples:
>>> from qtpy.QtWidgets import QPushButton\n>>> from superqt import QIconifyIcon\n>>> btn = QPushButton()\n>>> icon = QIconifyIcon(\"bi:alarm-fill\", color=\"red\", rotate=90)\n>>> btn.setIcon(icon)\n
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).
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.
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
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.
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.
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:
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 msecsint
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.
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().
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
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 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
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 funcCallable
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.
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 funccallable
The function being run in another thread. May be a generator function.
required SignalsClasstype
A QObject subclass that contains signals, by default GeneratorWorkerSignals
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)
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:
started: emitted when the work is started
finished: emitted when the work is finished
returned: emitted with return value
errored: emitted with error object on Exception
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:
yielded: emitted with yielded values
paused: emitted when a running job has successfully paused
resumed: emitted when a paused job has successfully resumed
aborted: emitted when a running job is successfully aborted
And these methods:
quit: ask the thread to quit
toggle_paused: toggle the running state of the thread.
send: send a value into the generator. (This requires that your decorator function uses the value = yield syntax)
Parameters:
Name Type Description Default functioncallable
Function to call in another thread. For communication between threads may be a generator function.
Nonestart_threadbool
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.
NoneconnectDict[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
Noneworker_classType[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.
Noneignore_errorsbool
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\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
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 funcCallable
The function to call in another thread.
required _start_threadbool
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_connectDict[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_classtype 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_errorsbool
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 workerWorkerBase
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}
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 WorkerQObject
QObject type that implements a work() method. The Worker should also emit a finished signal when the work is done.
required _start_threadbool
If True, thread will be started immediately, otherwise, thread must be manually started with thread.start().
False_connectdict
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 workerWorkerBase
The created worker.
threadQThread
The thread on which the worker is running.
Examples:
Create some QObject that has a long-running work method:
class Worker(QObject):\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\n for i in range(10):\n time.sleep(1)\n self.increment.emit(i)\n self.finished.emit()\n\n\nworker, thread = new_worker_qthread(\n Worker,\n \"argument\",\n _start_thread=True,\n _connect={\"increment\": print},\n)\n
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).
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 funcCallable
A function to throttle
Nonetimeoutint
Timeout in milliseconds to wait before allowing another call, by default 100
100leadingbool
Whether to invoke the function on the leading edge of the wait timer, by default False
Falsetimer_typeTimerType
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
PreciseTimerparentQObject | None
Parent object for timer. If using qthrottled as function it may be usefull for cleaning data
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 funcCallable
A function to throttle
Nonetimeoutint
Timeout in milliseconds to wait before allowing another call, by default 100
100leadingbool
Whether to invoke the function on the leading edge of the wait timer, by default True
Truetimer_typeTimerType
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
PreciseTimerparentQObject | None
Parent object for timer. If using qthrottled as function it may be usefull for cleaning data
"},{"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 QLabeledDoubleRangeSliderQDoubleRangeSlider variant with editable labels for each handle QLabeledDoubleSliderQSlider for float values with editable QSpinBox with the current value QLabeledRangeSliderQRangeSlider variant, with editable labels for each handle QLabeledSliderQSlider with editable QSpinBox that shows the current value QLargeIntSpinBoxQSpinbox 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. QEnumComboBoxQComboBox that populates the combobox from a python EnumQSearchableComboBoxQComboBox variant that filters available options based on text input QSearchableListWidgetQListWidget variant with search field that filters available options QSearchableTreeWidgetQTreeWidget variant with search field that filters available options QColorComboBoxQComboBox to select from a specified set of colors QColormapComboBoxQComboBox 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. QFlowLayout A layout that rearranges items based on parent width."},{"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.
A combo box for selecting a colormap from the entire cmap catalog.
Parameters:
Name Type Description Default parentQWidget
The parent widget.
Noneprefer_short_namesbool
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.
TruecategoriesContainer[Category]
If provided, only return names from the given categories.
()interpolationInterpolation
If provided, only return names that have the given interpolation method.
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
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
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.
Falseadd_color_textstr
The text to display for the \"Add Color\" item. Default is \"Add Color...\".
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
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
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.
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.
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
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.
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.
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.
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.
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 valueUnion[str, Quantity, Number]
The initial value to display. If a string, it will be parsed by pint.
0unitsUnion[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.
NoneuregUnitRegistry
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.
QRangeSlider inherits from QSlider and attempts to match the Qt API as closely as possible
It uses platform-specific styles (for handle, groove, & ticks) but also supports QSS style sheets.
Supports mouse wheel events
Supports more than 2 handles (e.g. slider.setValue([0, 10, 60, 80]))
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 barIsVisiblesetBarIsVisiblehideBar / showBarboolTrue Whether the bar between handles is visible. barMovesAllHandlessetBarMovesAllHandlesboolTrue Whether clicking on the bar moves all handles or just the nearest barIsRigidsetBarIsRigidboolTrue 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
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.
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.
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.
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 treeQTreeWidget
Shows the mapping as a tree of items.
filterQLineEdit
Used to filter items in the tree by matching their key against a regular expression.
"}]}
\ 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.
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:
https://bugreports.qt.io/browse/QTBUG-98093
https://github.com/pyapp-kit/superqt/issues/74
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:
set the environment variable USE_MAC_SLIDER_PATCH=1 before importing superqt (note: this is safe to use even if you're targeting more than just MacOS 12, it will only be applied when needed)
call the applyMacStylePatch() method on any of the superqt slider subclasses (note, this will override your slider styles)
apply the stylesheet manually:
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/#svg-icons","title":"SVG Icons","text":"Object Description QIconifyIcon QIcons backed by the Iconify icon library."},{"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. FunctionWorkerQRunnable with signals that wraps a simple long-running function. GeneratorWorkerQRunnable 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":"
Name Type Description Default painter_or_deviceQPainter | QPaintDevice
A QPainter instance or a QPaintDevice (e.g. a QWidget or QPixmap) onto which to paint the colormap.
required cmapColormap | 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 rectQRect | QRectF | None
A rect onto which to draw. If None, the painter.viewport() will be used. by default None
Noneborder_colorQColor | str | None
If not None, a border of color border_color and width border_width is included around the edge, by default None.
Noneborder_widthint
The width of the border to draw (provided border_color is not None), by default 2
1lighterint
Percentage by which to lighten (or darken) the colors. Greater than 100 lightens, less than 100 darkens, by default 100 (i.e. no change).
100checkerboard_sizebool
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\n\nclass W(QWidget):\n def paintEvent(self, event) -> None:\n draw_colormap(self, viridis, event.rect())\n\n\n# or draw onto a QPixmap\npm = QPixmap(200, 200)\ndraw_colormap(pm, viridis)\n
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 parentQWidget
The parent widget.
Nonefractional_colormap_widthfloat
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.33fallback_cmapColormap | str | None
The colormap to use when the current text is not a recognized colormap. by default \"gray\".
'gray'missing_iconQIcon | 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.
MISSINGcheckerboard_sizeint
Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.
4allow_invalidbool
If True, the user can enter any text, even if it does not represent a valid colormap (and fallback_cmap will be shown if it's invalid). If False, the text will be validated when editing is finished or focus is lost, and if the text is not a valid colormap, it will be reverted to the first available valid option from the completer, or, if that's not available, the last valid colormap. Default is True. This is only settable at initialization.
Delegate that draws colormaps into a QAbstractItemView item.
Parameters:
Name Type Description Default parentQObject
The parent object.
Noneitem_sizeQSize
The size hint for each item, by default QSize(80, 22).
DEFAULT_SIZEfractional_colormap_widthfloat
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.
1paddingint
The padding (in pixels) around the edge of the item, by default 1.
1checkerboard_sizeint
Size (in pixels) of the checkerboard pattern to draw behind colormaps with transparency, by default 4. If 0, no checkerboard is drawn.
Name Type Description Default parentQTextDocument | QObject | None
The parent object. Usually a QTextDocument. To use this class with a QTextArea, pass in text_area.document().
required langstr
The language of the code to highlight. This should be a string that Pygments recognizes, e.g. 'python', 'pytb', 'cpp', 'java', etc.
required themeKnownStyle | str
The name of the Pygments style to use. For a complete list of available styles, use pygments.styles.get_all_styles().
'default'
Examples:
from qtpy.QtWidgets import QTextEdit\nfrom superqt.utils import CodeSyntaxHighlight\n\ntext_area = QTextEdit()\nhighlighter = CodeSyntaxHighlight(text_area.document(), \"python\", \"monokai\")\n\n# then manually apply the background color to the text area.\npalette = text_area.palette()\nbgrd_color = QColor(self._highlight.background_color)\npalette.setColor(QPalette.ColorRole.Base, bgrd_color)\ntext_area.setPalette(palette)\n
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 exceptionstype[BaseException] | tuple[type[BaseException], ...]
The exception(s) to catch, by default Exception (i.e. all exceptions).
ExceptioniconIcon
The icon to show in the QMessageBox, by default QMessageBox.Icon.Critical
Criticaltitlestr
The title of the QMessageBox, by default \"An error occurred\".
'An error occurred'msg_templatestr
The message to show in the QMessageBox. The message will be formatted using three variables:
exc_value: the exception instance
exc_type: the exception type
tb: the traceback as a string
The default template is the content of the exception: \"{exc_value}\"
'{exc_value}'buttonsStandardButton
The buttons to show in the QMessageBox, by default QMessageBox.StandardButton.Ok
OkparentQWidget | None
The parent widget of the QMessageBox, by default None
Noneuse_error_messagebool | 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 dialogQMessageBox | 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\")).
exceptionBaseException | None
Will hold the exception instance if an exception was raised and caught.
Examples:
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
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:
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:
fonticon-fontawesome5 ('fa5s' & 'fa5r' prefixes)
fonticon-materialdesignicons6 ('mdi6' prefix)
...but fonts can also be added manually using addFont.
Parameters:
Name Type Description Default glyph_keystr
String encapsulating a font-family, style, and glyph. e.g. 'fa5s.smile'.
required scale_factorfloat
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_FACTORcolorValidColor
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).
Noneopacityfloat
Opacity of icon, by default 1
1animationAnimation
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.
NonetransformQTransform
A QTransform to apply when painting the icon, by default None
Nonestatesdict
Provide additional styling for the icon in different states. states must be a mapping of string to dict, where:
the key represents a QIcon.State (\"on\", \"off\"), a QIcon.Mode (\"normal\", \"active\", \"selected\", \"disabled\"), or any combination of a state & mode separated by an underscore (e.g. \"off_active\", \"selected_on\", etc...).
the value is a dict with all of the same key/value meanings listed above as parameters to this function (e.g. glyph_key, color,scale_factor, animation, etc...)
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)
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:
fonticon-fontawesome5
fonticon-materialdesignicons6
Parameters:
Name Type Description Default filepathstr
Path to an OTF or TTF file containing the fonts
required prefixstr
A prefix that will represent this font file when used for lookup. For example, 'fa5s' for 'Font-Awesome 5 Solid'.
required charmapDict[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.
Iconify is an icon library that includes 150,000+ icons from most major icon sets including Bootstrap, FontAwesome, Material Design, and many more; each available as individual SVGs. Unlike the superqt.fonticon module, superqt.QIconifyIcon does not require any additional dependencies or font files to be installed. Icons are downloaded (and cached) on-demand from the Iconify API, using pyconify
Search availble icons at https://icon-sets.iconify.design Once you find one you like, use the key in the format \"prefix:name\" to create an icon: QIconifyIcon(\"bi:bell\").
Iconify includes 150,000+ icons from most major icon sets including Bootstrap, FontAwesome, Material Design, and many more.
Search availble icons at https://icon-sets.iconify.design Once you find one you like, use the key in the format \"prefix:name\" to create an icon: QIconifyIcon(\"bi:bell\").
This class is a thin wrapper around the pyconify svg_path function. It pulls SVGs from iconify, creates a temporary SVG file and uses it as the source for a QIcon. SVGs are cached to disk, and persist across sessions (until pyconify.clear_cache() is called).
Parameters are the same as QIconifyIcon.addKey, which can be used to add additional icons for various modes and states to the same QIcon.
Parameters:
Name Type Description Default *keystr
Icon set prefix and name. May be passed as a single string in the format \"prefix:name\" or as two separate strings: 'prefix', 'name'.
()colorstr
Icon color. If not provided, the icon will appear black (the icon fill color will be set to the string \"currentColor\").
Noneflipstr
Flip icon. Must be one of \"horizontal\", \"vertical\", \"horizontal,vertical\"
Nonerotatestr | int
Rotate icon. Must be one of 0, 90, 180, 270, or 0, 1, 2, 3 (equivalent to 0, 90, 180, 270, respectively)
Nonedirstr
If 'dir' is not None, the file will be created in that directory, otherwise a default directory is used.
None
Examples:
>>> from qtpy.QtWidgets import QPushButton\n>>> from superqt import QIconifyIcon\n>>> btn = QPushButton()\n>>> icon = QIconifyIcon(\"bi:alarm-fill\", color=\"red\", rotate=90)\n>>> btn.setIcon(icon)\n
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).
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.
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
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.
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.
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:
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 msecsint
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.
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().
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
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 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
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 funcCallable
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.
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 funccallable
The function being run in another thread. May be a generator function.
required SignalsClasstype
A QObject subclass that contains signals, by default GeneratorWorkerSignals
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)
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:
started: emitted when the work is started
finished: emitted when the work is finished
returned: emitted with return value
errored: emitted with error object on Exception
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:
yielded: emitted with yielded values
paused: emitted when a running job has successfully paused
resumed: emitted when a paused job has successfully resumed
aborted: emitted when a running job is successfully aborted
And these methods:
quit: ask the thread to quit
toggle_paused: toggle the running state of the thread.
send: send a value into the generator. (This requires that your decorator function uses the value = yield syntax)
Parameters:
Name Type Description Default functioncallable
Function to call in another thread. For communication between threads may be a generator function.
Nonestart_threadbool
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.
NoneconnectDict[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
Noneworker_classType[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.
Noneignore_errorsbool
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\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
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 funcCallable
The function to call in another thread.
required _start_threadbool
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_connectDict[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_classtype 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_errorsbool
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 workerWorkerBase
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}
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 WorkerQObject
QObject type that implements a work() method. The Worker should also emit a finished signal when the work is done.
required _start_threadbool
If True, thread will be started immediately, otherwise, thread must be manually started with thread.start().
False_connectdict
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 workerWorkerBase
The created worker.
threadQThread
The thread on which the worker is running.
Examples:
Create some QObject that has a long-running work method:
class Worker(QObject):\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\n for i in range(10):\n time.sleep(1)\n self.increment.emit(i)\n self.finished.emit()\n\n\nworker, thread = new_worker_qthread(\n Worker,\n \"argument\",\n _start_thread=True,\n _connect={\"increment\": print},\n)\n
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).
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 funcCallable
A function to throttle
Nonetimeoutint
Timeout in milliseconds to wait before allowing another call, by default 100
100leadingbool
Whether to invoke the function on the leading edge of the wait timer, by default False
Falsetimer_typeTimerType
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
PreciseTimerparentQObject | None
Parent object for timer. If using qthrottled as function it may be usefull for cleaning data
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 funcCallable
A function to throttle
Nonetimeoutint
Timeout in milliseconds to wait before allowing another call, by default 100
100leadingbool
Whether to invoke the function on the leading edge of the wait timer, by default True
Truetimer_typeTimerType
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
PreciseTimerparentQObject | None
Parent object for timer. If using qthrottled as function it may be usefull for cleaning data
"},{"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 QLabeledDoubleRangeSliderQDoubleRangeSlider variant with editable labels for each handle QLabeledDoubleSliderQSlider for float values with editable QSpinBox with the current value QLabeledRangeSliderQRangeSlider variant, with editable labels for each handle QLabeledSliderQSlider with editable QSpinBox that shows the current value QLargeIntSpinBoxQSpinbox 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. QEnumComboBoxQComboBox that populates the combobox from a python EnumQSearchableComboBoxQComboBox variant that filters available options based on text input QSearchableListWidgetQListWidget variant with search field that filters available options QSearchableTreeWidgetQTreeWidget variant with search field that filters available options QColorComboBoxQComboBox to select from a specified set of colors QColormapComboBoxQComboBox to select from a specified set of colormaps. QToggleSwitchQAbstractButton that represents a boolean value with a toggle switch."},{"location":"widgets/#frames-and-containers","title":"Frames and containers","text":"Widget Description QCollapsible A collapsible widget to hide and unhide child widgets. QFlowLayout A layout that rearranges items based on parent width."},{"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.
A combo box for selecting a colormap from the entire cmap catalog.
Parameters:
Name Type Description Default parentQWidget
The parent widget.
Noneprefer_short_namesbool
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.
TruecategoriesContainer[Category]
If provided, only return names from the given categories.
()interpolationInterpolation
If provided, only return names that have the given interpolation method.
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
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
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.
Falseadd_color_textstr
The text to display for the \"Add Color\" item. Default is \"Add Color...\".
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
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
Set whether the user can enter/filter colormaps by typing in the line edit.
If enabled, the user can select the text in the line edit and type to filter the list of colormaps. The completer will show a list of matching colormaps as the user types. If disabled, the user can only select from the combo box dropdown.
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.
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.
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
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.
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.
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.
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.
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 valueUnion[str, Quantity, Number]
The initial value to display. If a string, it will be parsed by pint.
0unitsUnion[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.
NoneuregUnitRegistry
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.
QRangeSlider inherits from QSlider and attempts to match the Qt API as closely as possible
It uses platform-specific styles (for handle, groove, & ticks) but also supports QSS style sheets.
Supports mouse wheel events
Supports more than 2 handles (e.g. slider.setValue([0, 10, 60, 80]))
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 barIsVisiblesetBarIsVisiblehideBar / showBarboolTrue Whether the bar between handles is visible. barMovesAllHandlessetBarMovesAllHandlesboolTrue Whether clicking on the bar moves all handles or just the nearest barIsRigidsetBarIsRigidboolTrue 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
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.
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.
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.
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-6/qregularexpression.html#details
Attributes:
Name Type Description treeQTreeWidget
Shows the mapping as a tree of items.
filterQLineEdit
Used to filter items in the tree by matching their key against a regular expression.
QToggleSwitch is a QAbstractButton subclass that represents a boolean value as a toggle switch. The API is similar to QCheckBox but with a different visual representation.
If True, the user can enter any text, even if it does not represent a valid
+colormap (and fallback_cmap will be shown if it's invalid). If False, the text
+will be validated when editing is finished or focus is lost, and if the text is
+not a valid colormap, it will be reverted to the first available valid option
+from the completer, or, if that's not available, the last valid colormap.
+Default is True. This is only settable at initialization.
Set whether the user can enter/filter colormaps by typing in the line edit.
+
If enabled, the user can select the text in the line edit and type to
+filter the list of colormaps. The completer will show a list of matching
+colormaps as the user types. If disabled, the user can only select from
+the combo box dropdown.
QEnumComboBox is a variant of
-QComboBox that populates the items in
+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
diff --git a/widgets/qflowlayout/index.html b/widgets/qflowlayout/index.html
index 04a4b93..8914024 100644
--- a/widgets/qflowlayout/index.html
+++ b/widgets/qflowlayout/index.html
@@ -596,6 +596,8 @@
+
+
@@ -1136,6 +1138,27 @@
+
+
+
+
+
+
+
QRangeSlider inherits from QSlider
and attempts to match the Qt API as closely as possible
It uses platform-specific styles (for handle, groove, & ticks) but also supports
QSS style sheets.
@@ -1531,8 +1620,8 @@ select a range of values.
Supports more than 2 handles (e.g. slider.setValue([0, 10, 60, 80]))
As QRangeSlider inherits from
-QtWidgets.QSlider, you can use all of
-the same methods available in the QSlider
+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.)
@@ -1716,6 +1805,9 @@ the tuple is equal to the number of handles in the slider.)
QSearchableComboBox is a variant of
-QComboBox that allow to filter list
+QComboBox that allow to filter list
of options by enter part of text. It could be drop in replacement for
QComboBox.
QSearchableListWidget is a variant of
-QListWidget that add text entry
+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
+QListWidget but it does fully
satisfy its api. The only limitation is that it cannot be used as argument of
-QListWidgetItem constructor.
+
+
+
+
@@ -1259,7 +1284,7 @@ If the mapping changes, the easiest way to update this is by calling setDa
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
+https://doc.qt.io/qt-6/qregularexpression.html#details
QToggleSwitch is a
+QAbstractButton subclass
+that represents a boolean value as a toggle switch. The API is similar to
+QCheckBox but with a different
+visual representation.