12. widgets — A collection of custom widgets used in the pyFormex GUI

A collection of custom widgets used in the pyFormex GUI

The widgets in this module were primarily created in function of the pyFormex GUI. The user can apply them to change the GUI or to add interactive widgets to his scripts. Of course he can also use all the Qt widgets directly.

class widgets.Options
Options objects have the following methods:
class widgets.FileSelection(path, pattern=None, exist=False, multi=False, dir=False)

A file selection dialog.

You can specify a default path/filename that will be suggested initially. If a pattern is specified, only matching files will be shown. A pattern can be something like Images (*.png *.jpg) or a list of such strings. Default mode is to accept any filename. You can specify exist=True to accept only existing files. Or set exist=True and multi=True to accept multiple files. If dir==True, a single existing directory is asked.

The constructor shows the widget.

FileSelection objects have the following methods:

show(timeout=None, timeoutfunc=None, modal=False)
getFilename(timeout=None)

Ask for a filename by user interaction.

Return the filename selected by the user. If the user hits CANCEL or ESC, None is returned.

class widgets.ProjectSelection(path=None, pattern=None, exist=False, compression=0)

A file selection dialog specialized for opening projects.

Create the dialog.

ProjectSelection objects have the following methods:

getResult()
class widgets.SaveImageDialog(path=None, pattern=None, exist=False, multi=False)

A dialog for saving to an image file.

The dialog contains the normal file selection widget plus some extra fields to set the Save Image parameters.

Create the dialog.

SaveImageDialog objects have the following methods:

getResult()
class widgets.ImageViewerDialog(path=None)

A dialog to select an image file.

The dialog helps selecting the correct image by displaying the image in an image viewer widget.

ImageViewerDialog objects have the following methods:

getFilename()

Ask for a filename by user interaction.

Return the filename selected by the user. If the user hits CANCEL or ESC, None is returned.

class widgets.AppearenceDialog

A dialog for setting the GUI appearance.

The dialog lets you select one of the Qt styles.

Create the Appearance dialog.

AppearenceDialog objects have the following methods:

setFont()
getResult()
class widgets.DockedSelection(slist=[], title='Selection Dialog', mode=None, sort=False, func=None)

A widget that is docked in the main window and contains a modeless dialog for selecting items.

DockedSelection objects have the following methods:

setSelected(selected, bool)
getResult()
class widgets.ModelessSelection(slist=[], title='Selection Dialog', mode=None, sort=False, func=None, width=None, height=None)

A modeless dialog for selecting one or more items from a list.

Create the SelectionList dialog.

ModelessSelection objects have the following methods:

setSelected(selected, bool)
Mark the specified items as selected.
getResult()

Return the list of selected values.

If the user cancels the selection operation, the return value is None. Else, the result is always a list, possibly empty or with a single value.

class widgets.Selection(slist=[], title='Selection Dialog', mode=None, sort=False, selected=[])

A dialog for selecting one or more items from a list.

Create the SelectionList dialog.

selected is a list of items that are initially selected.

Selection objects have the following methods:

setSelected(selected)
Mark the specified items as selected.
getResult()

Return the list of selected values.

If the user cancels the selection operation, the return value is None. Else, the result is always a list, possibly empty or with a single value.

class widgets.InputItem(name, *args, **kargs)

A single input item, usually with a label in front.

The created widget is a QHBoxLayout which can be embedded in the vertical layout of a dialog.

This is a super class for all input items. It just creates a label. The input field(s) should be added by the dedicated subclass.

The constructor has one required argument: name. It is the name used to identify the item and should be unique for all InputItems in the same dialog. Other (optional) positional parameters are passed to the QHBoxLayout constructor.

By default the constructor adds a label to the QHBoxLayout, with text set by the text keyword argument or (by default) by the name of the item. Use the text argument if you want the displayed text to be different from the items name. A text='' parameter will suppress the label. This is e.g. used in the InputBoolean constructor, where the text is displayed by the input field.

The superclass also defines default values for the text(), value() and setValue() methods.

Subclasses should initialize the superclass as follows: InputItem.__init__(self,name,*args,**kargs)

Subclasses should override:

  • text(): if they called the superclass __init__() method with text='';
  • value(): if they did not create a self.input widget who’s text() is the return value of the item.
  • setValue(): always, unless the field is readonly.

Subclasses can set validators on the input, like input.setValidator(QtGui.QIntValidator(input))

Subclasses can define a show() method e.g. to select the data in the input field on display of the dialog.

Creates a horizontal box layout and puts the label in it.

InputItem objects have the following methods:

name()
Return the name of the InputItem.
text()
Return the displayed text of the InputItem.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputInfo(name, value, *args, **kargs)

An unchangeable input field with a label in front.

It is just like an InputString, but the text can not be edited.

There are no specific options.

Creates the input item.

InputInfo objects have the following methods:

value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputString(name, value, *args, **kargs)

A string input field with a label in front.

If the type of value is not a string, the input string will be eval’ed before returning.

There are no specific op[tions.

Creates the input item.

InputString objects have the following methods:

show()
Select all text on first display.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputText(name, value, *args, **kargs)

A scrollable text input field with a label in front.

If the type of value is not a string, the input text will be eval’ed before returning.

There are no specific op[tions.

Creates the input item.

InputText objects have the following methods:

show()
Select all text on first display.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputBool(name, value, *args, **kargs)

A boolean input item.

Creates a new checkbox for the input of a boolean value.

Displays the name next to a checkbox, which will initially be set if value evaluates to True. (Does not use the label) The value is either True or False,depending on the setting of the checkbox.

InputBool objects have the following methods:

text()
Return the displayed text.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputCombo(name, default, choices=[], *args, **kargs)

A combobox InputItem.

Creates a new combobox for the selection of a value from a list.

choices is a list/tuple of possible values. default is the initial/default choice. If default is not in the choices list, it is prepended. If default is None, the first item of choices is taken as the default.

The choices are presented to the user as a combobox, which will initially be set to the default value.

InputCombo objects have the following methods:

value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputRadio(name, default, choices=[], direction='h', *args, **kargs)

A radiobuttons InputItem.

Creates radiobuttons for the selection of a value from a list.

choices is a list/tuple of possible values. default is the initial/default choice. If default is not in the choices list, it is prepended. If default is None, the first item of choices is taken as the default.

The choices are presented to the user as a hbox with radio buttons, of which the default will initially be pressed. If direction == ‘v’, the options are in a vbox.

InputRadio objects have the following methods:

value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputPush(name, default=None, choices=[], direction='h', *args, **kargs)

A pushbuttons InputItem.

Creates pushbuttons for the selection of a value from a list.

choices is a list/tuple of possible values. default is the initial/default choice. If default is not in the choices list, it is prepended. If default is None, the first item of choices is taken as the default.

The choices are presented to the user as a hbox with radio buttons, of which the default will initially be pressed. If direction == ‘v’, the options are in a vbox.

InputPush objects have the following methods:

setText(text, index=0)
Change the text on button index.
setIcon(icon, index=0)
Change the icon on button index.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputInteger(name, value, *args, **kargs)

An integer input item.

Options:

  • ‘min, ‘max’: range of the scale (integer)

Creates a new integer input field with a label in front.

InputInteger objects have the following methods:

show()
Select all text on first display.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputFloat(name, value, *args, **kargs)

An float input item.

Creates a new float input field with a label in front.

InputFloat objects have the following methods:

show()
Select all text on first display.
value()
Return the widget’s value.
setValue(val)
Change the widget’s value.
class widgets.InputSlider(name, value, *args, **kargs)

An integer input item using a slider.

Options:

  • min, max: range of the scale (integer)
  • ticks : step for the tick marks (default range length / 10)
  • func : an optional function to be called whenever the value is changed. The function takes a float/integer argument.

Creates a new integer input slider.

InputSlider objects have the following methods:

set_value(val)
class widgets.InputFSlider(name, value, *args, **kargs)

A float input item using a slider.

Options:

  • ‘min’, ‘max’: range of the scale (integer)
  • ‘scale’: scale factor to compute the float value
  • ‘ticks’ : step for the tick marks (default range length / 10)
  • ‘func’ : an optional function to be called whenever the value is changed. The function takes a float/integer argument.

Creates a new integer input slider.

InputFSlider objects have the following methods:

set_value(val)
class widgets.InputColor(name, value, *args, **kargs)

A color input item.

Creates a new color input field with a label in front.

The color input field is a button displaying the current color. Clicking on the button opens a color dialog, and the returned value is set in the button.

InputColor objects have the following methods:

setColor()
setValue(value)
Change the widget’s value.
class widgets.InputDialog(items, caption=None, parent=None, flags=None, actions=None, default=None, scroll=False)

A dialog widget to set the value of one or more items.

While general input dialogs can be constructed from all the underlying Qt classes, this widget provides a way to construct fairly complex input dialogs with a minimum of effort.

The input dialog can be modal or non-modal dialog.

Create a dialog asking the user for the value of items.

items is either a list of items, or a dict where each value is a list of items. If items is a dict, a tabbed widget will be created with a tab for each (key,value) pair in the dict.

Each item in an items list is a list or tuple of the form (name,value,type,options), where the fields have the following meaning:

  • name: the name of the field,
  • value: the initial or default value of the field,
  • type: the type of values the field can accept,
  • options: a dict with options for the field.

At least the name and initial value need to be specified. The type can often be determined from the initial value. Some types set the initial value from an option if it was an empty string or None. The options dictionary has both generic options, available for all item types, and type specific options.

Each item specifies a single input field, and its value will be contained in the results dictionary using the field name as a key.

For each item a single input line is created in the dialog. This line by default consists of a label displaying the field name and a LineEdit widget where the initial value is displayed and can be changed. Where appropriate, a validator function is attached to it.

The following options are applicable to all item types:

  • text: if specified, the text value will be displayed instead of the name. The name value will remain the key in the return dict. Use this field to display a more descriptive text for the user, while using a short name for handling the value in your script.
  • buttons:
  • tooltip:

Currently, the following item types are available:

The item specific options: - min - max - range: the range of values the field can accept, - choices

The first two fields are mandatory. In many cases the type can be determined from the value and no other fields are required. Thus:

  • [ ‘name’, ‘value’ ] will accept any string (initial string = ‘value’),
  • [ ‘name’, True ] will show a checkbox with the item checked,
  • [ ‘name’, 10 ] will accept any integer,
  • [ ‘name’, 1.5 ] will accept any float.

Range settings for int and float types:

  • [ ‘name’, 1, int, 0, 4 ] will accept an integer from 0 to 4, inclusive
  • [ ‘name’, 1, float, 0.0, 1.0, 2 ] will accept a float in the range from 0.0 to 1.0 with a maximum of two decimals.

Composed types:

  • [ ‘name’, ‘option1’, ‘select’, [‘option0’,’option1’,’option2’]] will present a combobox to select between one of the options. The initial and default value is ‘option1’.
  • [ ‘name’, ‘option1’, ‘radio’, [‘option0’,’option1’,’option2’]] will present a group of radiobuttons to select between one of the options. The initial and default value is ‘option1’. A variant ‘vradio’ aligns the options vertically.
  • [ ‘name’, ‘option1’, ‘push’, [‘option0’,’option1’,’option2’]] will present a group of pushbuttons to select between one of the options. The initial and default value is ‘option1’. A variant ‘vpush’ aligns the options vertically.
  • [ ‘name’, ‘red’, ‘color’ ] will present a color selection widget, with ‘red’ as the initial choice.

InputDialog objects have the following methods:

timeout()
Hide the dialog and set the result code to TIMEOUT
timedOut()
Returns True if the result code was set to TIMEOUT
show(timeout=None, timeoutfunc=None, modal=False)

Show the dialog.

For a non-modal dialog, the user has to call this function to display the dialog. For a modal dialog, this is implicitely executed by getResult().

If a timeout is given, start the timeout timer.

acceptData(result=ACCEPTED)

Update the dialog’s return value from the field values.

This function is connected to the ‘accepted()’ signal. Modal dialogs should normally not need to call it. In non-modal dialogs however, you can call it to update the results without having to raise the accepted() signal (which would close the dialog).

updateData(d)

Update a dialog from the data in given dictionary.

d is a dictionary where the keys are field names in the dialog. The values will be set in the corresponding input items.

getResult(timeout=None)

Get the results from the input dialog.

This fuction is used to present a modal dialog to the user (i.e. a dialog that must be ended before the user can continue with the program. The dialog is shown and user interaction is processed. The user ends the interaction either by accepting the data (e.g. by pressing the OK button or the ENTER key) or by rejecting them (CANCEL button or ESC key). On accept, a dictionary with all the fields and their values is returned. On reject, an empty dictionary is returned.

If a timeout (in seconds) is given, a timer will be started and if no user input is detected during this period, the input dialog returns with the default values set. A value 0 will timeout immediately, a negative value will never timeout. The default is to use the global variable input_timeout.

The result() method can be used to find out how the dialog was ended. Its value will be one of ACCEPTED, REJECTED ot TIMEOUT.

class widgets.TableModel(data, chead=None, rhead=None, parent=None, *args)

A table model that represent data as a two-dimensional array of items.

data is any tabular data organized in a fixed number of rows and colums. This means that an item at row i and column j can be addressed as data[i][j]. Optional lists of column and row headers can be specified.

TableModel objects have the following methods:

rowCount(parent=None)
columnCount(parent=None)
data(index, role)
headerData(col, orientation, role)
insertRows(row=None, count=None)
removeRows(row=None, count=None)
class widgets.Table(data, chead=None, rhead=None, caption=None, parent=None, actions=[, ('OK', )], default='OK')

A dialog widget to show two-dimensional arrays of items.

Create the Table dialog.

data is a 2-D array of items, mith nrow rows and ncol columns. chead is an optional list of ncol column headers. rhead is an optional list of nrow row headers.

Table objects have the following methods:

class widgets.TableDialog(items, caption=None, parent=None, tab=False)

A dialog widget to show two-dimensional arrays of items.

Create the Table dialog.

If tab = False, a dialog with one table is created and items should be a list [table_header,table_data]. If tab = True, a dialog with multiple pages is created and items should be a list of pages [page_header,table_header,table_data].

TableDialog objects have the following methods:

class widgets.MessageBox(text, format='', level='info', actions=[, 'OK'], default=None, timeout=None)

A message box is a widget displaying a short text for the user.

The message box displays a text, an optional icon depending on the level and a number of push buttons.

  • text: the text to be shown. This can be either plain text or html or reStructuredText.
  • format: the text format: either ‘plain’, ‘html’ or ‘rst’. Any other value will try automatic recognition. Recognition of plain text and html is automatic. A text is autorecognized to be reStructuredText if its first line starts with ‘..’ and is followed by a blank line.
  • level: defines the icon that will be shown together with the text. If one of ‘question’, ‘info’, ‘warning’ or ‘error’, a matching icon will be shown to hint the user about the type of message. Any other value will suppress the icon.
  • actions: a list of strings. For each string a pushbutton will be created which can be used to exit the dialog and remove the message. By default there is a single button labeled ‘OK’.

When the MessageBox is displayed with the getResult() method, a modal dialog is created, i.e. the user will have to click a button or hit the ESC key before he can continue.

If you want a modeless dialog, allowing the user to continue while the message stays open, use the show() mehod to display it.

MessageBox objects have the following methods:

updateText(text, format='')

Set the text of the MessageBox.

This allows to update the text of an existing MessageBox widget.

getResult()

Display the message box and wait for user to click a button.

This will show the message box as a modal dialog, so that the user has to click a button (or hit the ESC key) before he can continue. Returns the text of the button that was clicked or an empty string if ESC was hit.

class widgets.TextBox(text, format=None, actions=[, 'OK'])

Display a text and wait for user response.

Possible choices are ‘OK’ and ‘CANCEL’. The function returns True if the OK button was clicked or ‘ENTER’ was pressed, False if the ‘CANCEL’ button was pressed or ESC was pressed.

TextBox objects have the following methods:

updateText(text, format='')

Set the text of the TextBox.

This allows to update the text of an existing TextBox widget.

getResult()
class widgets.ButtonBox(name, choices, funcs, *args)

ButtonBox objects have the following methods:

setText(text, index=0)
setIcon(icon, index=0)
class widgets.ComboBox(name, choices, func, *args)

ComboBox objects have the following methods:

setIndex(i)
class widgets.BaseMenu(title='AMenu', parent=None, before=None, items=None)

A general menu class.

This class is not intended for direct use, but through subclasses. Subclasses should implement at least the following methods:

  • addSeparator()
  • insertSeperator(before)
  • addAction(text,action)
  • insertAction(before,text,action)
  • addMenu(text,menu)
  • insertMenu(before,text,menu)

QtGui.Menu and QtGui.MenuBar provide these methods.

Create a menu.

This is a hierarchical menu that keeps a list of its item names and actions.

BaseMenu objects have the following methods:

item(text)

Get the menu item with given normalized text.

Text normalization removes all ‘&’ characters and converts to lower case.

itemAction(item)

Return the action corresponding to item.

item is either one of the menu’s item texts, or one of its values. This method guarantees that the return value is either the corresponding Action, or None.

insert_sep(before=None)
Create and insert a separator
insert_menu(menu, before=None)
Insert an existing menu.
insert_action(action, before=None)
Insert an action.
create_insert_action(str, val, before=None)
Create and insert an action.
insertItems(items, before=None)

Insert a list of items in the menu.

Each item is a tuple of two to five elements: Text, Action, [ Icon, ShortCut, ToolTip ].

Item text is the text that will be displayed in the menu. It will be stored in a normalized way: all lower case and with ‘&’ removed.

Action can be any of the following:

  • a Python function or instance method : it will be called when the item is selected,
  • a string with the name of a function/method,
  • a list of Menu Items: a popup Menu will be created that will appear when the item is selected,
  • None : this will create a separator item with no action.

Icon is the name of one of the icons in the installed icondir. ShortCut is an optional key combination to select the item. Tooltip is a popup help string.

If before is given, it specifies the text OR the action of one of the items in the menu: the new items will be inserted before that one.

class widgets.Menu(title='UserMenu', parent=None, before=None, items=None)

A popup/pulldown menu.

Create a popup/pulldown menu.

If parent==None, the menu is a standalone popup menu. If parent is given, the menu will be inserted in the parent menu. If parent==GD.GUI, the menu is inserted in the main menu bar.

If insert == True, the menu will be inserted in the main menubar before the item specified by before. If before is None or not the normalized text of an item of the main menu, the new menu will be inserted at the end. Calling the close() function of an inserted menu will remove it from the main menu.

If insert == False, the created menu will be an independent dialog and the user will have to process it explicitely.

Menu objects have the following methods:

process()
remove()
Remove this menu from its parent.
class widgets.MenuBar(title='TopMenuBar')

A menu bar allowing easy menu creation.

Create the menubar.

MenuBar objects have the following methods:

class widgets.DAction(name, icon=None, data=None, signal=None)

A DAction is a QAction that emits a signal with a string parameter.

When triggered, this action sends a signal (default ‘Clicked’) with a custom string as parameter. The connected slot can then act depending on this parameter.

Create a new DAction with name, icon and string data.

If the DAction is used in a menu, a name is sufficient. For use in a toolbar, you will probably want to specify an icon. When the action is triggered, the data is sent as a parameter to the SLOT function connected with the ‘Clicked’ signal. If no data is specified, the name is used as data.

See the views.py module for an example.

DAction objects have the following methods:

activated()
class widgets.ActionList(actions=[], function=None, menu=None, toolbar=None, icons=None)

Menu and toolbar with named actions.

An action list is a list of strings, each connected to some action. The actions can be presented in a menu and/or a toolbar. On activating one of the menu or toolbar buttons, a given signal is emitted with the button string as parameter. A fixed function can be connected to this signal to act dependent on the string value.

Create an new action list, empty by default.

A list of strings can be passed to initialize the actions. If a menu and/or toolbar are passed, a button is added to them for each string in the action list. If a function is passed, it will be called with the string as parameter when the item is triggered.

If no icon names are specified, they are taken equal to the action names. Icons will be taken from the installed icon directory. If you want to specify other icons, use the add() method.

ActionList objects have the following methods:

add(name, icon=None)

Add a new name to the actions list and create a matching DAction.

If the actions list has an associated menu or toolbar, a matching button will be inserted in each of these. If an icon is specified, it will be used on the menu and toolbar. The icon is either a filename or a QIcon object.

names()
Return an ordered list of names of the action items.

Functions defined in the module widgets

widgets.setInputTimeout(timeout)
widgets.addTimeOut(widget, timeout=None, timeoutfunc=None)

Add a timeout to a widget.

  • timeoutfunc is a callable. If None it will be set to the widget’s timeout method if one exists.
  • timeout is a float value. If None, it will be set to to the global input_timeout.

If timeout is positive, a timer will be installed into the widget which will call the timeoutfunc after timeout seconds have elapsed. The timeoutfunc can be any callable, but usually will emit a signal to make the widget accept or reject the input. The timeoutfunc will not be called is if the widget is destructed before the timer has finished.

widgets.selectFont()

Ask the user to select a font.

A font selection dialog widget is displayed and the user is requested to select a font. Returns a font if the user exited the dialog with the OK button. Returns None if the user clicked CANCEL.

widgets.getColor(col=None, caption=None)

Create a color selection dialog and return the selected color.

col is the initial selection. If a valid color is selected, its string name is returned, usually as a hex #RRGGBB string. If the dialog is canceled, None is returned.

widgets.inputAny(name, value, itemtype=str)

Create an InputItem of any type, depending on the arguments.

Arguments: only name and value are required

  • name: name of the item, also the key for the return value
  • value: initial value,
  • itemtype: one of the available itemtypes, default derived from value or str if value is not recognized.
  • text: descriptive text displayed on the input dialog, default equal to name
  • choices: a list of posible values (for selection types)
  • min,max: limits for range types
  • validator: customized validation function
widgets.inputAnyOld(item, parent=None)

Create an InputItem with the old data style.

This translates the data from the legacy InputItem data to the new style required by InputAny. Returns the InputItem constrctured with the data.

widgets.updateDialogItems(data, newdata)

Update the input data fields with new data values

data: a list of dialog items, as required by an InputDialog. newdata: a dictionary with new values for (some of) the items. The values in data which have a matching key in newdata will be replaced with the new value, unless it is None.

This function requires that the dialog items are lists, not tuples.

widgets.dialogButtons(dialog, actions, default=None)

Create a set of dialog buttons

dia is a dialog widget actions is a list of tuples (name,) or (name,function). If a function is specified, it will be executed on pressing the button. If no function is specified, and name is one of ‘ok’ or ‘cancel’ (case does not matter), the button will be bound to the dialog’s ‘accept’ or ‘reject’ slot. default is the name of the action to set as the default.

widgets.normalize(s)

Normalize a string.

Text normalization removes all ‘&’ characters and converts to lower case.

Documentation

Previous topic

11. elements — Element local coordinates and numbering.

Next topic

13. colorscale — Color mapping of a range of values.

This Page