As of version 1.9.1, a number of syntax additions were made to place the
wxRuby API style more in line with Ruby rather than C++ conventions. As
these apply globally to a large number of classes, they are not
currently listed as alternatives in the individual class reference
documentation, but instead are described here.
Classes that inherit from Window – covering all GUI
widgets and frames – typically have quite long lists of parameters
passed to their new
method. As well as class-specific arguments, they
usually have parameters for window id, size, position and style. This
means calls to new
can end looking unwieldy.
For example, to create a multiline “TextCtrl”, the TE_MULTILINE
style
must be passed. If default positioning and default sizing is
desired (as is usually the case when using Sizers to manage
layouts), the call ends up looking like this:
As of version 1.9.1, it is possible to use named keyword arguments to
specify constructor parameters in arbitrary order. The names of the
arguments can be got from the class documentation. Omitted arguments
will be given their default value. The above call could look like
Which is both less typing, and easier to read.
In the wxWidgets API, methods for getting and setting properties of
instances are named according to the convention commonest in C++ and
Java. For example, to get and set the size of a widget, the methods are
named:
In Ruby, much the commoner convention is to have accessor methods named
simply after the property. Therefore, in wxRuby, the following are valid
alternatives to the above:
Note that in Ruby, if you are calling a setter argument within an
instance’s method, you must explicitly specify self
as the
receiver. Without this, Ruby will interpret the call as an assignment to
a local variable rather than a method call:
The correct way:
self.size = new_sizeSimilar to the getters and setters, there are numerous methods in the
C++ API which test a condition, such as
Bitmap#is_ok. Ruby enables such methods which
return true or false to have a name ending with the “?”
character. In wxRuby, therefore, both the following are permitted
Or
Point and Size are simple Wx classes which
represent an x/y position and a width/height size respectively. They are
widely used in the API, including in widget constructors. For example,
to create a button at a specific position:
As a terser alternative, Point and Size arguments may be specified using
a two-element Ruby array, specifying an x/y co-ordinate or a
width/height size. The above could be re-written:
Or, neater, using keyword arguments:
button = Wx::Button.new( parent, :label => ‘press me’, :pos => [50, 50])These can be used in any method accepting a size argument:
Or a point argument
[This page automatically generated from the Textile source at 2023-06-09 00:45:33 +0000]