pycollapsiblepane.py
31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
# --------------------------------------------------------------------------------- #
# PYCOLLAPSIBLEPANE wxPython IMPLEMENTATION
# Generic Implementation Based On wx.CollapsiblePane.
#
# Andrea Gavana, @ 09 Aug 2007
# Latest Revision: 14 Mar 2012, 21.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #
"""
:class:`PyCollapsiblePane` is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.
Description
===========
A collapsible pane is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.
Once constructed you should use the meth:~PyCollapsiblePane.GetPane` function to access the pane and
add your controls inside it (i.e. use the window returned from meth:~PyCollapsiblePane.GetPane` as the
parent for the controls which must go in the pane, **not** the :class:`PyCollapsiblePane`
itself!).
:note: Note that because of its nature of control which can dynamically (and drastically)
change its size at run-time under user-input, when putting :class:`PyCollapsiblePane`
inside a :class:`Sizer` you should be careful to add it with a proportion value of zero;
this is because otherwise all other windows with non-null proportion values would
automatically get resized each time the user expands or collapse the pane window
resulting usually in a weird, flickering effect.
Usage
=====
Usage example::
import wx
import wx.lib.agw.pycollapsiblepane as PCP
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "PyCollapsiblePane Demo")
panel = wx.Panel(self)
title = wx.StaticText(panel, label="PyCollapsiblePane")
title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
title.SetForegroundColour("blue")
self.cp = cp = PCP.PyCollapsiblePane(panel, label=label1,
style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)
self.MakePaneContent(cp.GetPane())
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(title, 0, wx.ALL, 25)
sizer.Add(cp, 0, wx.RIGHT|wx.LEFT|wx.EXPAND, 25)
panel.SetSizer(sizer)
sizer.Layout()
def MakePaneContent(self, pane):
''' Just makes a few controls to put on `PyCollapsiblePane`. '''
nameLbl = wx.StaticText(pane, -1, "Name:")
name = wx.TextCtrl(pane, -1, "");
addrLbl = wx.StaticText(pane, -1, "Address:")
addr1 = wx.TextCtrl(pane, -1, "");
addr2 = wx.TextCtrl(pane, -1, "");
cstLbl = wx.StaticText(pane, -1, "City, State, Zip:")
city = wx.TextCtrl(pane, -1, "", size=(150,-1));
state = wx.TextCtrl(pane, -1, "", size=(50,-1));
zip = wx.TextCtrl(pane, -1, "", size=(70,-1));
addrSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
addrSizer.AddGrowableCol(1)
addrSizer.Add(nameLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
addrSizer.Add(name, 0, wx.EXPAND)
addrSizer.Add(addrLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
addrSizer.Add(addr1, 0, wx.EXPAND)
addrSizer.Add((5,5))
addrSizer.Add(addr2, 0, wx.EXPAND)
addrSizer.Add(cstLbl, 0,
wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
cstSizer = wx.BoxSizer(wx.HORIZONTAL)
cstSizer.Add(city, 1)
cstSizer.Add(state, 0, wx.LEFT|wx.RIGHT, 5)
cstSizer.Add(zip)
addrSizer.Add(cstSizer, 0, wx.EXPAND)
border = wx.BoxSizer()
border.Add(addrSizer, 1, wx.EXPAND|wx.ALL, 5)
pane.SetSizer(border)
# our normal wxApp-derived class, as usual
app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Window Styles
=============
This class supports the following window styles:
==================== =========== ==================================================
Window Styles Hex Value Description
==================== =========== ==================================================
``CP_NO_TLW_RESIZE`` 0x2 By default :class:`PyCollapsiblePane` resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
``CP_GTK_EXPANDER`` 0x4 Uses a GTK expander instead of a button.
``CP_USE_STATICBOX`` 0x8 Uses a :class:`StaticBox` around :class:`PyCollapsiblePane`.
``CP_LINE_ABOVE`` 0x10 Draws a line above :class:`PyCollapsiblePane`.
==================== =========== ==================================================
Events Processing
=================
This class processes the following events:
=============================== ==================================================
Event Name Description
=============================== ==================================================
``EVT_COLLAPSIBLEPANE_CHANGED`` The user showed or hid the collapsible pane.
=============================== ==================================================
License And Version
===================
:class:`PyCollapsiblePane` is distributed under the wxPython license.
Latest Revision: Andrea Gavana @ 14 Mar 2012, 21.00 GMT
Version 0.4
"""
import wx
CP_GTK_EXPANDER = 4
""" Uses a GTK expander instead of a button. """
CP_USE_STATICBOX = 8
""" Uses a :class:`StaticBox` around :class:`PyCollapsiblePane`. """
CP_LINE_ABOVE = 16
""" Draws a line above :class:`PyCollapsiblePane`. """
CP_DEFAULT_STYLE = wx.CP_DEFAULT_STYLE
""" The default style. It includes ``wx.TAB_TRAVERSAL`` and ``wx.BORDER_NONE``. """
CP_NO_TLW_RESIZE = wx.CP_NO_TLW_RESIZE
""" By default :class:`PyCollapsiblePane` resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then. """
# inject into the wx namespace with the other CP_* constants
wx.CP_GTK_EXPANDER = CP_GTK_EXPANDER
wx.CP_USE_STATICBOX = CP_USE_STATICBOX
wx.CP_LINE_ABOVE = CP_LINE_ABOVE
# PyCollapsiblePane events
EVT_COLLAPSIBLEPANE_CHANGED = wx.EVT_COLLAPSIBLEPANE_CHANGED
""" The user showed or hid the collapsible pane. """
#-----------------------------------------------------------------------------
# 2.9 deprecates SetSpacer, so we'll use AssignSpacer and monkey-patch 2.8 so
# it works there too
if wx.VERSION < (2, 9):
wx.SizerItem.AssignSpacer = wx.SizerItem.SetSpacer
#-----------------------------------------------------------------------------
# GTKExpander widget
#-----------------------------------------------------------------------------
class GTKExpander(wx.PyControl):
"""
A :class:`GTKExpander` allows the user to hide or show its child by clicking on an expander
triangle.
"""
def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.NO_BORDER):
"""
Default class constructor.
:param `parent`: the :class:`GTKExpander` parent. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `label`: the expander text label;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the expander style.
"""
wx.PyControl.__init__(self, parent, id, pos, size, style)
self.SetLabel(label)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self._parent = parent
self.Bind(wx.EVT_SIZE, self.OnSize)
def OnDrawGTKExpander(self, dc):
"""
Draws the :class:`GTKExpander` triangle.
:param `dc`: an instance of :class:`DC`.
"""
size = self.GetSize()
label = self._parent.GetBtnLabel()
triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
textWidth, textHeight, descent, externalLeading = dc.GetFullTextExtent(label, self.GetFont())
dc.SetBrush(wx.BLACK_BRUSH)
dc.SetPen(wx.BLACK_PEN)
if self._parent.IsCollapsed():
startX, startY = triangleWidth/2, size.y - triangleHeight - 1 - descent
pt1 = wx.Point(startX, startY)
pt2 = wx.Point(startX, size.y - 1 - descent)
pt3 = wx.Point(startX+triangleWidth, size.y-triangleHeight/2 - 1 - descent)
else:
startX, startY = 0, size.y - triangleWidth - descent - 1
pt1 = wx.Point(startX, startY)
pt2 = wx.Point(startX+triangleHeight, startY)
pt3 = wx.Point(startX+triangleHeight/2, size.y - descent - 1)
dc.DrawPolygon([pt1, pt2, pt3])
def OnDrawGTKText(self, dc):
"""
Draws the :class:`GTKExpander` text label.
:param `dc`: an instance of :class:`DC`.
"""
size = self.GetSize()
label = self._parent.GetBtnLabel()
triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
textWidth, textHeight, descent, externalLeading = dc.GetFullTextExtent(label, self.GetFont())
dc.SetFont(self.GetFont())
startX, startY = 2*triangleHeight+1, size.y - textHeight
dc.DrawText(label, startX, startY)
def DoGetBestSize(self):
"""
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
:note: Overridden from :class:`PyControl`.
"""
triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
label = self._parent.GetBtnLabel()
dc = wx.ClientDC(self)
textWidth, textHeight, descent, externalLeading = dc.GetFullTextExtent(label, self.GetFont())
maxHeight = max(textHeight+descent, triangleHeight)
maxWidth = 2*triangleHeight+1 + textWidth
return wx.Size(maxWidth, maxHeight)
def OnSize(self, event):
"""
Handles the ``wx.EVT_SIZE`` event for :class:`GTKExpander`.
:param `event`: a :class:`SizeEvent` event to be processed.
"""
self.Refresh()
#-----------------------------------------------------------------------------
# PyCollapsiblePane
#-----------------------------------------------------------------------------
class PyCollapsiblePane(wx.PyPanel):
"""
:class:`PyCollapsiblePane` is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.
"""
def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0, agwStyle=wx.CP_DEFAULT_STYLE,
validator=wx.DefaultValidator, name="PyCollapsiblePane"):
"""
Default class constructor.
:param `parent`: the :class:`PyCollapsiblePane` parent. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `label`: The initial label shown in the button which allows the
user to expand or collapse the pane window.
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the underlying :class:`PyPanel` window style;
:param `agwStyle`: the AGW-specifi window style. This can be a combination of the
following bits:
==================== =========== ==================================================
Window Styles Hex Value Description
==================== =========== ==================================================
``CP_NO_TLW_RESIZE`` 0x2 By default :class:`PyCollapsiblePane` resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
``CP_GTK_EXPANDER`` 0x4 Uses a GTK expander instead of a button.
``CP_USE_STATICBOX`` 0x8 Uses a :class:`StaticBox` around :class:`PyCollapsiblePane`.
``CP_LINE_ABOVE`` 0x10 Draws a line above :class:`PyCollapsiblePane`.
==================== =========== ==================================================
:param `validator`: the validator associated to the :class:`PyCollapsiblePane`;
:param `name`: the widget name.
"""
wx.PyPanel.__init__(self, parent, id, pos, size, style, name)
self._pButton = self._pStaticLine = self._pPane = self._sz = None
self._strLabel = label
self._bCollapsed = True
self._agwStyle = agwStyle
self._pPane = wx.Panel(self, style=wx.TAB_TRAVERSAL|wx.NO_BORDER)
self._pPane.Hide()
if self.HasAGWFlag(CP_USE_STATICBOX):
# Use a StaticBox instead of a StaticLine, and the button's
# position will be handled separately so don't put it in the sizer
self._pStaticBox = wx.StaticBox(self)
self.SetButton(wx.Button(self, wx.ID_ANY, self.GetLabel(), style=wx.BU_EXACTFIT))
self._sz = wx.BoxSizer(wx.VERTICAL)
self._sz.Add((1,1)) # spacer, size will be reset later
self._contentSizer = wx.StaticBoxSizer(self._pStaticBox, wx.VERTICAL)
self._contentSizer.Add((1,1)) # spacer, size will be reset later
self._contentSizer.Add(self._pPane, 1, wx.EXPAND)
self._sz.Add(self._contentSizer, 1, wx.EXPAND)
if self.HasAGWFlag(CP_USE_STATICBOX) and 'wxMSW' in wx.PlatformInfo:
# This hack is needed on Windows because wxMSW clears the
# CLIP_SIBLINGS style from all sibling controls that overlap the
# static box, so the box ends up overdrawing the button since we
# have the button overlapping the box. This hack will ensure that
# the button is refreshed after every time that the box is drawn.
# This adds a little flicker but it is not too bad compared to
# others.
def paint(evt):
def updateBtn():
if self and self._pButton:
self._pButton.Refresh()
self._pButton.Update()
wx.CallAfter(updateBtn)
evt.Skip()
self._pStaticBox.Bind(wx.EVT_PAINT, paint)
elif self.HasAGWFlag(CP_GTK_EXPANDER):
self._sz = wx.BoxSizer(wx.HORIZONTAL)
self.SetExpanderDimensions(3, 6)
self.SetButton(GTKExpander(self, wx.ID_ANY, self.GetLabel()))
self._sz.Add(self._pButton, 0, wx.LEFT|wx.TOP|wx.BOTTOM, self.GetBorder())
self._pButton.Bind(wx.EVT_PAINT, self.OnDrawGTKStyle)
self._pButton.Bind(wx.EVT_LEFT_DOWN, self.OnButton)
if wx.Platform == "__WXMSW__":
self._pButton.Bind(wx.EVT_LEFT_DCLICK, self.OnButton)
else:
# create children and lay them out using a wx.BoxSizer
# (so that we automatically get RTL features)
self.SetButton(wx.Button(self, wx.ID_ANY, self.GetLabel(), style=wx.BU_EXACTFIT))
self._pStaticLine = wx.StaticLine(self, wx.ID_ANY)
if self.HasAGWFlag(CP_LINE_ABOVE):
# put the static line above the button
self._sz = wx.BoxSizer(wx.VERTICAL)
self._sz.Add(self._pStaticLine, 0, wx.ALL|wx.GROW, self.GetBorder())
self._sz.Add(self._pButton, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, self.GetBorder())
else:
# arrange the static line and the button horizontally
self._sz = wx.BoxSizer(wx.HORIZONTAL)
self._sz.Add(self._pButton, 0, wx.LEFT|wx.TOP|wx.BOTTOM, self.GetBorder())
self._sz.Add(self._pStaticLine, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, self.GetBorder())
self.Bind(wx.EVT_SIZE, self.OnSize)
def SetAGWWindowStyleFlag(self, agwStyle):
"""
Sets the :class:`PyCollapsiblePane` window style flags.
:param `agwStyle`: the AGW-specific window style. This can be a combination of the
following bits:
==================== =========== ==================================================
Window Styles Hex Value Description
==================== =========== ==================================================
``CP_NO_TLW_RESIZE`` 0x2 By default :class:`PyCollapsiblePane` resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
``CP_GTK_EXPANDER`` 0x4 Uses a GTK expander instead of a button.
``CP_USE_STATICBOX`` 0x8 Uses a :class:`StaticBox` around :class:`PyCollapsiblePane`.
``CP_LINE_ABOVE`` 0x10 Draws a line above :class:`PyCollapsiblePane`.
==================== =========== ==================================================
"""
self._agwStyle = agwStyle
self.Layout()
self.Refresh()
def GetAGWWindowStyleFlag(self):
"""
Returns the :class:`PyCollapsiblePane` window style.
:see: :meth:`~PyCollapsiblePane.SetAGWWindowStyleFlag` for a list of possible window style flags.
"""
return self._agwStyle
def HasAGWFlag(self, flag):
"""
Returns whether a flag is present in the :class:`PyCollapsiblePane` style.
:param `flag`: one of the possible :class:`PyCollapsiblePane` window styles.
:see: :meth:`~PyCollapsiblePane.SetAGWWindowStyleFlag` for a list of possible window style flags.
"""
agwStyle = self.GetAGWWindowStyleFlag()
res = (agwStyle & flag and [True] or [False])[0]
return res
def GetBtnLabel(self):
""" Returns the button label. """
if self.GetAGWWindowStyleFlag() & CP_GTK_EXPANDER:
return self.GetLabel()
return self.GetLabel() + (self.IsCollapsed() and [" >>"] or [" <<"])[0]
def OnStateChange(self, sz):
"""
Handles the status changes (collapsing/expanding).
:param `sz`: an instance of :class:`Size`.
"""
self.SetSize(sz)
if self.HasAGWFlag(wx.CP_NO_TLW_RESIZE):
# the user asked to explicitely handle the resizing itself...
return
# NB: the following block of code has been accurately designed to
# as much flicker-free as possible be careful when modifying it!
top = wx.GetTopLevelParent(self)
if top:
# NB: don't Layout() the 'top' window as its size has not been correctly
# updated yet and we don't want to do an initial Layout() with the old
# size immediately followed by a SetClientSize/Fit call for the new
# size that would provoke flickering!
if top.GetSizer():
if (wx.Platform == "__WXGTK__" and self.IsCollapsed()) or wx.Platform != "__WXGTK__":
# FIXME: the SetSizeHints() call would be required also for GTK+ for
# the expanded.collapsed transition. Unfortunately if we
# enable this line, then the GTK+ top window won't always be
# resized by the SetClientSize() call below! As a side effect
# of this dirty fix, the minimal size for the pane window is
# not set in GTK+ and the user can hide it shrinking the "top"
# window...
top.GetSizer().SetSizeHints(top)
# we shouldn't attempt to resize a maximized window, whatever happens
if not top.IsMaximized():
if self.IsCollapsed():
# expanded . collapsed transition
if top.GetSizer():
# we have just set the size hints...
sz = top.GetSizer().CalcMin()
# use SetClientSize() and not SetSize() otherwise the size for
# e.g. a wxFrame with a menubar wouldn't be correctly set
top.SetClientSize(sz)
else:
top.Layout()
else:
# collapsed . expanded transition
# force our parent to "fit", i.e. expand so that it can honour
# our best size
top.Fit()
def Collapse(self, collapse=True):
"""
Collapses or expands the pane window.
:param `collapse`: ``True`` to collapse the pane window, ``False`` to expand it.
"""
# optimization
if self.IsCollapsed() == collapse:
return
self.Freeze()
# update our state
self._pPane.Show(not collapse)
self._bCollapsed = collapse
self.InvalidateBestSize()
self.Thaw()
# update button label
# NB: this must be done after updating our "state"
self._pButton.SetLabel(self.GetBtnLabel())
self.OnStateChange(self.GetBestSize())
def Expand(self):
""" Same as :meth:`~PyCollapsiblePane.Collapse` (False). """
self.Collapse(False)
def IsCollapsed(self):
""" Returns ``True`` if the pane window is currently hidden. """
return self._bCollapsed
def IsExpanded(self):
""" Returns ``True`` if the pane window is currently shown. """
return not self.IsCollapsed()
def GetPane(self):
"""
Returns a reference to the pane window. Use the returned :class:`Window` as
the parent of widgets to make them part of the collapsible area.
"""
return self._pPane
def SetLabel(self, label):
"""
Sets the button label.
:param `label`: the new button label.
:note: Overridden from :class:`PyPanel`.
"""
self._strLabel = label
self._pButton.SetLabel(self.GetBtnLabel())
self._pButton.SetInitialSize()
self._pButton.Refresh()
self.InvalidateBestSize()
self.Layout()
def GetLabel(self):
"""
Returns the button label.
:note: Overridden from :class:`PyPanel`.
"""
return self._strLabel
def SetButtonFont(self, font):
"""
Sets the button font.
:param `font`: a valid :class:`Font` object.
"""
self._pButton.SetFont(font)
self.InvalidateBestSize()
self.Layout()
def GetButtonFont(self):
""" Returns the button font. """
return self._pButton.GetFont()
def GetBorder(self):
""" Returns the :class:`PyCollapsiblePane` border in pixels (platform dependent). """
if wx.Platform == "__WXMAC__":
return 6
elif wx.Platform == "__WXGTK__":
return 3
elif wx.Platform == "__WXMSW__":
return self._pButton.ConvertDialogSizeToPixels(wx.Size(2, 0)).x
else:
return 5
def SetExpanderDimensions(self, width, height):
"""
Sets the expander width and height.
:param `width`: an integer specifying the expander width in pixels;
:param `height`: an integer specifying the expander height in pixels.
"""
self._expanderDimensions = width, height
self.InvalidateBestSize()
if self._sz:
self._sz.Layout()
if self._pButton:
self._pButton.Refresh()
def GetExpanderDimensions(self):
"""
Returns the expander dimensions, a tuple of integers representing the
width and height of the expander, in pixels.
"""
return self._expanderDimensions
def DoGetBestSize(self):
"""
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
:note: Overridden from :class:`PyPanel`.
"""
if self.HasAGWFlag(CP_USE_STATICBOX):
# In this case the button is not in the sizer, and the static box
# is not shown when not expanded, so use the size of the button as
# our stating point. But first we'll make sure that it is it's
# best size.
sz = self._pButton.GetBestSize()
self._pButton.SetSize(sz)
bdr = self.GetBorder()
sz += (2*bdr, 2*bdr)
if self.IsExpanded():
# Reset the spacer sizes to be based on the button size
adjustment = 0
if 'wxMac' not in wx.PlatformInfo:
adjustment = -3
self._sz.Children[0].AssignSpacer((1, sz.height/2 + adjustment))
self._contentSizer.Children[0].AssignSpacer((1, sz.height/2))
ssz = self._sz.GetMinSize()
sz.width = max(sz.width, ssz.width)
sz.height = max(sz.height, ssz.height)
else:
# do not use GetSize() but rather GetMinSize() since it calculates
# the required space of the sizer
sz = self._sz.GetMinSize()
# when expanded, we need more space
if self.IsExpanded():
pbs = self._pPane.GetBestSize()
sz.width = max(sz.GetWidth(), pbs.x)
sz.height = sz.y + self.GetBorder() + pbs.y
return sz
def Layout(self):
""" Layout the :class:`PyCollapsiblePane`. """
if not self._pButton or not self._pPane or not self._sz:
return False # we need to complete the creation first!
oursz = self.GetSize()
if self.HasAGWFlag(CP_USE_STATICBOX):
bdr = self.GetBorder()
self._pButton.SetPosition((bdr, bdr))
if self.IsExpanded():
self._pPane.Show()
self._pPane.Layout()
self._pStaticBox.Show()
self._pStaticBox.Lower()
self._pButton.Raise()
self._sz.SetDimension(0, 0, oursz.width, oursz.height)
self._sz.Layout()
else:
if hasattr(self, '_pStaticBox'):
self._pStaticBox.Hide()
else:
# move & resize the button and the static line
self._sz.SetDimension(0, 0, oursz.GetWidth(), self._sz.GetMinSize().GetHeight())
self._sz.Layout()
if self.IsExpanded():
# move & resize the container window
yoffset = self._sz.GetSize().GetHeight() + self.GetBorder()
self._pPane.SetDimensions(0, yoffset, oursz.x, oursz.y - yoffset)
# this is very important to make the pane window layout show correctly
self._pPane.Show()
self._pPane.Layout()
return True
def SetButton(self, button):
"""
Assign a new button to :class:`PyCollapsiblePane`.
:param `button`: can be the standard :class:`Button` or any of the generic
implementations which live in :mod:`lib.buttons`.
"""
if self._pButton:
if not self.HasAGWFlag(CP_USE_STATICBOX):
self._sz.Replace(self._pButton, button)
self.Unbind(wx.EVT_BUTTON, self._pButton)
self._pButton.Destroy()
self._pButton = button
self.SetLabel(button.GetLabel())
self.Bind(wx.EVT_BUTTON, self.OnButton, self._pButton)
if self._pPane:
self._pButton.MoveBeforeInTabOrder(self._pPane)
self.InvalidateBestSize()
self.Layout()
def GetButton(self):
""" Returns the button associated with :class:`PyCollapsiblePane`. """
return self._pButton
#-----------------------------------------------------------------------------
# PyCollapsiblePane - event handlers
#-----------------------------------------------------------------------------
def OnButton(self, event):
"""
Handles the ``wx.EVT_BUTTON`` event for :class:`PyCollapsiblePane`.
:param `event`: a :class:`CommandEvent` event to be processed.
"""
if event.GetEventObject() != self._pButton:
event.Skip()
return
self.Collapse(not self.IsCollapsed())
# this change was generated by the user - send the event
ev = wx.CollapsiblePaneEvent(self, self.GetId(), self.IsCollapsed())
self.GetEventHandler().ProcessEvent(ev)
def OnSize(self, event):
"""
Handles the ``wx.EVT_SIZE`` event for :class:`PyCollapsiblePane`.
:param `event`: a :class:`SizeEvent` event to be processed.
"""
self.Layout()
def OnDrawGTKStyle(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for :class:`PyCollapsiblePane`.
:param `event`: a :class:`PaintEvent` event to be processed.
:note: This is a drawing routine to paint the GTK-style expander.
"""
dc = wx.AutoBufferedPaintDC(self._pButton)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.OnDrawGTKExpander(dc)
self.OnDrawGTKText(dc)
def OnDrawGTKExpander(self, dc):
"""
Overridable method to draw the GTK-style expander.
:param `dc`: an instance of :class:`DC`.
"""
self._pButton.OnDrawGTKExpander(dc)
def OnDrawGTKText(self, dc):
"""
Overridable method to draw the :class:`PyCollapsiblePane` text in the expander.
:param `dc`: an instance of :class:`DC`.
"""
self._pButton.OnDrawGTKText(dc)