.. _howto-custom-widgets: Create custom Taurus widgets ============================ Use :class:`taurus.qt.qtgui.base.TaurusBaseComponent` (or one of its derived mixin classes) when a custom Qt widget needs to interact directly with Taurus models. For background on the widget model API and the available customization levels, see :ref:`custom-widgets`. Create a single-model widget ---------------------------- The following example creates a simple power-meter widget by combining a :class:`QProgressBar` with :class:`taurus.qt.qtgui.base.TaurusBaseComponent`: .. literalinclude:: ../_examples/powermeter.py :language: python :linenos: :emphasize-lines: 6, 10-11, 19-24 The mixin provides the Taurus functionality for setting and subscribing to a model. The widget implements ``handleEvent``, which is called whenever the attached model is updated. If the widget is generic enough to be useful to others, consider contributing it to Taurus or distributing it as a :ref:`Taurus plugin `. Add support for multiple models ------------------------------- To attach several models to one widget, define the supported keys in ``modelKeys`` and handle events according to their source. This version of the power-meter adds a second model that supplies the background color: .. literalinclude:: ../_examples/powermeter2.py :language: python :linenos: :emphasize-lines: 13-14,25,27-28,39 The first key returned by ``modelKeys`` is used as the default when a model API method is called without an explicit key. Handle a list of models ----------------------- Use the special ``MLIST`` key when the widget must operate on an arbitrary list of models. The following widget logs events received from a list of attributes: .. literalinclude:: ../_examples/eventlogger.py :language: python :linenos: Calling ``setModel`` with ``key=MLIST`` expects a sequence of model names. Taurus adds generated keys of the form ``(MLIST, i)`` to the widget's model list, and the corresponding models can then be accessed using the normal multi-model API. Delegate models to child widgets -------------------------------- A container widget does not need to process all model events itself. It can create Taurus child widgets and assign the models to them instead. The following simplified form creates a label and a value widget for every model: .. literalinclude:: ../_examples/simpleform.py :language: python :linenos: In this example the container does not reimplement ``handleEvent``. Instead, it calls ``setModel`` on its child widgets and lets each child handle the events from its own model.