1 #----------------------------------------------------------------------------
2 # Name: wxPython.lib.maskednumctrl.py
5 # Copyright: (c) 2003 by Will Sadkin
7 # License: wxWindows license
8 #----------------------------------------------------------------------------
10 # This was written to provide a numeric edit control for wxPython that
11 # does things like right-insert (like a calculator), and does grouping, etc.
12 # (ie. the features of wxMaskedTextCtrl), but allows Get/Set of numeric
13 # values, rather than text.
15 # wxMaskedNumCtrl permits integer, and floating point values to be set
16 # retrieved or set via .GetValue() and .SetValue() (type chosen based on
17 # fraction width, and provides an EVT_MASKEDNUM() event function for trapping
18 # changes to the control.
20 # It supports negative numbers as well as the naturals, and has the option
21 # of not permitting leading zeros or an empty control; if an empty value is
22 # not allowed, attempting to delete the contents of the control will result
23 # in a (selected) value of zero, thus preserving a legitimate numeric value.
24 # Similarly, replacing the contents of the control with '-' will result in
25 # a selected (absolute) value of -1.
27 # wxMaskedNumCtrl also supports range limits, with the option of either
28 # enforcing them or simply coloring the text of the control if the limits
31 # wxMaskedNumCtrl is intended to support fixed-point numeric entry, and
32 # is derived from wxMaskedTextCtrl. As such, it supports a limited range
33 # of values to comply with a fixed-width entry mask.
34 #----------------------------------------------------------------------------
35 # 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
37 # o Updated for wx namespace
42 <B>wxMaskedNumCtrl:</B>
44 <LI>allows you to get and set integer or floating point numbers as value,</LI>
45 <LI>provides bounds support and optional value limiting,</LI>
46 <LI>has the right-insert input style that wxMaskedTextCtrl supports,</LI>
47 <LI>provides optional automatic grouping, sign control and format, grouping and decimal
48 character selection, etc. etc.</LI>
51 Being derived from wxMaskedTextCtrl, the control only allows
52 fixed-point notation. That is, it has a fixed (though reconfigurable)
53 maximum width for the integer portion and optional fixed width
58 <B>wxMaskedNumCtrl</B>(
61 pos = wxDefaultPosition,
64 validator = wxDefaultValidator,
65 name = "maskednumber",
66 <B>integerWidth</B> = 10,
67 <B>fractionWidth</B> = 0,
68 <B>allowNone</B> = False,
69 <B>allowNegative</B> = True,
70 <B>useParensForNegatives</B> = False,
71 <B>groupDigits</B> = False,
72 <B>groupChar</B> = ',',
73 <B>decimalChar</B> = '.',
76 <B>limited</B> = False,
77 <B>selectOnEntry</b> = True,
78 <B>foregroundColour</B> = "Black",
79 <B>signedForegroundColour</B> = "Red",
80 <B>emptyBackgroundColour</B> = "White",
81 <B>validBackgroundColour</B> = "White",
82 <B>invalidBackgroundColour</B> = "Yellow",
87 <DD>If no initial value is set, the default will be zero, or
88 the minimum value, if specified. If an illegal string is specified,
89 a ValueError will result. (You can always later set the initial
90 value with SetValue() after instantiation of the control.)
92 <DL><B>integerWidth</B>
93 <DD>Indicates how many places to the right of any decimal point
94 should be allowed in the control. This will, perforce, limit
95 the size of the values that can be entered. This number need
96 not include space for grouping characters or the sign, if either
97 of these options are enabled, as the resulting underlying
98 mask is automatically by the control. The default of 10
99 will allow any 32 bit integer value. The minimum value
100 for integerWidth is 1.
102 <DL><B>fractionWidth</B>
103 <DD>Indicates how many decimal places to show for numeric value.
104 If default (0), then the control will display and return only
105 integer or long values.
108 <DD>Boolean indicating whether or not the control is allowed to be
109 empty, representing a value of None for the control.
111 <DT><B>allowNegative</B>
112 <DD>Boolean indicating whether or not control is allowed to hold
115 <DT><B>useParensForNegatives</B>
116 <DD>If true, this will cause negative numbers to be displayed with ()s
117 rather than -, (although '-' will still trigger a negative number.)
119 <DT><B>groupDigits</B>
120 <DD>Indicates whether or not grouping characters should be allowed and/or
121 inserted when leaving the control or the decimal character is entered.
124 <DD>What grouping character will be used if allowed. (By default ',')
126 <DT><B>decimalChar</B>
127 <DD>If fractionWidth is > 0, what character will be used to represent
128 the decimal point. (By default '.')
131 <DD>The minimum value that the control should allow. This can be also be
132 adjusted with SetMin(). If the control is not limited, any value
133 below this bound will result in a background colored with the current
134 invalidBackgroundColour. If the min specified will not fit into the
135 control, the min setting will be ignored.
138 <DD>The maximum value that the control should allow. This can be
139 adjusted with SetMax(). If the control is not limited, any value
140 above this bound will result in a background colored with the current
141 invalidBackgroundColour. If the max specified will not fit into the
142 control, the max setting will be ignored.
145 <DD>Boolean indicating whether the control prevents values from
146 exceeding the currently set minimum and maximum values (bounds).
147 If False and bounds are set, out-of-bounds values will
148 result in a background colored with the current invalidBackgroundColour.
150 <DT><B>selectOnEntry</B>
151 <DD>Boolean indicating whether or not the value in each field of the
152 control should be automatically selected (for replacement) when
153 that field is entered, either by cursor movement or tabbing.
154 This can be desirable when using these controls for rapid data entry.
156 <DT><B>foregroundColour</B>
157 <DD>Color value used for positive values of the control.
159 <DT><B>signedForegroundColour</B>
160 <DD>Color value used for negative values of the control.
162 <DT><B>emptyBackgroundColour</B>
163 <DD>What background color to use when the control is considered
164 "empty." (allow_none must be set to trigger this behavior.)
166 <DT><B>validBackgroundColour</B>
167 <DD>What background color to use when the control value is
170 <DT><B>invalidBackgroundColour</B>
171 <DD>Color value used for illegal values or values out-of-bounds of the
172 control when the bounds are set but the control is not limited.
176 <DT><B>EVT_MASKEDNUM(win, id, func)</B>
177 <DD>Respond to a wxEVT_COMMAND_MASKED_NUMBER_UPDATED event, generated when
178 the value changes. Notice that this event will always be sent when the
179 control's contents changes - whether this is due to user input or
180 comes from the program itself (for example, if SetValue() is called.)
183 <DT><B>SetValue(int|long|float|string)</B>
184 <DD>Sets the value of the control to the value specified, if
185 possible. The resulting actual value of the control may be
186 altered to conform to the format of the control, changed
187 to conform with the bounds set on the control if limited,
188 or colored if not limited but the value is out-of-bounds.
189 A ValueError exception will be raised if an invalid value
192 <DT><B>GetValue()</B>
193 <DD>Retrieves the numeric value from the control. The value
194 retrieved will be either be returned as a long if the
195 fractionWidth is 0, or a float otherwise.
198 <DT><B>SetParameters(**kwargs)</B>
199 <DD>Allows simultaneous setting of various attributes
200 of the control after construction. Keyword arguments
201 allowed are the same parameters as supported in the constructor.
204 <DT><B>SetIntegerWidth(value)</B>
205 <DD>Resets the width of the integer portion of the control. The
206 value must be >= 1, or an AttributeError exception will result.
207 This value should account for any grouping characters that might
208 be inserted (if grouping is enabled), but does not need to account
209 for the sign, as that is handled separately by the control.
210 <DT><B>GetIntegerWidth()</B>
211 <DD>Returns the current width of the integer portion of the control,
212 not including any reserved sign position.
215 <DT><B>SetFractionWidth(value)</B>
216 <DD>Resets the width of the fractional portion of the control. The
217 value must be >= 0, or an AttributeError exception will result. If
218 0, the current value of the control will be truncated to an integer
220 <DT><B>GetFractionWidth()</B>
221 <DD>Returns the current width of the fractional portion of the control.
224 <DT><B>SetMin(min=None)</B>
225 <DD>Resets the minimum value of the control. If a value of <I>None</I>
226 is provided, then the control will have no explicit minimum value.
227 If the value specified is greater than the current maximum value,
228 then the function returns False and the minimum will not change from
229 its current setting. On success, the function returns True.
231 If successful and the current value is lower than the new lower
232 bound, if the control is limited, the value will be automatically
233 adjusted to the new minimum value; if not limited, the value in the
234 control will be colored as invalid.
236 If min > the max value allowed by the width of the control,
237 the function will return False, and the min will not be set.
240 <DD>Gets the current lower bound value for the control.
241 It will return None if no lower bound is currently specified.
244 <DT><B>SetMax(max=None)</B>
245 <DD>Resets the maximum value of the control. If a value of <I>None</I>
246 is provided, then the control will have no explicit maximum value.
247 If the value specified is less than the current minimum value, then
248 the function returns False and the maximum will not change from its
249 current setting. On success, the function returns True.
251 If successful and the current value is greater than the new upper
252 bound, if the control is limited the value will be automatically
253 adjusted to this maximum value; if not limited, the value in the
254 control will be colored as invalid.
256 If max > the max value allowed by the width of the control,
257 the function will return False, and the max will not be set.
260 <DD>Gets the current upper bound value for the control.
261 It will return None if no upper bound is currently specified.
264 <DT><B>SetBounds(min=None,max=None)</B>
265 <DD>This function is a convenience function for setting the min and max
266 values at the same time. The function only applies the maximum bound
267 if setting the minimum bound is successful, and returns True
268 only if both operations succeed. <B><I>Note:</I></B> leaving out an argument
269 will remove the corresponding bound.
270 <DT><B>GetBounds()</B>
271 <DD>This function returns a two-tuple (min,max), indicating the
272 current bounds of the control. Each value can be None if
273 that bound is not set.
276 <DT><B>IsInBounds(value=None)</B>
277 <DD>Returns <I>True</I> if no value is specified and the current value
278 of the control falls within the current bounds. This function can also
279 be called with a value to see if that value would fall within the current
280 bounds of the given control.
283 <DT><B>SetLimited(bool)</B>
284 <DD>If called with a value of True, this function will cause the control
285 to limit the value to fall within the bounds currently specified.
286 If the control's value currently exceeds the bounds, it will then
287 be limited accordingly.
288 If called with a value of False, this function will disable value
289 limiting, but coloring of out-of-bounds values will still take
290 place if bounds have been set for the control.
291 <DT><B>GetLimited()</B>
292 <DT><B>IsLimited()</B>
293 <DD>Returns <I>True</I> if the control is currently limiting the
294 value to fall within the current bounds.
297 <DT><B>SetAllowNone(bool)</B>
298 <DD>If called with a value of True, this function will cause the control
299 to allow the value to be empty, representing a value of None.
300 If called with a value of False, this function will prevent the value
301 from being None. If the value of the control is currently None,
302 ie. the control is empty, then the value will be changed to that
303 of the lower bound of the control, or 0 if no lower bound is set.
304 <DT><B>GetAllowNone()</B>
305 <DT><B>IsNoneAllowed()</B>
306 <DD>Returns <I>True</I> if the control currently allows its
310 <DT><B>SetAllowNegative(bool)</B>
311 <DD>If called with a value of True, this function will cause the
312 control to allow the value to be negative (and reserve space for
313 displaying the sign. If called with a value of False, and the
314 value of the control is currently negative, the value of the
315 control will be converted to the absolute value, and then
316 limited appropriately based on the existing bounds of the control
318 <DT><B>GetAllowNegative()</B>
319 <DT><B>IsNegativeAllowed()</B>
320 <DD>Returns <I>True</I> if the control currently permits values
324 <DT><B>SetGroupDigits(bool)</B>
325 <DD>If called with a value of True, this will make the control
326 automatically add and manage grouping characters to the presented
327 value in integer portion of the control.
328 <DT><B>GetGroupDigits()</B>
329 <DT><B>IsGroupingAllowed()</B>
330 <DD>Returns <I>True</I> if the control is currently set to group digits.
333 <DT><B>SetGroupChar()</B>
334 <DD>Sets the grouping character for the integer portion of the
335 control. (The default grouping character this is ','.
336 <DT><B>GetGroupChar()</B>
337 <DD>Returns the current grouping character for the control.
340 <DT><B>SetSelectOnEntry()</B>
341 <DD>If called with a value of <I>True</I>, this will make the control
342 automatically select the contents of each field as it is entered
343 within the control. (The default is True.)
344 <DT><B>GetSelectOnEntry()</B>
345 <DD>Returns <I>True</I> if the control currently auto selects
346 the field values on entry.
359 from sys
import maxint
360 MAXINT
= maxint
# (constants should be in upper case)
363 from wx
.tools
.dbg
import Logger
364 from wx
.lib
.maskededit
import wxMaskedEditMixin
, wxMaskedTextCtrl
, Field
369 #----------------------------------------------------------------------------
371 wxEVT_COMMAND_MASKED_NUMBER_UPDATED
= wx
.NewEventType()
372 EVT_MASKEDNUM
= wx
.PyEventBinder(wxEVT_COMMAND_MASKED_NUMBER_UPDATED
, 1)
374 #----------------------------------------------------------------------------
376 class wxMaskedNumNumberUpdatedEvent(wx
.PyCommandEvent
):
377 def __init__(self
, id, value
= 0, object=None):
378 wx
.PyCommandEvent
.__init
__(self
, wxEVT_COMMAND_MASKED_NUMBER_UPDATED
, id)
381 self
.SetEventObject(object)
384 """Retrieve the value of the control at the time
385 this event was generated."""
389 #----------------------------------------------------------------------------
391 class wxMaskedNumCtrl(wxMaskedTextCtrl
):
393 valid_ctrl_params
= {
394 'integerWidth': 10, # by default allow all 32-bit integers
395 'fractionWidth': 0, # by default, use integers
396 'decimalChar': '.', # by default, use '.' for decimal point
397 'allowNegative': True, # by default, allow negative numbers
398 'useParensForNegatives': False, # by default, use '-' to indicate negatives
399 'groupDigits': True, # by default, don't insert grouping
400 'groupChar': ',', # by default, use ',' for grouping
401 'min': None, # by default, no bounds set
403 'limited': False, # by default, no limiting even if bounds set
404 'allowNone': False, # by default, don't allow empty value
405 'selectOnEntry': True, # by default, select the value of each field on entry
406 'foregroundColour': "Black",
407 'signedForegroundColour': "Red",
408 'emptyBackgroundColour': "White",
409 'validBackgroundColour': "White",
410 'invalidBackgroundColour': "Yellow",
411 'useFixedWidthFont': True, # by default, use a fixed-width font
416 self
, parent
, id=-1, value
= 0,
417 pos
= wx
.DefaultPosition
, size
= wx
.DefaultSize
,
418 style
= wx
.TE_PROCESS_TAB
, validator
= wx
.DefaultValidator
,
422 dbg('wxMaskedNumCtrl::__init__', indent
=1)
424 # Set defaults for control:
425 dbg('setting defaults:')
426 for key
, param_value
in wxMaskedNumCtrl
.valid_ctrl_params
.items():
427 # This is done this way to make setattr behave consistently with
428 # "private attribute" name mangling
429 setattr(self
, '_' + key
, copy
.copy(param_value
))
431 # Assign defaults for all attributes:
432 init_args
= copy
.deepcopy(wxMaskedNumCtrl
.valid_ctrl_params
)
433 dbg('kwargs:', kwargs
)
434 for key
, param_value
in kwargs
.items():
435 key
= key
.replace('Color', 'Colour')
436 if key
not in wxMaskedNumCtrl
.valid_ctrl_params
.keys():
437 raise AttributeError('invalid keyword argument "%s"' % key
)
439 init_args
[key
] = param_value
440 dbg('init_args:', indent
=1)
441 for key
, param_value
in init_args
.items():
442 dbg('%s:' % key
, param_value
)
445 # Process initial fields for the control, as part of construction:
446 if type(init_args
['integerWidth']) != types
.IntType
:
447 raise AttributeError('invalid integerWidth (%s) specified; expected integer' % repr(init_args
['integerWidth']))
448 elif init_args
['integerWidth'] < 1:
449 raise AttributeError('invalid integerWidth (%s) specified; must be > 0' % repr(init_args
['integerWidth']))
453 if init_args
.has_key('fractionWidth'):
454 if type(init_args
['fractionWidth']) != types
.IntType
:
455 raise AttributeError('invalid fractionWidth (%s) specified; expected integer' % repr(self
._fractionWidth
))
456 elif init_args
['fractionWidth'] < 0:
457 raise AttributeError('invalid fractionWidth (%s) specified; must be >= 0' % repr(init_args
['fractionWidth']))
458 self
._fractionWidth
= init_args
['fractionWidth']
460 if self
._fractionWidth
:
461 fracmask
= '.' + '#{%d}' % self
._fractionWidth
462 dbg('fracmask:', fracmask
)
463 fields
[1] = Field(defaultValue
='0'*self
._fractionWidth
)
467 self
._integerWidth
= init_args
['integerWidth']
468 if init_args
['groupDigits']:
469 self
._groupSpace
= (self
._integerWidth
- 1) / 3
472 intmask
= '#{%d}' % (self
._integerWidth
+ self
._groupSpace
)
473 if self
._fractionWidth
:
477 fields
[0] = Field(formatcodes
='r<>', emptyInvalid
=emptyInvalid
)
478 dbg('intmask:', intmask
)
480 # don't bother to reprocess these arguments:
481 del init_args
['integerWidth']
482 del init_args
['fractionWidth']
485 mask
= intmask
+fracmask
487 # initial value of state vars
490 self
._typedSign
= False
492 # Construct the base control:
493 wxMaskedTextCtrl
.__init
__(
494 self
, parent
, id, '',
495 pos
, size
, style
, validator
, name
,
499 validFunc
=self
.IsInBounds
,
500 setupEventHandling
= False)
502 self
.Bind(wx
.EVT_SET_FOCUS
, self
._OnFocus
) ## defeat automatic full selection
503 self
.Bind(wx
.EVT_KILL_FOCUS
, self
._OnKillFocus
) ## run internal validator
504 self
.Bind(wx
.EVT_LEFT_DCLICK
, self
._OnDoubleClick
) ## select field under cursor on dclick
505 self
.Bind(wx
.EVT_RIGHT_UP
, self
._OnContextMenu
) ## bring up an appropriate context menu
506 self
.Bind(wx
.EVT_KEY_DOWN
, self
._OnKeyDown
) ## capture control events not normally seen, eg ctrl-tab.
507 self
.Bind(wx
.EVT_CHAR
, self
._OnChar
) ## handle each keypress
508 self
.Bind(wx
.EVT_TEXT
, self
.OnTextChange
) ## color control appropriately & keep
509 ## track of previous value for undo
511 # Establish any additional parameters, with appropriate error checking
512 self
.SetParameters(**init_args
)
514 # Set the value requested (if possible)
515 ## wxCallAfter(self.SetValue, value)
518 # Ensure proper coloring:
520 dbg('finished wxMaskedNumCtrl::__init__', indent
=0)
523 def SetParameters(self
, **kwargs
):
525 This routine is used to initialize and reconfigure the control:
527 dbg('wxMaskedNumCtrl::SetParameters', indent
=1)
528 maskededit_kwargs
= {}
529 reset_fraction_width
= False
532 if( (kwargs
.has_key('integerWidth') and kwargs
['integerWidth'] != self
._integerWidth
)
533 or (kwargs
.has_key('fractionWidth') and kwargs
['fractionWidth'] != self
._fractionWidth
)
534 or (kwargs
.has_key('groupDigits') and kwargs
['groupDigits'] != self
._groupDigits
) ):
538 if kwargs
.has_key('fractionWidth'):
539 if type(kwargs
['fractionWidth']) != types
.IntType
:
540 raise AttributeError('invalid fractionWidth (%s) specified; expected integer' % repr(kwargs
['fractionWidth']))
541 elif kwargs
['fractionWidth'] < 0:
542 raise AttributeError('invalid fractionWidth (%s) specified; must be >= 0' % repr(kwargs
['fractionWidth']))
544 if self
._fractionWidth
!= kwargs
['fractionWidth']:
545 self
._fractionWidth
= kwargs
['fractionWidth']
547 if self
._fractionWidth
:
548 fracmask
= '.' + '#{%d}' % self
._fractionWidth
549 fields
[1] = Field(defaultValue
='0'*self
._fractionWidth
)
554 dbg('fracmask:', fracmask
)
556 if kwargs
.has_key('integerWidth'):
557 if type(kwargs
['integerWidth']) != types
.IntType
:
559 raise AttributeError('invalid integerWidth (%s) specified; expected integer' % repr(kwargs
['integerWidth']))
560 elif kwargs
['integerWidth'] < 0:
562 raise AttributeError('invalid integerWidth (%s) specified; must be > 0' % repr(kwargs
['integerWidth']))
564 self
._integerWidth
= kwargs
['integerWidth']
566 if kwargs
.has_key('groupDigits'):
567 self
._groupDigits
= kwargs
['groupDigits']
569 if self
._groupDigits
:
570 self
._groupSpace
= (self
._integerWidth
- 1) / 3
574 intmask
= '#{%d}' % (self
._integerWidth
+ self
._groupSpace
)
575 dbg('intmask:', intmask
)
576 fields
[0] = Field(formatcodes
='r<>', emptyInvalid
=emptyInvalid
)
577 maskededit_kwargs
['fields'] = fields
579 # don't bother to reprocess these arguments:
580 if kwargs
.has_key('integerWidth'):
581 del kwargs
['integerWidth']
582 if kwargs
.has_key('fractionWidth'):
583 del kwargs
['fractionWidth']
585 maskededit_kwargs
['mask'] = intmask
+fracmask
587 if kwargs
.has_key('groupChar'):
588 old_groupchar
= self
._groupChar
# save so we can reformat properly
589 dbg("old_groupchar: '%s'" % old_groupchar
)
590 maskededit_kwargs
['groupChar'] = kwargs
['groupChar']
591 if kwargs
.has_key('decimalChar'):
592 old_decimalchar
= self
._decimalChar
593 dbg("old_decimalchar: '%s'" % old_decimalchar
)
594 maskededit_kwargs
['decimalChar'] = kwargs
['decimalChar']
596 # for all other parameters, assign keyword args as appropriate:
597 for key
, param_value
in kwargs
.items():
598 key
= key
.replace('Color', 'Colour')
599 if key
not in wxMaskedNumCtrl
.valid_ctrl_params
.keys():
600 raise AttributeError('invalid keyword argument "%s"' % key
)
601 elif key
not in wxMaskedEditMixin
.valid_ctrl_params
.keys():
602 setattr(self
, '_' + key
, param_value
)
603 elif key
in ('mask', 'autoformat'): # disallow explicit setting of mask
604 raise AttributeError('invalid keyword argument "%s"' % key
)
606 maskededit_kwargs
[key
] = param_value
607 dbg('kwargs:', kwargs
)
609 # reprocess existing format codes to ensure proper resulting format:
610 formatcodes
= self
.GetFormatcodes()
611 if kwargs
.has_key('allowNegative'):
612 if kwargs
['allowNegative'] and '-' not in formatcodes
:
614 maskededit_kwargs
['formatcodes'] = formatcodes
615 elif not kwargs
['allowNegative'] and '-' in formatcodes
:
616 formatcodes
= formatcodes
.replace('-','')
617 maskededit_kwargs
['formatcodes'] = formatcodes
619 if kwargs
.has_key('groupDigits'):
620 if kwargs
['groupDigits'] and ',' not in formatcodes
:
622 maskededit_kwargs
['formatcodes'] = formatcodes
623 elif not kwargs
['groupDigits'] and ',' in formatcodes
:
624 formatcodes
= formatcodes
.replace(',','')
625 maskededit_kwargs
['formatcodes'] = formatcodes
627 if kwargs
.has_key('selectOnEntry'):
628 self
._selectOnEntry
= kwargs
['selectOnEntry']
629 dbg("kwargs['selectOnEntry']?", kwargs
['selectOnEntry'], "'S' in formatcodes?", 'S' in formatcodes
)
630 if kwargs
['selectOnEntry'] and 'S' not in formatcodes
:
632 maskededit_kwargs
['formatcodes'] = formatcodes
633 elif not kwargs
['selectOnEntry'] and 'S' in formatcodes
:
634 formatcodes
= formatcodes
.replace('S','')
635 maskededit_kwargs
['formatcodes'] = formatcodes
637 if 'r' in formatcodes
and self
._fractionWidth
:
638 # top-level mask should only be right insert if no fractional
639 # part will be shown; ie. if reconfiguring control, remove
640 # previous "global" setting.
641 formatcodes
= formatcodes
.replace('r', '')
642 maskededit_kwargs
['formatcodes'] = formatcodes
644 if kwargs
.has_key('limited'):
645 if kwargs
['limited'] and not self
._limited
:
646 maskededit_kwargs
['validRequired'] = True
647 elif not kwargs
['limited'] and self
._limited
:
648 maskededit_kwargs
['validRequired'] = False
649 self
._limited
= kwargs
['limited']
651 dbg('maskededit_kwargs:', maskededit_kwargs
)
652 if maskededit_kwargs
.keys():
653 self
.SetCtrlParameters(**maskededit_kwargs
)
655 # Record end of integer and place cursor there:
656 integerEnd
= self
._fields
[0]._extent
[1]
657 self
.SetInsertionPoint(integerEnd
)
658 self
.SetSelection(integerEnd
, integerEnd
)
660 # Go ensure all the format codes necessary are present:
661 orig_intformat
= intformat
= self
.GetFieldParameter(0, 'formatcodes')
662 if 'r' not in intformat
:
664 if '>' not in intformat
:
666 if intformat
!= orig_intformat
:
667 if self
._fractionWidth
:
668 self
.SetFieldParameters(0, formatcodes
=intformat
)
670 self
.SetCtrlParameters(formatcodes
=intformat
)
672 # Set min and max as appropriate:
673 if kwargs
.has_key('min'):
675 if( self
._max
is None
677 or (self
._max
is not None and self
._max
>= min) ):
681 textmin
= self
._toGUI
(min, apply_limits
= False)
683 dbg('min will not fit into control; ignoring', indent
=0)
691 if kwargs
.has_key('max'):
693 if( self
._min
is None
695 or (self
._min
is not None and self
._min
<= max) ):
699 textmax
= self
._toGUI
(max, apply_limits
= False)
701 dbg('max will not fit into control; ignoring', indent
=0)
708 if kwargs
.has_key('allowNegative'):
709 self
._allowNegative
= kwargs
['allowNegative']
711 # Ensure current value of control obeys any new restrictions imposed:
712 text
= self
._GetValue
()
713 dbg('text value: "%s"' % text
)
714 if kwargs
.has_key('groupChar') and text
.find(old_groupchar
) != -1:
715 text
= text
.replace(old_groupchar
, self
._groupChar
)
716 if kwargs
.has_key('decimalChar') and text
.find(old_decimalchar
) != -1:
717 text
= text
.replace(old_decimalchar
, self
._decimalChar
)
718 if text
!= self
._GetValue
():
719 wx
.TextCtrl
.SetValue(self
, text
)
721 value
= self
.GetValue()
723 dbg('self._allowNegative?', self
._allowNegative
)
724 if not self
._allowNegative
and self
._isNeg
:
726 dbg('abs(value):', value
)
729 elif not self
._allowNone
and wxMaskedTextCtrl
.GetValue(self
) == '':
735 sel_start
, sel_to
= self
.GetSelection()
736 if self
.IsLimited() and self
._min
is not None and value
< self
._min
:
737 dbg('Set to min value:', self
._min
)
738 self
._SetValue
(self
._toGUI
(self
._min
))
740 elif self
.IsLimited() and self
._max
is not None and value
> self
._max
:
741 dbg('Setting to max value:', self
._max
)
742 self
._SetValue
(self
._toGUI
(self
._max
))
744 # reformat current value as appropriate to possibly new conditions
745 dbg('Reformatting value:', value
)
746 sel_start
, sel_to
= self
.GetSelection()
747 self
._SetValue
(self
._toGUI
(value
))
748 self
.Refresh() # recolor as appropriate
749 dbg('finished wxMaskedNumCtrl::SetParameters', indent
=0)
753 def _GetNumValue(self
, value
):
755 This function attempts to "clean up" a text value, providing a regularized
756 convertable string, via atol() or atof(), for any well-formed numeric text value.
758 return value
.replace(self
._groupChar
, '').replace(self
._decimalChar
, '.').replace('(', '-').replace(')','').strip()
761 def GetFraction(self
, candidate
=None):
763 Returns the fractional portion of the value as a float. If there is no
764 fractional portion, the value returned will be 0.0.
766 if not self
._fractionWidth
:
769 fracstart
, fracend
= self
._fields
[1]._extent
770 if candidate
is None:
771 value
= self
._toGUI
(wxMaskedTextCtrl
.GetValue(self
))
773 value
= self
._toGUI
(candidate
)
774 fracstring
= value
[fracstart
:fracend
].strip()
778 return string
.atof(fracstring
)
780 def _OnChangeSign(self
, event
):
781 dbg('wxMaskedNumCtrl::_OnChangeSign', indent
=1)
782 self
._typedSign
= True
783 wxMaskedEditMixin
._OnChangeSign
(self
, event
)
787 def _disallowValue(self
):
788 dbg('wxMaskedNumCtrl::_disallowValue')
789 # limited and -1 is out of bounds
792 if not wx
.Validator_IsSilent():
794 sel_start
, sel_to
= self
._GetSelection
()
795 dbg('queuing reselection of (%d, %d)' % (sel_start
, sel_to
))
796 wx
.CallAfter(self
.SetInsertionPoint
, sel_start
) # preserve current selection/position
797 wx
.CallAfter(self
.SetSelection
, sel_start
, sel_to
)
799 def _SetValue(self
, value
):
801 This routine supersedes the base masked control _SetValue(). It is
802 needed to ensure that the value of the control is always representable/convertable
803 to a numeric return value (via GetValue().) This routine also handles
804 automatic adjustment and grouping of the value without explicit intervention
808 dbg('wxMaskedNumCtrl::_SetValue("%s")' % value
, indent
=1)
810 if( (self
._fractionWidth
and value
.find(self
._decimalChar
) == -1) or
811 (self
._fractionWidth
== 0 and value
.find(self
._decimalChar
) != -1) ) :
812 value
= self
._toGUI
(value
)
814 numvalue
= self
._GetNumValue
(value
)
815 dbg('cleansed value: "%s"' % numvalue
)
820 dbg('calling base wxMaskedTextCtrl._SetValue(self, "%s")' % value
)
821 wxMaskedTextCtrl
._SetValue
(self
, value
)
824 elif self
._min
> 0 and self
.IsLimited():
825 replacement
= self
._min
828 dbg('empty value; setting replacement:', replacement
)
830 if replacement
is None:
831 # Go get the integer portion about to be set and verify its validity
832 intstart
, intend
= self
._fields
[0]._extent
833 dbg('intstart, intend:', intstart
, intend
)
834 dbg('raw integer:"%s"' % value
[intstart
:intend
])
835 int = self
._GetNumValue
(value
[intstart
:intend
])
836 numval
= self
._fromGUI
(value
)
838 dbg('integer: "%s"' % int)
840 fracval
= self
.GetFraction(value
)
841 except ValueError, e
:
842 dbg('Exception:', e
, 'must be out of bounds; disallow value')
843 self
._disallowValue
()
848 dbg('self._isNeg?', self
._isNeg
)
849 if int == '-' and self
._oldvalue
< 0 and not self
._typedSign
:
850 dbg('just a negative sign; old value < 0; setting replacement of 0')
853 elif int[:2] == '-0' and self
._fractionWidth
== 0:
854 if self
._oldvalue
< 0:
855 dbg('-0; setting replacement of 0')
858 elif not self
._limited
or (self
._min
< -1 and self
._max
>= -1):
859 dbg('-0; setting replacement of -1')
863 # limited and -1 is out of bounds
864 self
._disallowValue
()
868 elif int == '-' and (self
._oldvalue
>= 0 or self
._typedSign
) and self
._fractionWidth
== 0:
869 if not self
._limited
or (self
._min
< -1 and self
._max
>= -1):
870 dbg('just a negative sign; setting replacement of -1')
873 # limited and -1 is out of bounds
874 self
._disallowValue
()
878 elif( self
._typedSign
879 and int.find('-') != -1
881 and not self
._min
<= numval
<= self
._max
):
882 # changed sign resulting in value that's now out-of-bounds;
884 self
._disallowValue
()
888 if replacement
is None:
889 if int and int != '-':
893 # integer requested is not legal. This can happen if the user
894 # is attempting to insert a digit in the middle of the control
895 # resulting in something like " 3 45". Disallow such actions:
896 dbg('>>>>>>>>>>>>>>>> "%s" does not convert to a long!' % int)
897 if not wx
.Validator_IsSilent():
899 sel_start
, sel_to
= self
._GetSelection
()
900 dbg('queuing reselection of (%d, %d)' % (sel_start
, sel_to
))
901 wx
.CallAfter(self
.SetInsertionPoint
, sel_start
) # preserve current selection/position
902 wx
.CallAfter(self
.SetSelection
, sel_start
, sel_to
)
906 if int[0] == '0' and len(int) > 1:
907 dbg('numvalue: "%s"' % numvalue
.replace(' ', ''))
908 if self
._fractionWidth
:
909 value
= self
._toGUI
(string
.atof(numvalue
))
911 value
= self
._toGUI
(string
.atol(numvalue
))
912 dbg('modified value: "%s"' % value
)
914 self
._typedSign
= False # reset state var
916 if replacement
is not None:
917 # Value presented wasn't a legal number, but control should do something
918 # reasonable instead:
919 dbg('setting replacement value:', replacement
)
920 self
._SetValue
(self
._toGUI
(replacement
))
921 sel_start
= wxMaskedTextCtrl
.GetValue(self
).find(str(abs(replacement
))) # find where it put the 1, so we can select it
922 sel_to
= sel_start
+ len(str(abs(replacement
)))
923 dbg('queuing selection of (%d, %d)' %(sel_start
, sel_to
))
924 wx
.CallAfter(self
.SetInsertionPoint
, sel_start
)
925 wx
.CallAfter(self
.SetSelection
, sel_start
, sel_to
)
929 # Otherwise, apply appropriate formatting to value:
931 # Because we're intercepting the value and adjusting it
932 # before a sign change is detected, we need to do this here:
933 if '-' in value
or '(' in value
:
938 dbg('value:"%s"' % value
, 'self._useParens:', self
._useParens
)
939 if self
._fractionWidth
:
940 adjvalue
= self
._adjustFloat
(self
._GetNumValue
(value
).replace('.',self
._decimalChar
))
942 adjvalue
= self
._adjustInt
(self
._GetNumValue
(value
))
943 dbg('adjusted value: "%s"' % adjvalue
)
946 sel_start
, sel_to
= self
._GetSelection
() # record current insertion point
947 dbg('calling base wxMaskedTextCtrl._SetValue(self, "%s")' % adjvalue
)
948 wxMaskedTextCtrl
._SetValue
(self
, adjvalue
)
949 # After all actions so far scheduled, check that resulting cursor
950 # position is appropriate, and move if not:
951 wx
.CallAfter(self
._CheckInsertionPoint
)
953 dbg('finished wxMaskedNumCtrl::_SetValue', indent
=0)
955 def _CheckInsertionPoint(self
):
956 # If current insertion point is before the end of the integer and
957 # its before the 1st digit, place it just after the sign position:
958 dbg('wxMaskedNumCtrl::CheckInsertionPoint', indent
=1)
959 sel_start
, sel_to
= self
._GetSelection
()
960 text
= self
._GetValue
()
961 if sel_to
< self
._fields
[0]._extent
[1] and text
[sel_to
] in (' ', '-', '('):
962 text
, signpos
, right_signpos
= self
._getSignedValue
()
963 dbg('setting selection(%d, %d)' % (signpos
+1, signpos
+1))
964 self
.SetInsertionPoint(signpos
+1)
965 self
.SetSelection(signpos
+1, signpos
+1)
969 def _OnErase( self
, event
):
971 This overrides the base control _OnErase, so that erasing around
972 grouping characters auto selects the digit before or after the
973 grouping character, so that the erasure does the right thing.
975 dbg('wxMaskedNumCtrl::_OnErase', indent
=1)
977 #if grouping digits, make sure deletes next to group char always
978 # delete next digit to appropriate side:
979 if self
._groupDigits
:
980 key
= event
.GetKeyCode()
981 value
= wxMaskedTextCtrl
.GetValue(self
)
982 sel_start
, sel_to
= self
._GetSelection
()
984 if key
== wx
.WXK_BACK
:
985 # if 1st selected char is group char, select to previous digit
986 if sel_start
> 0 and sel_start
< len(self
._mask
) and value
[sel_start
:sel_to
] == self
._groupChar
:
987 self
.SetInsertionPoint(sel_start
-1)
988 self
.SetSelection(sel_start
-1, sel_to
)
990 # elif previous char is group char, select to previous digit
991 elif sel_start
> 1 and sel_start
== sel_to
and value
[sel_start
-1:sel_start
] == self
._groupChar
:
992 self
.SetInsertionPoint(sel_start
-2)
993 self
.SetSelection(sel_start
-2, sel_to
)
995 elif key
== wx
.WXK_DELETE
:
996 if( sel_to
< len(self
._mask
) - 2 + (1 *self
._useParens
)
997 and sel_start
== sel_to
998 and value
[sel_to
] == self
._groupChar
):
999 self
.SetInsertionPoint(sel_start
)
1000 self
.SetSelection(sel_start
, sel_to
+2)
1002 elif( sel_to
< len(self
._mask
) - 2 + (1 *self
._useParens
)
1003 and value
[sel_start
:sel_to
] == self
._groupChar
):
1004 self
.SetInsertionPoint(sel_start
)
1005 self
.SetSelection(sel_start
, sel_to
+1)
1007 wxMaskedTextCtrl
._OnErase
(self
, event
)
1011 def OnTextChange( self
, event
):
1013 Handles an event indicating that the text control's value
1014 has changed, and issue EVT_MaskedNum event.
1015 NOTE: using wxTextCtrl.SetValue() to change the control's
1016 contents from within a EVT_CHAR handler can cause double
1017 text events. So we check for actual changes to the text
1018 before passing the events on.
1020 dbg('wxMaskedNumCtrl::OnTextChange', indent
=1)
1021 if not wxMaskedTextCtrl
._OnTextChange
(self
, event
):
1025 # else... legal value
1027 value
= self
.GetValue()
1028 if value
!= self
._oldvalue
:
1030 self
.GetEventHandler().ProcessEvent(
1031 wxMaskedNumNumberUpdatedEvent( self
.GetId(), self
.GetValue(), self
) )
1035 # let normal processing of the text continue
1037 self
._oldvalue
= value
# record for next event
1040 def _GetValue(self
):
1042 Override of wxMaskedTextCtrl to allow amixin to get the raw text value of the
1043 control with this function.
1045 return wx
.TextCtrl
.GetValue(self
)
1050 Returns the current numeric value of the control.
1052 return self
._fromGUI
( wxMaskedTextCtrl
.GetValue(self
) )
1054 def SetValue(self
, value
):
1056 Sets the value of the control to the value specified.
1057 The resulting actual value of the control may be altered to
1058 conform with the bounds set on the control if limited,
1059 or colored if not limited but the value is out-of-bounds.
1060 A ValueError exception will be raised if an invalid value
1063 wxMaskedTextCtrl
.SetValue( self
, self
._toGUI
(value
) )
1066 def SetIntegerWidth(self
, value
):
1067 self
.SetCtrlParameters(integerWidth
=value
)
1068 def GetIntegerWidth(self
):
1069 return self
._integerWidth
1071 def SetFractionWidth(self
, value
):
1072 self
.SetCtrlParameters(fractionWidth
=value
)
1073 def GetFractionWidth(self
):
1074 return self
._fractionWidth
1078 def SetMin(self
, min=None):
1080 Sets the minimum value of the control. If a value of None
1081 is provided, then the control will have no explicit minimum value.
1082 If the value specified is greater than the current maximum value,
1083 then the function returns False and the minimum will not change from
1084 its current setting. On success, the function returns True.
1086 If successful and the current value is lower than the new lower
1087 bound, if the control is limited, the value will be automatically
1088 adjusted to the new minimum value; if not limited, the value in the
1089 control will be colored as invalid.
1091 If min > the max value allowed by the width of the control,
1092 the function will return False, and the min will not be set.
1094 dbg('wxMaskedNumCtrl::SetMin(%s)' % repr(min), indent
=1)
1095 if( self
._max
is None
1097 or (self
._max
is not None and self
._max
>= min) ):
1099 self
.SetParameters(min=min)
1110 Gets the lower bound value of the control. It will return
1111 None if not specified.
1116 def SetMax(self
, max=None):
1118 Sets the maximum value of the control. If a value of None
1119 is provided, then the control will have no explicit maximum value.
1120 If the value specified is less than the current minimum value, then
1121 the function returns False and the maximum will not change from its
1122 current setting. On success, the function returns True.
1124 If successful and the current value is greater than the new upper
1125 bound, if the control is limited the value will be automatically
1126 adjusted to this maximum value; if not limited, the value in the
1127 control will be colored as invalid.
1129 If max > the max value allowed by the width of the control,
1130 the function will return False, and the max will not be set.
1132 if( self
._min
is None
1134 or (self
._min
is not None and self
._min
<= max) ):
1136 self
.SetParameters(max=max)
1148 Gets the maximum value of the control. It will return the current
1149 maximum integer, or None if not specified.
1154 def SetBounds(self
, min=None, max=None):
1156 This function is a convenience function for setting the min and max
1157 values at the same time. The function only applies the maximum bound
1158 if setting the minimum bound is successful, and returns True
1159 only if both operations succeed.
1160 NOTE: leaving out an argument will remove the corresponding bound.
1162 ret
= self
.SetMin(min)
1163 return ret
and self
.SetMax(max)
1166 def GetBounds(self
):
1168 This function returns a two-tuple (min,max), indicating the
1169 current bounds of the control. Each value can be None if
1170 that bound is not set.
1172 return (self
._min
, self
._max
)
1175 def SetLimited(self
, limited
):
1177 If called with a value of True, this function will cause the control
1178 to limit the value to fall within the bounds currently specified.
1179 If the control's value currently exceeds the bounds, it will then
1180 be limited accordingly.
1182 If called with a value of False, this function will disable value
1183 limiting, but coloring of out-of-bounds values will still take
1184 place if bounds have been set for the control.
1186 self
.SetParameters(limited
= limited
)
1189 def IsLimited(self
):
1191 Returns True if the control is currently limiting the
1192 value to fall within the current bounds.
1194 return self
._limited
1196 def GetLimited(self
):
1197 """ (For regularization of property accessors) """
1198 return self
.IsLimited
1201 def IsInBounds(self
, value
=None):
1203 Returns True if no value is specified and the current value
1204 of the control falls within the current bounds. This function can
1205 also be called with a value to see if that value would fall within
1206 the current bounds of the given control.
1208 dbg('IsInBounds(%s)' % repr(value
), indent
=1)
1210 value
= self
.GetValue()
1213 value
= self
._GetNumValue
(self
._toGUI
(value
))
1214 except ValueError, e
:
1215 dbg('error getting NumValue(self._toGUI(value)):', e
, indent
=0)
1219 elif self
._fractionWidth
:
1220 value
= float(value
)
1226 if min is None: min = value
1227 if max is None: max = value
1229 # if bounds set, and value is None, return False
1230 if value
== None and (min is not None or max is not None):
1231 dbg('finished IsInBounds', indent
=0)
1234 dbg('finished IsInBounds', indent
=0)
1235 return min <= value
<= max
1238 def SetAllowNone(self
, allow_none
):
1240 Change the behavior of the validation code, allowing control
1241 to have a value of None or not, as appropriate. If the value
1242 of the control is currently None, and allow_none is False, the
1243 value of the control will be set to the minimum value of the
1244 control, or 0 if no lower bound is set.
1246 self
._allowNone
= allow_none
1247 if not allow_none
and self
.GetValue() is None:
1249 if min is not None: self
.SetValue(min)
1250 else: self
.SetValue(0)
1253 def IsNoneAllowed(self
):
1254 return self
._allowNone
1255 def GetAllowNone(self
):
1256 """ (For regularization of property accessors) """
1257 return self
.IsNoneAllowed()
1259 def SetAllowNegative(self
, value
):
1260 self
.SetParameters(allowNegative
=value
)
1261 def IsNegativeAllowed(self
):
1262 return self
._allowNegative
1263 def GetAllowNegative(self
):
1264 """ (For regularization of property accessors) """
1265 return self
.IsNegativeAllowed()
1267 def SetGroupDigits(self
, value
):
1268 self
.SetParameters(groupDigits
=value
)
1269 def IsGroupingAllowed(self
):
1270 return self
._groupDigits
1271 def GetGroupDigits(self
):
1272 """ (For regularization of property accessors) """
1273 return self
.IsGroupingAllowed()
1275 def SetGroupChar(self
, value
):
1276 self
.SetParameters(groupChar
=value
)
1277 def GetGroupChar(self
):
1278 return self
._groupChar
1280 def SetDecimalChar(self
, value
):
1281 self
.SetParameters(decimalChar
=value
)
1282 def GetDecimalChar(self
):
1283 return self
._decimalChar
1285 def SetSelectOnEntry(self
, value
):
1286 self
.SetParameters(selectOnEntry
=value
)
1287 def GetSelectOnEntry(self
):
1288 return self
._selectOnEntry
1290 # (Other parameter accessors are inherited from base class)
1293 def _toGUI( self
, value
, apply_limits
= True ):
1295 Conversion function used to set the value of the control; does
1296 type and bounds checking and raises ValueError if argument is
1299 dbg('wxMaskedNumCtrl::_toGUI(%s)' % repr(value
), indent
=1)
1300 if value
is None and self
.IsNoneAllowed():
1302 return self
._template
1304 elif type(value
) in (types
.StringType
, types
.UnicodeType
):
1305 value
= self
._GetNumValue
(value
)
1306 dbg('cleansed num value: "%s"' % value
)
1308 if self
._fractionWidth
or value
.find('.') != -1:
1309 value
= float(value
)
1312 except Exception, e
:
1313 dbg('exception raised:', e
, indent
=0)
1314 raise ValueError ('wxMaskedNumCtrl requires numeric value, passed %s'% repr(value
) )
1316 elif type(value
) not in (types
.IntType
, types
.LongType
, types
.FloatType
):
1319 'wxMaskedNumCtrl requires numeric value, passed %s'% repr(value
) )
1321 if not self
._allowNegative
and value
< 0:
1323 'control configured to disallow negative values, passed %s'% repr(value
) )
1325 if self
.IsLimited() and apply_limits
:
1328 if not min is None and value
< min:
1331 'value %d is below minimum value of control'% value
)
1332 if not max is None and value
> max:
1335 'value %d exceeds value of control'% value
)
1337 adjustwidth
= len(self
._mask
) - (1 * self
._useParens
* self
._signOk
)
1338 dbg('len(%s):' % self
._mask
, len(self
._mask
))
1339 dbg('adjustwidth - groupSpace:', adjustwidth
- self
._groupSpace
)
1340 dbg('adjustwidth:', adjustwidth
)
1341 if self
._fractionWidth
== 0:
1342 s
= str(long(value
)).rjust(self
._integerWidth
)
1344 format
= '%' + '%d.%df' % (self
._integerWidth
+self
._fractionWidth
+1, self
._fractionWidth
)
1345 s
= format
% float(value
)
1346 dbg('s:"%s"' % s
, 'len(s):', len(s
))
1347 if len(s
) > (adjustwidth
- self
._groupSpace
):
1349 raise ValueError ('value %s exceeds the integer width of the control (%d)' % (s
, self
._integerWidth
))
1350 elif s
[0] not in ('-', ' ') and self
._allowNegative
and len(s
) == (adjustwidth
- self
._groupSpace
):
1352 raise ValueError ('value %s exceeds the integer width of the control (%d)' % (s
, self
._integerWidth
))
1354 s
= s
.rjust(adjustwidth
).replace('.', self
._decimalChar
)
1355 if self
._signOk
and self
._useParens
:
1356 if s
.find('-') != -1:
1357 s
= s
.replace('-', '(') + ')'
1360 dbg('returned: "%s"' % s
, indent
=0)
1364 def _fromGUI( self
, value
):
1366 Conversion function used in getting the value of the control.
1369 dbg('wxMaskedNumCtrl::_fromGUI(%s)' % value
, indent
=1)
1370 # One or more of the underlying text control implementations
1371 # issue an intermediate EVT_TEXT when replacing the control's
1372 # value, where the intermediate value is an empty string.
1373 # So, to ensure consistency and to prevent spurious ValueErrors,
1374 # we make the following test, and react accordingly:
1377 if not self
.IsNoneAllowed():
1378 dbg('empty value; not allowed,returning 0', indent
= 0)
1379 if self
._fractionWidth
:
1384 dbg('empty value; returning None', indent
= 0)
1387 value
= self
._GetNumValue
(value
)
1388 dbg('Num value: "%s"' % value
)
1389 if self
._fractionWidth
:
1392 return float( value
)
1394 dbg("couldn't convert to float; returning None")
1405 return long( value
)
1407 dbg("couldn't convert to long; returning None")
1413 dbg('exception occurred; returning None')
1417 def _Paste( self
, value
=None, raise_on_invalid
=False, just_return_value
=False ):
1419 Preprocessor for base control paste; if value needs to be right-justified
1420 to fit in control, do so prior to paste:
1422 dbg('wxMaskedNumCtrl::_Paste (value = "%s")' % value
)
1424 paste_text
= self
._getClipboardContents
()
1428 # treat paste as "replace number", if appropriate:
1429 sel_start
, sel_to
= self
._GetSelection
()
1430 if sel_start
== sel_to
or self
._selectOnEntry
and (sel_start
, sel_to
) == self
._fields
[0]._extent
:
1431 paste_text
= self
._toGUI
(paste_text
)
1432 self
._SetSelection
(0, len(self
._mask
))
1434 return wxMaskedEditMixin
._Paste
(self
,
1436 raise_on_invalid
=raise_on_invalid
,
1437 just_return_value
=just_return_value
)
1441 #===========================================================================
1443 if __name__
== '__main__':
1447 class myDialog(wx
.Dialog
):
1448 def __init__(self
, parent
, id, title
,
1449 pos
= wx
.DefaultPosition
, size
= wx
.DefaultSize
,
1450 style
= wx
.DEFAULT_DIALOG_STYLE
):
1451 wx
.Dialog
.__init
__(self
, parent
, id, title
, pos
, size
, style
)
1453 self
.int_ctrl
= wxMaskedNumCtrl(self
, wx
.NewId(), size
=(55,20))
1454 self
.OK
= wx
.Button( self
, wx
.ID_OK
, "OK")
1455 self
.Cancel
= wx
.Button( self
, wx
.ID_CANCEL
, "Cancel")
1457 vs
= wx
.BoxSizer( wx
.VERTICAL
)
1458 vs
.Add( self
.int_ctrl
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1459 hs
= wx
.BoxSizer( wx
.HORIZONTAL
)
1460 hs
.Add( self
.OK
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1461 hs
.Add( self
.Cancel
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1462 vs
.Add(hs
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1464 self
.SetAutoLayout( True )
1467 vs
.SetSizeHints( self
)
1468 self
.Bind(EVT_MASKEDNUM
, self
.OnChange
, self
.int_ctrl
)
1470 def OnChange(self
, event
):
1471 print 'value now', event
.GetValue()
1473 class TestApp(wx
.App
):
1476 self
.frame
= wx
.Frame(None, -1, "Test", (20,20), (120,100) )
1477 self
.panel
= wx
.Panel(self
.frame
, -1)
1478 button
= wx
.Button(self
.panel
, -1, "Push Me", (20, 20))
1479 self
.Bind(wx
.EVT_BUTTON
, self
.OnClick
, button
)
1481 traceback
.print_exc()
1485 def OnClick(self
, event
):
1486 dlg
= myDialog(self
.panel
, -1, "test wxMaskedNumCtrl")
1487 dlg
.int_ctrl
.SetValue(501)
1488 dlg
.int_ctrl
.SetInsertionPoint(1)
1489 dlg
.int_ctrl
.SetSelection(1,2)
1490 rc
= dlg
.ShowModal()
1491 print 'final value', dlg
.int_ctrl
.GetValue()
1493 self
.frame
.Destroy()
1496 self
.frame
.Show(True)
1503 traceback
.print_exc()
1507 ## =============================##
1508 ## 1. Add support for printf-style format specification.
1509 ## 2. Add option for repositioning on 'illegal' insertion point.