W Widget Reference


W Widgets
Using W Widgets / W Widget Reference
Arguments / Bindings / Abstract Widgets / Concrete Widgets / Menus

This section documents the most important classes and methods of the W Widget modules. (XXX except that it's incomplete - the main widget parts are done, though)

This is not meant to be comprehensive, rather it's meant to explain the parts that you are most likely to use. If you are hacking deeply you will need to look at the source.

Standard Arguments for Widgets

There are a number of arguments that most widgets take that are worth their own descriptions:

possize
This is either:
  1. a tuple (l, t, r, b):
    • l determines the location of the left edge of the widget: if it is non-negative it is the distance from the left edge of its parent widget in pixels; if it is negative it is the distance from the right edge of its parent widget.
    • t determines the location of the top edge of the widget: if it is non-negative it is the distance from the top edge of its parent widget in pixels; if it is negative it is the distance from the bottom edge of its parent widget.
    • r determines the location of the right edge of the widget: if it is positive, it is the width of the widget; if it is non-positive it is the distance from the right edge of the parent window.
    • b determines the location of the bottom edge of the widget: if it is positive, it is the height of the widget; if it is non-positive it is the distance from the bottom edge of the parent window.
    By carefully choosing these values you can get a variety of useful behaviour from a widget automatically.
  2. a function which takes the width and height of the parent widget as arguments and returns the bounding rectangle of the widget.
  3. in some cases (such as for the window classes and resize methods) a tuple (w, h) will be interpreted as the width and height, with the position automatically determined.
title
A string. On some widgets, such as windows and buttons, this string is displayed in the widget.
callback
A function. What this does, and when it is called, depend upon the type of widget; usually it will be called in response to the most significant event for a widget, such as when a button is clicked.
color, backgroundcolor
A tuple of three values giving the RGB specification of the color.
fontsettings
Either None, in which case the window's font is used, or a tuple (font, style, size, color). Font is the name of the font, style is a flag giving the style to be used for the text (these are listed at the start of the Quickdraw module), size is the font size in points, and color is a tuple as described above.

Bindings

[control][cmd][shift]char

The user has pressed a key, possibly modified by a control, command or shift key. char is the actual character which is typed after modifier keys have been applied; it's "shiftC", not "shiftc". Certain characters are translated to more friendly forms, such as return, which is called returnkey, the arrow keys, page up and page down. The complete listing is available in the Wkeys module.

The callback will be passed the actual character, and the original event record from the application's mainloop.

<key>

The user has pressed some key, possibly with modifiers.

The callback will be passed the actual character, and the original event record from the application's mainloop. If the callback returns 1, the application will not propogate the event any further. This can allow you to block or modify certain keystrokes.

<click>

The user has clicked in a widget.

The callback will be sent the point where the click occurred and any modifier keys which are down. If the callback returns 1, the application will not propogate the event any further.

<idle>

The application is idling. Widgets sent this event can do periodic things, like blinking a cursor.

The callback will not be sent any arguments. If the callback returns 1, the application will not propogate the event any further.

<select>

The widget has just been selected to be a window's active widget, or is being deslected.

If the callback is bound to the window, it will be sent the new active widget. If the callback is bound to a widget, it is sent 1 or 0, depending on whether the widget is being selected or deselected. If the callback returns 1, all further processing will be blocked, so a widget can refuse to take the selection, or the window can block active widget changes.

Abstract Widget Classes

Widget / ClickableWidget / SelectableWidget / ControlWidget

Abstract widget classes are designed to be subclassed, rather than directly instantiated. They provide useful common functionality.

Widget (possize)

Widget is the base class from which all W widgets are derived.

Widget provides the following methods:

show(onoff)
This shows or hides the Widget, depending on the value of onoff. It also will hide any subwidgets of the Widget.
getpossize()
Returns the current value of possize.
getbounds()
Returns the current bounding rectangle of the widget.
move(x [, y = None])
Shifts the left, top corner of the widget to x, y.
rmove(deltax [, deltay = None])
Shifts the left, top corner of the widget by deltax, deltay.
resize(possize)
Changes the possize of the widget to possize. possize can either be a tuple, or the corresponding entries of the tuple as arguments.
open()
This opens the widget.
bind(key, callback)
This binds a callback to a keystroke or abstract event. If callback is false, then the current binding is deleted.
forall(methodname [, *args])
forall_butself(methodname [, *args])
forall_frombottom(methodname [, *args])
These three methods apply methodname with the arguments *args to subwidgets recursuively. It first looks for a binding to the key '<methodname>', then for an actual method with the name methodname. forall calls forall for each subwidget, and applies methodname to itself (ie. it is a postorder traversal). forall_frombottom applies methodname to itself first, and then calls forall_frombottom for its subwidgets (ie. it is a preorder traversal). forall_butself calls forall for each if the subwidgets, but does not apply methodname to the current widget.
Widget also provides __setattr__, __delattr__, __setitem__, __getitem__ and __delitem__ methods to ease handling subwidgets. __setitem__, __getitem__ and __delitem__ directly affect the widget's subwidget dictionary; __setattr__ and __delattr__ divert Widget instances to the subwidget dictionary of the widget.

If you are subclassing Widget, you may want to override the methods:

click(point, modifiers)
This is called whenever a click occurs in the widget. If you need your widget to respond to clicks in some manner, you should use this.
draw([visRgn = None])
This is called whenever your widget needs to be drawn. visRgn is the region of the window which is visible, so you can test this to avoid unneeded drawing.
test(point)
This is called to see if a point lies in the widget. The standard behaviour is to return true if the point is in the widget's bounding rectangle. Widgets which have unusual shapes may wish to modify this.
close()
This is called when the widget is being destroyed. Make sure you delete any new instance variables you define which could contain circular references, so that Python can free the memory your widget uses.

There are some methods which do not exist in the base widget class, but if added will hook in with other parts of the W widgets:

rollover(onoff)
A widget's parent window will invoke a rollover method of a widget if the mouse moves in into or out of the widget at idle time. The parameter onoff is 1 if the pointer moves in, 0 if it moves out. (XXX actually, while the mouse is on the widget gets called repeatedly with onoff 0 and then 1 - be careful; based on source comments, this is not what is desired...)

ClickableWidget (possize)

ClickableWidget is a base class for widgets that respond to clicks.

ClickableWidget is a subclass of Widget. In addition it defines the following methods:

enable(onoff)
This enables or disables the ClickableWidget depending on the value of onoff. Disabled ClickableWidgets will not respond to clicks.
callback()
This wraps the callback that should be called when the widget is clicked.

SelectableWidget (possize)

SelectableWidget is a base class for widgets that can accept keyboard focus.

SelectableWidget is a subclass of Widget. In addition it defines the following methods:

select(onoff [, isclick = 0])
This selects or deselects the SelectableWidget for keyboard focus, depending on the value of onoff. If the widget was selected by a click from the mouse, isclick is true. If the widget has a callback bound to '<select>', it will be called by this method. The callback should return 1 if the widget should not be selected for some reason.
drawselframe(onoff)
This draws or erases, depending on the value of onoff, a focus rectangle about the widget. It is not automatically called, and will not be drawn if inappropriate for the parent window.

If you are deriving a class from SelectableWidget, you will most likely want to override the following method:

key(char, event)
This is called whenever the widget is selected and the user presses a key (presuming the event is not intercepted by the application, front window, or a binding to the key in the widget). Char is the actual character pressed, event is the event tuple originally returned by Evt.GetNextEvent. This method should be used for regular keystrokes; command keys are best dealt with by binding a callback to a command key event (to ignore or special-case command keys you can test for their presence by seeing if modifiers & Events.cmdKey is true).

ControlWidget (possize [, title = "Control", procID = 0, callback = None, value = 0, min = 0, max = 0])

ControlWidget is an abstract class which is used for wrapping stadard Macintosh controls, such as buttons and scroll bars.

procID is the Macintosh toolbox control ID, descriptive constants are available in the Control module. Value is the initial value of the control, min is the minimum value it can take, and max is the maximum value it can take. ControlWidget is a subclass of ClickableWidget and Widget, and inherits their methods. In addition, it has the following methods:

open()
This opens the widget and creates the underlying Macintosh control via a call to Ctl.NewControl.
enable(onoff)
This enables or disables the ControlWidget depending on the value of onoff. Disabled ControlWidgets will not respond to clicks.
activate(onoff)
This is called whenever the parent window becomes active or is deactivated. Onoff tells the widget which of these events has occurred.
settitle(title)
This sets the title of the ControlWidget to title. This may change the appearance of the widget.
gettitle()
This returns a string containing the current title of the ControlWidget.

It is conceivable that you may want to subclass ControlWidget if you want to create a new widget around some other Macintosh control (there are quite a few more which are now standard with System 8). If you do, you should be careful to call ControlWidget.__init__ with the appropriate ProcID, value, min and max in your subclass's __init__ method. Refer to Inside Macintosh for how these are used. You may need to override the following method as well:

click(point, modifiers)
This is called whenever a click occurs in the widget. The default behaviour is to call Ctl.TrackControl, and if it returns true to call the callback if it exists. If there are instance variables that you need to set to track your control's state, or if you have a complex control with multiple parts, you will need to override this method.

Concrete Widget Classes

Controls / Popup Menus / Static Graphics / Groups / Text / Windows

Concrete Widget classes are those which are designed to be created and used as-is.

Control Widget Classes

These are wrappers around various standard Macintosh controls.

Button (possize [, title = "", callback = None])

This creates a standard Macintosh push button.

Title is used for the text of the button, and will appear in the window font. Callback will be called whenever the button is enabled, and is clicked; it takes no arguments. Button is a subclass of ControlWidget, ClickableWidget and Widget. In addition to their methods, Button has the following methods:

push()
This simulates a user clicking on the button. This is ideal for binding command-keys to.

In each window, one button may be designated as the default, and has a thick border drawn around it. This is done thought the parent window's methods.

CheckBox (possize [, title = "Checkbox", callback = None, value = 0])

This creates a standard Macintosh check box.

Title is used for the text of the check box, and will appear in the window font. Callback will be called whenever the check box is enabled, and is clicked; it takes one argument, which is the state of the checkbox as returned by get(). Value is the initial state of the check box.

CheckBox is a subclass of ControlWidget, ClickableWidget and Widget. In addition to their methods, CheckBox has the following methods:

push()
This simulates a user clicking on the check box by toggling the state of the check box and calling the callback. If the check box is disabled, it does nothing. This is ideal for binding command-keys to.
toggle()
This flips the state of the check box, but does not call the callback.
set(value)
This sets the state of the check box to value (1 is checked, 0 is unchecked). It does not call the callback.
get()
The gets the state of the check box (1 is checked, 0 is unchecked).

RadioButton (possize, title, thebuttons [, callback = None, value = 0])

This creates a standard Macintosh radio button.

Title is used for the text of the radio button, and will appear in the window font. TheButtons is a list of radio buttons that are grouped together. Callback will be called whenever the radio button is enabled, and is clicked; it takes one argument, which is always 1 (but presumably, may be 0 in a future version of W). Value is the initial state of the radio button (make sure that at most one radio button in a group is selected at the start).

RadioButton is a subclass of ControlWidget, ClickableWidget and Widget. In addition to their methods, RadioButton has the following methods:

push()
This simulates a user clicking on the radio button by selecting it and calling the callback. If the check box is disabled, it does nothing. This is ideal for binding command-keys to.
set(value)
This selects the current radio button and deselects the current selection in the group. It does not call the callback. Value is a dummy variable.
get()
The gets the state of the radio button (1 is selected, 0 is not selected).

ScrollBar (possize [, callback = None, value = 0, min = 0, max = 0])

This creates a standard Macintosh scroll bar.

Callback will be called whenever the scroll bar is enabled, and is clicked; it takes one argument, which either the current value of the scroll bar if the user moved the thumb of the scroll bar, or one of '+', '-', '++' or '--' if the user clicked on the up, down, page up and page down parts of the scroll bar, respectively. Value is the initial position of the scroll bar. min is the minimum value that the scroll bar can take, and max is the maximum value.

ScrollBar is a subclass of ControlWidget, ClickableWidget and Widget. In addition to their methods, ScrollBar has the following methods:

up()
Simulates a user clicking on the up button of the scrollbar by calling the callback with '+'. Ideal for binding keystrokes to.
down()
Simulates a user clicking on the down button of the scrollbar by calling the callback with '-'. Ideal for binding keystrokes to.
pageup()
Simulates a user clicking on the page up region of the scrollbar by calling the callback with '++'. Ideal for binding keystrokes to.
pagedown()
Simulates a user clicking on the page down region of the scrollbar by calling the callback with '--'. Ideal for binding keystrokes to.
set(value)
(XXX two different set methods, the one to call the callback is overridden) This sets the value of the scroll bar to value and moves the position of the thumb accordingly. It does not call the callback.
get()
The gets the current value of the scrollbar.
setmin(value)
This sets the minimum value of the scroll bar to value and moves the position of the thumb accordingly.
getmin()
The gets the current minimum value of the scrollbar.
setmax(value)
This sets the maximum value of the scroll bar to value and moves the position of the thumb accordingly.
getmax()
The gets the current maximum value of the scrollbar.

List (possize [, items = None, callback = None, flags = 0, cols = 1, typingcasesens = 0])

This creates a standard Macintosh list box.

Items is the intial set of entries to appear in the list box - the list items can be any Python object and the corresponding entry in the list box will be the first 255 characters of their str() representation. Callback will be called whenever the list box is enabled and is clicked; it takes one argument, which is 1 if the user double-clicked on the list box. Flags are the selection flags (see the List module: the flag constants are lOnlyOne through lNoNilHilite). Cols is the number of columns the list box has (XXX at present, only 1 column or all the item manipulation commands won't work, there is an experimental MultiList subclass which copes with multiple coulmns). Typingcasesens is 0 if you want keystrokes to match items irrespective of case, and 1 if you need the case to be taken into consideration.

ListBox is a subclass of SelectableWidget and Widget. In addition to their methods, ScrollBar has the following methods:

set(items)
This takes a list items and sets the items of the List box to the items in the python list.
get()
This returns a python list of the current items in the list box.
setselection(selection)
This takes a list of indices of items which are to be selected and selects them.
getselection()
This returns a list of the indices of the items which are currently selected.
setselectedobjects(objects)
This takes a list of objects that are list items and sets the current selection to those objects.
getselectedobjects()
This returns a list of objects which are presently selected.
ListBox also has __getitem__,__setitem__, __delitem__, __getslice__, __selslice__, __len__, append, remove, index and insert methods, so it can be used as a mutable list object in a natural way.

To create a list box with a different LDEF than the standard, you can override the LDEF_ID class variable in your List instance before calling open() to create the list widget. TwoLineList is a subclass of List the uses a variant LDEF which displays 2 lines in each cell; this is the sort of list which appears in IDE tracebacks.

Movie (possize)

Creates a quicktime movie widget. (XXX this looks experimental - shouldn't the movie be able to be passed in as an argument?)

Movie is a subclass of Widget. It defines the following methods:

set(file [, start = 0])
Loads the movie from the pathname or fss passed to file and optionally starts the movie, depending on the value of start.
get()
Returns the current quicktime movie object in the widget.
getmovietitle()
Returns the title of the movie.
start()
Starts the current movie playing.
stop()
Stops the current movie if it is playing.
rewind()
Rewinds the current movie to the beginning.

Popup Menu Widget Classes

These are various sorts of popup menus.

PopupWidget (possize [, items = [], callback = None])

Creates a small popup menu button. The menu is dynamically created when the widget is clicked. Should be 16 pixels wide and 16 pixels high.

Callback is called for any menu items which do not have their own callback associated to them; the object selected is passed as an argument to the callback. Items is the list of menu items to display; the items in this list must be one of:

PopupWidget is a subclass of ClickableWidget. It defines the additional methods:

set(items)
This takes a list items and sets the menu items to the items in the list as described above.
get()
This returns a list of the current menu items.
(XXX Would be nice if it was a UserList as well.)

PopupMenu (possize [, items = [], callback = None])

Creates a small popup menu button. The menu is prebuilt, so this widget is best for menus with static content. Should be 16 pixels wide and 16 pixels high.

PopupMenu is a subclass of PopupWidget, and has the same interface.

FontMenu (possize, callback)

Creates a small font popup menu button. Should be 16 pixels wide and 16 pixels high.

Callback is called when a selection is made from the menu; the name of the font selected is passed as an argument.

FontMenu is a subclass of PopupMenu, and has the same interface, except that trying to use the set() method will raise an exception.

Static Graphic Classes

These are widgets which implement simple graphic elements.

HorizontalLine (possize [, thickness = 1])

A horizontal line.

The line is drawn at the top edge of the rectangle specified by possize, and is thickness pixels thick.

VerticalLine (possize [, thickness = 1])

A vertical line.

The line is drawn at the left edge of the rectangle specified by possize, and is thickness pixels thick.

Horizontal and vertical lines are both subclasses of Widget. They have no additional methods.

Frame (possize [, pattern = Qd.qd.black, color = (0, 0, 0) ])

A rectangular box.

The box is drawn with a pen which has pattern pattern and color color.

Frame is a subclass of Widget and has two additional methods:

setcolor(color)
Sets the pen colour to color and redraws the frame
setpattern(pattern)
Sets the pen pattern to pattern and redraws the frame.

BevelBox (possize [, color = (0xe000, 0xe000, 0xe000) ])

A box with a bevelled appearance.

The box is filled with the color color (specified as RGB), with highlights around the edges to match the Apple 'Platinum' appearance.

BevelBox is a subclass of Widget and has one additional method:

setcolor(color)
Sets the pen colour to color (specified as RGB) and redraws the frame

Grouping Classes

These widgets group together other widgets.

Group (possize)

This creates a widget which groups together its subwidgets as a unit.

Group is a subwidget of Widget. It provides no additional methods.

HorizontalPanes (possize [, panesizes = None, gutter = 8 ])
VerticalPanes (possize [, panesizes = None, gutter = 8 ])

Creates a group of widgets in a horizontal row or vertical column. The space available to each widget can be resized by dragging the dividers between them.

Panesizes is a list of the proportional widths of the panes, and it should sum to 1, if it is None then the panes will be evenly spaced (XXX except you get a division by 0 error, because the widths are set up during __init__, and at that stage there are no subwidgets). Gutter is the width of the strip between each pane.

VerticalPane and HorizontalPane are subclasses of Widget, but do not define any additional methods which should be used publically.

Text Widget Classes

All of these are wrappers around a WASTE text editor.

TextBox (possize [, text = "", align = TextEdit.teJustLeft, fontsettings = None, backgroundcolor = (0xffff, 0xffff, 0xffff) ])

Creates a static text widget.

Text is the text to be displayed, with alignment align.

TextBox is a subclass of Widget and has two additional methods:

set(text)
This sets the text of the widget to the string text.
get()
This returns the text of the TextBox.

EditText (possize [, text = "", callback = None, inset = (3, 3), fontsettings = None, tabsettings = (32, 0), readonly = 0 ])

Creates an editable text widget intended for simple entry fields. If there are subwidgets of its parent widget called _barx and _bary, then these will be used as scrollbars for the window.

Callback will be called whenever the texts is changed; it takes no arguments. Inset is a tuple (h, v) which determines the margins between the boundary of the widget and the actual text it contains, h being the horizontal inset at the left and right sides, v being the vertical inset at the top and bottom. Tabsettings is a tuple (size, mode) which determines the spacing allocated to tab chatacters, if mode is true then size is the number of characters between tab-stops, otherwise it is the number of pixels. Readonly is true if the text widget is static, and false if it is editable.

EditText is a subclass of SelectableWidget and Widget, and inherits their methods. It also defines the following methods:

set(text)
This sets the text of the widget to the string text.
get()
This returns the text of the TextBox.
gettabsettings
settabsettings
getfontsettings
setfontsettings
getselection
setselection
selview
selectall
selectline
offsettoline
countlines
expandselection
insert
can_undo

EditText provides callbacks for Cut, Copy, Paste, Clear, Undo/Redo and Select All menu items.

TextEditor (possize [, text = "", callback = None, wrap = 1, inset = (4, 4), fontsettings = None, tabsettings = (32, 0), readonly = 0 ])

Creates a text editor widget intended for editing substantial quantities of text.

The arguments are the same as those for EditText except for wrap which determines if lines of text will be wrapped by the widget.

TextEditor is a subclass of EditText, SelectableWidget and Widget, and inherits their methods. It does not define any public methods of its own.

PyEditor (possize [, text = "", callback = None, inset = (4, 4), fontsettings = None, tabsettings = (32, 0), readonly = 0, debugger = None, file = ''])

Creates a specialised Python source code edit widget with debugger hooks.

Arguments are the same as TextEditor, except for debugger, which specifies a debugger to use when running the code, and file, which is the file containing the source code for the debugger's reference.

Additional methods are

set
setfile
getfile
showbreakpoints
togglebreakpoints
clearbreakpoints
editbreakpoints

PyEditor defines additional callbacks for Shift Left, Shift Right, Comment and Uncomment menu items.

Window Classes

Window (possize [, title = "", minsize = None, maxsize = None, tabable = 1, show = 1, fontsettings = None])

Creates a standard document window.

Title is the text which appears at the top of the window. Minsize and maxsize are the minimum and maximum sizes that a window can be set to. If tabable is true then pressing the "Tab" key will cycle through the selectable widgets of the window; "Shift-Tab" will cycle in the reverse order. If show is true, then the window will be visible when it is created.

Window is a subwidget of SelectableWidget and Widget; it is also a subwidget of the FrameWork.Window class. The following methods are also defined:

settitle(title)
This sets the title of the window to title.
gettitle()
This returns a string containing the current title of the window.
getcurrentwidget()
This returns the widget which is currently selected for keyboard focus, if any.
setdefaultbutton([button = None, *keys])
Sets the default button of the window to button, or removes the default button if the argument is false. Button must be an instance of the Button class. Button's push() method is bound to "return", "enter", and any othery keys provided by the *keys parameters.
In addition, the Window widget provides a handler for the "Close" menu item.

In any significant application, you will probably want to override the __init__ method to provide specialised set up (you can call Window.__init__ to do the normal set up, though), and close to check if the document has been saved and query the user. You will also want to provide domenu_menuitem handlers for document-level operations. Document window classes are also appropriate places to add commands which operate on the document if the data is stored internally.

Dialog (possize [, title = ""])

Creates a standard modeless dialog box. This is for dialog boxes which are too complex for the EasyDialogs module.

Title is the title of the dialog box.

Dialog disables the "Close" menu item (so it must be explicitly closed by calling the close() method), but is otherwise the same as Window, which it is a subclass of.

Dialog is really just a regular window with a modeless dialog frame; it doesn't use any of the Dialog Manager routines, and the items for user-defined dialogs should be built from scratch rather than from a 'DLOG' resource. For these sorts of dialogs, use FrameWork.Dialog.

ModalDialog (possize [, title = ""])

Creates a modal dialog box (a dialog which the user must deal with before proceeding with normal processing).

The arguments are the same as for the Dialog class. If title is empty, a fixed dialog box window is used, otherwise a movable dialog window is created. ModalDialog is a subclass of Dialog.

Like Dialog, ModalDialog is a regular window with a dialog frame. Modal behaviour is achieved by using its own event loop.

Menubar and Menu Classes

The menu classes are essentially the same as the classes in the FrameWork module, which in turn are wrappers around the objects in the Menu toolbox module.

MenuBar and Menu are found in the Wapplication module, MenuItem in the FrameWork module.

Beware of potential name conflicts between the Menu module and the Menu class.

MenuBar()

A menubar.

You generally do not need to create this; the default behaviour of your application is to create one during initialisation, together with an Apple Menu, and make it available via the menubar instance variable of the application.

The methods defined by MenuBar are not public: unless you need to subclass MenuBar or Menu all you need to is to keep track of the application's menubar instance.

Menu(self, menubar, title [, where = 0])

Creates a standard Macintosh menu and inserts it into a menubar.

The menu has title title and is inserted into the MenuBar menubar. The where parameter determines where the menu is inserted in the menubar; if it is 0, it is at the end, if it is -1 it is not displayed, but is held to be used as a submenu or popup menu.

MenuItem(menu, title, [shortcut = None, callback = None])
RadioItem(menu, title, [shortcut = None, callback = None])
CheckItem(menu, title, [shortcut = None, callback = None])

Creates an item in a menu, and inserts it into the menu. (XXX RadioItems and CheckItems don't work).

Menu items must either be passed a callable callback, or one of the application, the frontmost window or the selected widget in the current window must have a 'domenu_callback' method; if not, the menu item will be dimmed. If there is a menu item whose value or applicability should depend upon the current state of the application or document, there should be a 'can_callback' method; if this method returns false the menu item will be dimmed,if it returns true it will be active. The 'can_callback' is responsible for changing the menu item's text if that is required.

Application Class

Utility Functions