OWBaseWidget¶
The OWBaseWidget
is the main component for implementing a widget in
the Orange Canvas workflow. It both defines the widget input/output
capabilities and implements it’s functionality within the canvas.
Widget Meta Description¶
Every widget in the canvas framework needs to define it’s meta definition. This includes the widget’s name and text descriptions but more importantly also its input/output specification.
class IntConstant(OWBaseWidget):
name = "Integer Constant"
description = "A simple integer constant"
class Outputs:
constant = Output("Constant", int)
...
def commit(self):
"""Commit/send the outputs."""
self.Outputs.constant.send(42)
Omitting the implementation details, this defines a simple node named
Integer Constant which outputs (on a signal called Constant) a single
object of type int
.
The node’s inputs are defined similarly. Each input is then used as a decorator of its corresponding handler method, which accepts the inputs at runtime:
class Adder(OWBaseWidget):
name = "Add two integers"
description = "Add two numbers"
class Inputs:
a = Input("A", int)
b = Input("B", int)
class Outputs:
sum = Input("A + B", int)
...
@Inputs.a
def set_A(self, a):
"""Set the `A` input."""
self.A = a
@Inputs.b
def set_B(self, b):
"""Set the `B` input."""
self.B = b
def handleNewSignals(self):
"""Coalescing update."""
self.commit()
def commit(self):
"""Commit/send the outputs"""
sef.Outputs.sum.send(self.A + self.B)
See also
Input/Output Signal Definitions¶
Widgets specify their input/output capabilities in their class definitions by defining classes named Inputs and Outputs, which contain class attributes of type Input and Output, correspondingly. Input and Output require at least two arguments, the signal’s name (as shown in canvas) and type. Optional arguments further define the behaviour of the signal.
Note: old-style signals define the input and output signals using class attributes inputs and outputs instead of classes Input and Output. The two attributes contain a list of tuples with the name and type and, for inputs, the name of the handler method. The optional last argument is an integer constant giving the flags. This style of signal definition is deprecated.
- class orangewidget.widget.Input(name, type, id=None, doc=None, replaces=None, *, multiple=False, default=False, explicit=False, auto_summary=None, closing_sentinel=None)[source]¶
Description of an input signal.
The class is used to declare input signals for a widget as follows (the example is taken from the widget Test & Score):
class Inputs: train_data = Input("Data", Table, default=True) test_data = Input("Test Data", Table) learner = Input("Learner", Learner, multiple=True) preprocessor = Input("Preprocessor", Preprocess)
Every input signal must be used to decorate exactly one method that serves as the input handler, for instance:
@Inputs.train_data def set_train_data(self, data): ...
- Parameters:
(str) (id) – signal name
(type) (type) – signal type
(str) – a unique id of the signal
(str (doc) – signal documentation
optional) – signal documentation
str) (replaces (list of) – a list with names of signals replaced by this signal
(bool (auto_summary) – if set, multiple signals can be connected to this output (default: False)
optional) – if set, multiple signals can be connected to this output (default: False)
(bool – when the widget accepts multiple signals of the same type, one of them can set this flag to act as the default (default: False)
optional) – when the widget accepts multiple signals of the same type, one of them can set this flag to act as the default (default: False)
(bool – if set, this signal is only used when it is the only option or when explicitly connected in the dialog (default: False)
optional) – if set, this signal is only used when it is the only option or when explicitly connected in the dialog (default: False)
(bool – by default, the input is reflected in widget’s summary for all types with registered summarize function. This can be overridden by explicitly setting auto_summary to False or True. Explicitly setting this argument will also silence warnings for types without the summary function and for types defined with a fully qualified string instead of an actual type object.
optional) – by default, the input is reflected in widget’s summary for all types with registered summarize function. This can be overridden by explicitly setting auto_summary to False or True. Explicitly setting this argument will also silence warnings for types without the summary function and for types defined with a fully qualified string instead of an actual type object.
- class orangewidget.widget.MultiInput(*args, filter_none=False, **kwargs)[source]¶
A special multiple input descriptor.
This type of input has explicit set/insert/remove interface to maintain fully ordered sequence input. This should be preferred to the plain Input(…, multiple=True) descriptor.
This input type must register three methods in the widget implementation class corresponding to the insert, set/update and remove input commands:
class Inputs: values = MultiInput("Values", object) ... @Inputs.values def set_value(self, index: int, value: object): "Set/update the value at index" ... @Inputs.values.insert def insert_value(self, index: int, value: object): "Insert value at specified index" ... @Inputs.values.remove def remove_value(self, index: int): "Remove value at index" ...
- Parameters:
filter_none (bool) – If True any None values sent by workflow execution are implicitly converted to ‘remove’ notifications. When the value again changes to non-None the input is re-inserted into its proper position.
Added in version 4.13.0.
- class orangewidget.widget.Output(name, type, id=None, doc=None, replaces=None, *, default=False, explicit=False, dynamic=True, auto_summary=None)[source]¶
Description of an output signal.
The class is used to declare output signals for a widget as follows (the example is taken from the widget Test & Score):
class Outputs: predictions = Output("Predictions", Table) evaluations_results = Output("Evaluation Results", Results)
The signal is then transmitted by, for instance:
self.Outputs.predictions.send(predictions)
- Parameters:
(str) (id) – signal name
(type) (type) – signal type
(str) – a unique id of the signal
(str (doc) – signal documentation
optional) – signal documentation
str) (replaces (list of) – a list with names of signals replaced by this signal
(bool (auto_summary) – when the widget accepts multiple signals of the same type, one of them can set this flag to act as the default (default: False)
optional) – when the widget accepts multiple signals of the same type, one of them can set this flag to act as the default (default: False)
(bool – if set, this signal is only used when it is the only option or when explicitly connected in the dialog (default: False)
optional) – if set, this signal is only used when it is the only option or when explicitly connected in the dialog (default: False)
(bool – Specifies that the instances on the output will in general be subtypes of the declared type and that the output can be connected to any input signal which can accept a subtype of the declared output type (default: True)
optional) – Specifies that the instances on the output will in general be subtypes of the declared type and that the output can be connected to any input signal which can accept a subtype of the declared output type (default: True)
(bool – by default, the output is reflected in widget’s summary for all types with registered summarize function. This can be overridden by explicitly setting auto_summary to False or True. Explicitly setting this argument will also silence warnings for types without the summary function and for types defined with a fully qualified string instead of an actual type object.
optional) – by default, the output is reflected in widget’s summary for all types with registered summarize function. This can be overridden by explicitly setting auto_summary to False or True. Explicitly setting this argument will also silence warnings for types without the summary function and for types defined with a fully qualified string instead of an actual type object.
Sending/Receiving¶
The widgets receive inputs at runtime with the handler method decorated with the signal, as shown in the above examples.
If an input is defined with the flag multiple set, the input handler method also receives a connection id uniquely identifying a connection/link on which the value was sent (see also Channels and Tokens)
The widget sends an output by calling the signal’s send method, as shown above.
Accessing Controls though Attribute Names¶
The preferred way for constructing the user interface is to use functions from
module orangewidget.gui
that insert a Qt widget and establish the
signals for synchronization with the widget’s attributes.
gui.checkBox(box, self, “binary_trees”, “Induce binary tree”)
This inserts a QCheckBox into the layout of box, and make it reflect and changes the attriubte self.binary_trees. The instance of QCheckbox can be accessed through the name it controls. E.g. we can disable the check box by calling
self.controls.binary_trees.setDisabled(True)
This may be more practical than having to store the attribute and the Qt widget that controls it, e.g. with
- self.binarization_cb = gui.checkBox(
box, self, “binary_trees”, “Induce binary tree”)
Class Member Documentation¶
- class orangewidget.widget.OWBaseWidget(*args, captionTitle=None, **kwargs)[source]¶
Base widget class in an Orange widget workflow.
- class Inputs[source]¶
Define inputs in this nested class as class variables. (type orangewidget.widget.Input)
Example:
class Inputs: data = Input("Data", Table)
Then, register input handler methods with decorators.
Example:
@Inputs.data def set_data(self, data): self.my_data = data
- class Outputs[source]¶
Define outputs in this nested class as class variables. (type orangewidget.widget.Output)
Example:
class Outputs: data = Output("Data", Table)
Then, send results to the output with its send method.
Example:
def commit(self): self.Outputs.data.send(self.my_data)
- want_basic_layout = True¶
Should the widget have basic layout? (if not, the rest of the GUI layout settings are ignored)
- want_control_area = True¶
Should the widget construct a controlArea?
- want_main_area = True¶
Should the widget construct a mainArea? (a resizable area to the right of the controlArea)
- want_message_bar = True¶
Should the widget construct a message_bar? (if not, make sure you show warnings/errors in some other way)
- resizing_enabled = True¶
Should the widget’s window be resizeable? (if not, the widget will derive a fixed size constraint from its layout)
- save_position = True¶
Should the widget remember its window position/size?
- buttons_area_orientation = 1¶
Orientation of the buttonsArea box; valid only if want_control_area is True. Possible values are Qt.Horizontal, Qt.Vertical and None for no buttons area
- UserAdviceMessages: List[Message] = []¶
A list of advice messages to display to the user. (when a widget is first shown a message from this list is selected for display. If a user accepts (clicks ‘Ok. Got it’) the choice is recorded and the message is never shown again (closing the message will not mark it as seen). Messages can be displayed again by pressing Shift + F1)
- settings_version: int = 1¶
Version of the settings representation (subclasses should increase this number when they make breaking changes to settings representation (a settings that used to store int now stores string) and handle migrations in migrate and migrate_context settings)
- settingsAboutToBePacked¶
Signal emitted before settings are packed and saved. (gives you a chance to sync state to Setting values)
- settingsHandler: SettingsHandler = None¶
Settings handler, can be overridden for context handling.
- short_name: str = None¶
Short name for widget, displayed in toolbox. (set this if the widget’s conventional name is long)
- mainArea_width_height_ratio: float | None = 1.1¶
Ratio between width and height for mainArea widgets, set to None for super().sizeHint()
- set_basic_layout()[source]¶
Provide the basic widget layout
Which parts are created is regulated by class attributes want_main_area, want_control_area, want_message_bar and buttons_area_orientation, the presence of method send_report and attribute graph_name.
- statusBar() QStatusBar [source]¶
Return the widget’s status bar.
The status bar can be hidden/shown (self.statusBar().setVisible()).
Note
The status bar takes control of the widget’s bottom margin (contentsMargins) to layout itself in the OWBaseWidget.
- property info: StateInfo¶
A namespace for reporting I/O, state … related messages.
Added in version 3.19.
- Returns:
namespace
- Return type:
- save_graph()[source]¶
Save the graph with the name given in class attribute graph_name.
The method is called by the Save graph button, which is created automatically if the graph_name is defined.
- resizeEvent(event)[source]¶
Overloaded to save the geometry (width and height) when the widget is resized.
- openContext(*a)[source]¶
Open a new context corresponding to the given data.
The settings handler first checks the stored context for a suitable match. If one is found, it becomes the current contexts and the widgets settings are initialized accordingly. If no suitable context exists, a new context is created and data is copied from the widget’s settings into the new context.
Widgets that have context settings must call this method after reinitializing the user interface (e.g. combo boxes) with the new data.
The arguments given to this method are passed to the context handler. Their type depends upon the handler. For instance, DomainContextHandler expects Orange.data.Table or Orange.data.Domain.
- closeContext()[source]¶
Save the current settings and close the current context.
Widgets that have context settings must call this method before reinitializing the user interface (e.g. combo boxes) with the new data.
- retrieveSpecificSettings()[source]¶
Retrieve data that is not registered as setting.
This method is called by orangewidget.settings.ContextHandler.settings_to_widget. Widgets may define it to retrieve any data that is not stored in widget attributes. See
Orange.widgets.data.owcolor.OWColor
for an example.
- storeSpecificSettings()[source]¶
Store data that is not registered as setting.
This method is called by orangewidget.settings.ContextHandler.settings_from_widget. Widgets may define it to store any data that is not stored in widget attributes. See
Orange.widgets.data.owcolor.OWColor
for an example.
- saveSettings()[source]¶
Writes widget instance’s settings to class defaults. Usually called when the widget is deleted.
- onDeleteWidget()[source]¶
Invoked by the canvas to notify the widget it has been deleted from the workflow.
If possible, subclasses should gracefully cancel any currently executing tasks.
- handleNewSignals()[source]¶
Invoked by the workflow signal propagation manager after all signals handlers have been called.
Reimplement this method in order to coalesce updates from multiple updated inputs.
- statusMessageChanged¶
Widget’s status message has changed.
- setStatusMessage(text)[source]¶
Set widget’s status message.
This is a short status string to be displayed inline next to the instantiated widget icon in the canvas.
- setBlocking(state=True) None [source]¶
Set blocking flag for this widget.
While this flag is set this widget and all its descendants will not receive any new signals from the workflow signal manager.
Deprecated since version 4.2.0: Setting/clearing this flag is equivalent to setInvalidated(True); setReady(False) and setInvalidated(False); setReady(True) respectively. Use
setInvalidated()
andsetReady()
in new code.See also
- setInvalidated(state: bool) None [source]¶
Set/clear invalidated flag on this widget.
While this flag is set none of its descendants will receive new signals from the workflow execution manager.
This is useful for instance if the widget does it’s work in a separate thread or schedules processing from the event queue. In this case it can set the invalidated flag when starting a task. After the task has completed the widget can clear the flag and send the updated outputs.
Note
Failure to clear this flag will block dependent nodes forever.
See also
invalidate()
for a more fine grained invalidation.
- setReady(state: bool) None [source]¶
Set/clear ready flag on this widget.
While a ready flag is unset, the widget will not receive any new input updates from the workflow execution manager.
By default this flag is True.
- workflowEnv()[source]¶
Return (a view to) the workflow runtime environment.
- Returns:
env
- Return type:
- workflowEnvChanged(key, value, oldvalue)[source]¶
A workflow environment variable key has changed to value.
Called by the canvas framework to notify widget of a change in the workflow runtime environment.
The default implementation does nothing.
- saveGeometryAndLayoutState() QByteArray [source]¶
Save the current geometry and layout state of this widget and child windows (if applicable).
- Returns:
state – Saved state.
- Return type:
QByteArray
- restoreGeometryAndLayoutState(state: QByteArray) bool [source]¶
Restore the geometry and layout of this widget to a state previously saved with
saveGeometryAndLayoutState()
.- Parameters:
state (QByteArray) – Saved state.
- Returns:
success – True if the state was successfully restored, False otherwise.
- Return type:
- classmethod migrate_settings(settings, version)[source]¶
Fix settings to work with the current version of widgets
- class orangewidget.widget.Message(text, persistent_id, icon=None, moreurl=None)[source]¶
A user message.
- Parameters:
See also
- class orangewidget.widget.StateInfo(*args, **kwargs)[source]¶
A namespace for OWBaseWidget’s detailed input/output/state summary reporting.
See also
- class Summary(brief: str = '', details: str = '', icon: ~PyQt5.QtGui.QIcon = <PyQt5.QtGui.QIcon object>, format: ~PyQt5.QtCore.Qt.TextFormat = 0)[source]¶
Input/output summary description.
This class is used to hold and report detailed I/O summaries.
- icon¶
An custom icon. If not set a default set will be used to indicate special states (i.e. empty input …)
- Type:
QIcon
- format¶
Qt.PlainText if brief and details are to be rendered as plain text or Qt.RichText if they are HTML.
- Type:
Qt.TextFormat
- class Empty(brief: str = '', details: str = '', icon: ~PyQt5.QtGui.QIcon = <PyQt5.QtGui.QIcon object>, format: ~PyQt5.QtCore.Qt.TextFormat = 0)[source]¶
Bases:
Summary
Input/output summary description indicating empty I/O state.
- class Partial(brief: str = '', details: str = '', icon: ~PyQt5.QtGui.QIcon = <PyQt5.QtGui.QIcon object>, format: ~PyQt5.QtCore.Qt.TextFormat = 0)[source]¶
Bases:
Summary
Input summary indicating partial input.
This state indicates that some inputs are present but more are needed in order for the widget to proceed.
- NoInput Empty()¶
A default message displayed to indicate no inputs.
- NoOutput Empty()¶
A default message displayed to indicate no output.
- set_input_summary(summary: Optional[StateInfo.Summary]])[source]¶
Set the input summary description.
- Parameters:
summary (Optional[StateInfo.Summary])
- set_input_summary(brief: str, detailed: str = '', icon: QIcon = QIcon, format: Qt.TextFormat = Qt.PlainText)[source]
- set_input_summary(number: int)[source]
Automatically format number with metric suffixes and set it as input summary.
- set_output_summary(summary: Optional[StateInfo.Summary]])[source]¶
Set the output summary description.
- Parameters:
summary (Optional[StateInfo.Summary])
- set_output_summary(brief: str, detailed: str = '', icon: QIcon = QIcon, format: Qt.TextFormat = Qt.PlainText)[source]
- set_output_summary(number: int)[source]
Automatically format number with metric suffixes and set it as output summary.
- format_number(n: int) str [source]¶
Format integers larger then 9999 with metric suffix and at most 3 digits.
- input_summary_changed(message: StateInfo.Summary)¶
Signal emitted when the input summary changes
- output_summary_changed(message: StateInfo.Summary)¶
Signal emitted when the output summary changes