File: dialogs.py

package info (click to toggle)
psychopy 2020.2.10%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 44,056 kB
  • sloc: python: 119,649; javascript: 3,022; makefile: 148; sh: 125; xml: 9
file content (643 lines) | stat: -rw-r--r-- 24,217 bytes parent folder | download
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This is for general purpose dialogs/widgets, not particular functionality

MessageDialog:
    a drop-in replacement for wx message dialog (which was buggy on mac)
GlobSizer:
    built on top of GridBagSizer but with ability to add/remove
    rows. Needed for the ListWidget
ListWidget:
    takes a list of dictionaries (with identical fields) and allows
    the user to add/remove entries. e.g. expInfo control
"""

from __future__ import absolute_import, print_function

from builtins import str
from builtins import range
import wx
from wx.lib.newevent import NewEvent

from psychopy import logging
from psychopy.localization import _translate
from pkg_resources import parse_version


class MessageDialog(wx.Dialog):
    """For some reason the wx built-in message dialog has issues on macOS
    (buttons don't always work) so we need to use this instead.
    """

    def __init__(self, parent=None, message='', type='Warning', title=None,
                 timeout=None):
        # select and localize a title
        if not title:
            title = type
        labels = {'Warning': _translate('Warning'),
                  'Info': _translate('Info'),
                  'Query': _translate('Query')}
        try:
            label = labels[title]
        except Exception:
            label = title
        wx.Dialog.__init__(self, parent, -1, title=label)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(self, -1, message), flag=wx.ALL, border=15)
        # add buttons
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        if type == 'Warning':  # we need Yes,No,Cancel
            self.yesBtn = wx.Button(self, wx.ID_YES, _translate('Yes'))
            self.yesBtn.SetDefault()
            self.cancelBtn = wx.Button(
                self, wx.ID_CANCEL, _translate('Cancel'))
            self.noBtn = wx.Button(self, wx.ID_NO, _translate('No'))
            self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_CANCEL)
            self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_YES)
            self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_NO)
#            self.Bind(wx.EVT_CLOSE, self.onEscape)
            btnSizer.Add(self.noBtn, 0,
                         wx.ALL | wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
                         border=3)
            btnSizer.AddStretchSpacer()
            btnSizer.Add(self.cancelBtn, 0,
                         wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                         border=3)
            btnSizer.Add(self.yesBtn, 0,
                         wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                         border=3)
        elif type == 'Query':  # we need Yes,No
            self.yesBtn = wx.Button(self, wx.ID_YES, _translate('Yes'))
            self.yesBtn.SetDefault()
            self.noBtn = wx.Button(self, wx.ID_NO, _translate('No'))
            self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_YES)
            self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_NO)
#            self.Bind(wx.EVT_CLOSE, self.onEscape)
            btnSizer.Add(self.noBtn, 0,
                         wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                         border=3)
            btnSizer.Add(self.yesBtn, 0,
                         wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                         border=3)
        elif type == 'Info':  # just an OK button
            self.okBtn = wx.Button(self, wx.ID_OK, _translate('OK'))
            self.okBtn.SetDefault()
            self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_OK)
            btnSizer.Add(self.okBtn, 0,
                         wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                         border=3)
        else:
            raise NotImplementedError('Message type %s unknown' % type)
        # configure sizers and fit
        sizer.Add(btnSizer,
                  flag=wx.ALL | wx.EXPAND, border=5)
        self.Center()
        self.SetSizerAndFit(sizer)
        self.timeout = timeout

    def onButton(self, event):
        self.EndModal(event.GetId())

    def onEscape(self, event):
        self.EndModal(wx.ID_CANCEL)

    def onEnter(self, event=None):
        self.EndModal(wx.ID_OK)

    def ShowModal(self):
        if self.timeout:
            timeout = wx.CallLater(self.timeout, self.onEnter)
            timeout.Start()
        return wx.Dialog.ShowModal(self)

# Event for GlobSizer-----------------------------------------------------
(GBSizerExLayoutEvent, EVT_GBSIZEREX_LAYOUT) = NewEvent()


class GlobSizer(wx.GridBagSizer):
    """This is a GridBagSizer that supports adding/removing/inserting rows and
    columns. It was found online, with not clear use license (public domain?).
    Appears to have been written by e.a.tacao <at> estadao.com.br
    """

    def __init__(self, *args, **kwargs):
        self.win = kwargs.pop("win", None)
        # This is here because we need to be able to find out whether a
        # row/col is growable. We also override the AddGrowableRow/Col and
        # RemoveGrowableRow/Col methods, as well as create new methods to
        # handle growable row/cols.
        self.growableRows = {}
        self.growableCols = {}
        wx.GridBagSizer.__init__(self, *args, **kwargs)

    def _resetSpan(self):
        # Unspans all spanned items; returns a reference to objects.
        objs = {}
        for item in self.GetChildren():
            span = item.GetSpan().Get()
            if span != (1, 1):
                objs[item.GetWindow()] = span
                item.SetSpan((1, 1))
        return objs

    def _setSpan(self, objs):
        # Respans all items containing the given objects.
        for obj, span in list(objs.items()):
            if obj:
                self.FindItem(obj).SetSpan(span)

    def GetClassName(self):
        return "GlobSizer"

    def GetAttributes(self):
        gap = self.GetGap()
        ecs = self.GetEmptyCellSize().Get()
        grows = self.GetGrowableRows()
        gcols = self.GetGrowableCols()
        return (gap, ecs, grows, gcols)

    def SetAttributes(self, attrs):
        gap, ecs, grows, gcols = attrs
        self.SetGap(gap)
        self.SetEmptyCellSize(ecs)
        [self.AddGrowableRow(row) for row in grows]
        [self.AddGrowableCol(col) for col in gcols]

    def Layout(self):
        wx.GridBagSizer.Layout(self)
        if self.win:
            wx.PostEvent(self.win, GBSizerExLayoutEvent(val=True))

    def SetGap(self, gap=(0, 0)):
        v, h = gap
        self.SetVGap(v)
        self.SetHGap(h)

    def GetGap(self):
        return self.GetVGap(), self.GetHGap()

    def AddGrowableRow(self, *args, **kwargs):
        idx = kwargs.get("idx", args[0])
        if not self.IsRowGrowable(idx):
            proportion = kwargs.get("proportion", (args + (0,))[1])
            self.growableRows[idx] = proportion
            wx.GridBagSizer.AddGrowableRow(self, idx, proportion)

    def AddGrowableCol(self, *args, **kwargs):
        idx = kwargs.get("idx", args[0])
        if not self.IsColGrowable(idx):
            proportion = kwargs.get("proportion", (args + (0,))[1])
            self.growableCols[idx] = proportion
            wx.GridBagSizer.AddGrowableCol(self, idx, proportion)

    def RemoveGrowableRow(self, idx):
        if self.IsRowGrowable(idx):
            del self.growableRows[idx]
            wx.GridBagSizer.RemoveGrowableRow(self, idx)

    def RemoveGrowableCol(self, idx):
        if self.IsColGrowable(idx):
            del self.growableCols[idx]
            wx.GridBagSizer.RemoveGrowableCol(self, idx)

    def IsRowGrowable(self, idx):
        return idx in self.growableRows

    def IsColGrowable(self, idx):
        return idx in self.growableCols

    def GetGrowableRows(self):
        grows = list(self.growableRows.keys())
        grows.sort()
        return grows

    def GetGrowableCols(self):
        gcols = list(self.growableCols.keys())
        gcols.sort()
        return gcols

    def FindUnspannedItemAtPosition(self, *args, **kwargs):
        # FindItemAtPosition(r, c) will return a valid spanned item
        # even if (r, c) is not its top-left position. This method will only
        # return a valid item (spanned or not*) if the position passed is the
        # top-left. (*As for unspanned items, obviously it'll always return a
        # valid item).
        item = self.FindItemAtPosition(*args, **kwargs)
        if item:
            if item.GetSpan().Get() > (1, 1):
                if item.GetPos() == kwargs.get("pos", args[0]):
                    r = item
                else:
                    r = None
            else:
                r = item
        else:
            r = None
        return r

    def GetItemPositions(self, *args, **kwargs):
        # Returns all positions occupied by a spanned item, as GetItemPosition
        # only returns its top-left position.
        row, col = self.GetItemPosition(*args, **kwargs).Get()
        rspan, cspan = self.GetItemSpan(*args, **kwargs).Get()
        return [(row + r, col + c)
                for r, c in [(r, c) for r in range(0, rspan)
                             for c in range(0, cspan)]]

    def InsertRow(self, row):
        # As for the vertically spanned objects in the given row,
        # we'll need to respan them later with an increased row span
        # (increased by 1 row).
        # 1. Get a reference of the vertically spanned objects on this row and
        #    their span, incrementing their row span by 1.
        _update_span = {}
        for c in range(0, self.GetCols()):
            item = self.FindItemAtPosition((row, c))
            if item:
                rs, cs = item.GetSpan().Get()
                if rs > 1 and item.GetPos().GetRow() != row:
                    _update_span[item.GetWindow()] = (rs + 1, cs)
        # 2. Unspan all objects.
        objs = self._resetSpan()
        # 3. Shift rows down.
        self.ShiftRowsDown(row)
        # 4. Respan all objects.
        objs.update(_update_span)
        self._setSpan(objs)
        # 5. Update references to growable rows.
        grows = list(self.growableRows.keys())
        for r in grows:
            if r >= row:
                self.RemoveGrowableRow(r)
                self.AddGrowableRow(r + 1)

    def InsertCol(self, col):
        # As for the horizontally spanned objects in the given col,
        # we'll need to respan them later with an increased col span
        # (increased by 1 col).
        # 1. Get a reference of the horizontally spanned objects on this col
        #    and their span, incrementing their col span by 1.
        _update_span = {}
        for r in range(0, self.GetRows()):
            item = self.FindItemAtPosition((r, col))
            if item:
                rs, cs = item.GetSpan().Get()
                if cs > 1 and item.GetPos().GetCol() != col:
                    _update_span[item.GetWindow()] = (rs, cs + 1)
        # 2. Unspan all objects.
        objs = self._resetSpan()
        # 3. Shift cols right.
        self.ShiftColsRight(col)
        # 4. Respan all objects.
        objs.update(_update_span)
        self._setSpan(objs)
        # 5. Update references to growable cols.
        gcols = list(self.growableCols.keys())
        for c in gcols:
            if c >= col:
                self.RemoveGrowableCol(c)
                self.AddGrowableCol(c + 1)

    def DeleteRow(self, row):
        """Deletes an entire row, destroying its objects (if any).
        """
        # As for the vertically spanned objects in the given row,
        # we'll need to move them somewhere safe (so that their objects
        # won't be destroyed as we destroy the row itself) and respan
        # them later with a reduced row span (decreased by 1 row).
        # 1. Get a reference of the vertically spanned objects on this row and
        #    their span, decrementing their row span by 1.
        _update_span = {}
        for c in range(0, self.GetCols()):
            item = self.FindItemAtPosition((row, c))
            if item:
                rs, cs = item.GetSpan().Get()
                if rs > 1:
                    _update_span[item.GetWindow()] = (rs - 1, cs)
        # 2. Unspan all objects.
        objs = self._resetSpan()
        # 3. Move the _update_span objects to an adjacent row somewhere safe.
        for obj in _update_span:
            item = self.FindItem(obj)
            org_r, org_c = item.GetPos().Get()
            if org_r == row:
                item.SetPos((org_r + 1, org_c))
        # 4. Destroy all objects on this row.
        for c in range(0, self.GetCols()):
            item = self.FindItemAtPosition((row, c))
            if item:
                obj = item.GetWindow()
                self.Detach(obj)
                obj.Destroy()
        # 5. Shift rows up.
        self.ShiftRowsUp(row + 1)
        # 6. Respan all objects.
        objs.update(_update_span)
        self._setSpan(objs)
        # 7. Update references to growable rows.
        grows = list(self.growableRows.keys())
        for r in grows:
            if r >= row:
                self.RemoveGrowableRow(r)
                if r > row:
                    self.AddGrowableRow(r - 1)

    def DeleteCol(self, col):
        """Deletes an entire col, destroying its objects (if any)."""
        # As for the horizontally spanned objects in the given col,
        # we'll need to move them somewhere safe (so that their objects
        # won't be destroyed as we destroy the row itself) and respan
        # them later with a reduced col span (decreased by 1 col).
        # 1. Get a reference of the horizontally spanned objects on this col
        #    and their span, decrementing their col span by 1.
        _update_span = {}
        for r in range(0, self.GetRows()):
            item = self.FindItemAtPosition((r, col))
            if item:
                rs, cs = item.GetSpan().Get()
                if cs > 1:
                    _update_span[item.GetWindow()] = (rs, cs - 1)
        # 2. Unspan all objects.
        objs = self._resetSpan()
        # 3. Move the _update_span objects to an adjacent col somewhere safe.
        for obj in _update_span:
            item = self.FindItem(obj)
            org_r, org_c = item.GetPos().Get()
            if org_c == col:
                item.SetPos((org_r, org_c + 1))
        # 4. Destroy all objects on this col.
        for r in range(0, self.GetRows()):
            item = self.FindItemAtPosition((r, col))
            if item:
                obj = item.GetWindow()
                self.Detach(obj)
                obj.Destroy()
        # 5. Shift cols left.
        self.ShiftColsLeft(col + 1)
        # 6. Respan all objects.
        objs.update(_update_span)
        self._setSpan(objs)
        # 7. Update references to growable cols.
        gcols = list(self.growableCols.keys())
        for c in gcols:
            if c >= col:
                self.RemoveGrowableCol(c)
                if c > col:
                    self.AddGrowableCol(c - 1)

    def ShiftRowsUp(self, startRow, endRow=None, startCol=None,
                    endCol=None):
        if endCol is None:
            endCol = self.GetCols()
        else:
            endCol += 1
        if endRow is None:
            endRow = self.GetRows()
        else:
            endRow += 1
        if startCol is None:
            startCol = 0
        for c in range(startCol, endCol):
            for r in range(startRow, endRow):
                item = self.FindItemAtPosition((r, c))
                if item:
                    w = item.GetWindow()
                    if w:
                        self.SetItemPosition(w, (r - 1, c))
                        w.Refresh()

    def ShiftRowsDown(self, startRow, endRow=None, startCol=None,
                      endCol=None):

        if endCol is None:
            endCol = self.GetCols()
        else:
            endCol += 1
        if endRow is None:
            endRow = self.GetRows()
        else:
            endRow += 1
        if startCol is None:
            startCol = 0
        for c in range(startCol, endCol):
            for r in range(endRow, startRow, -1):
                item = self.FindItemAtPosition((r, c))
                if item:
                    w = item.GetWindow()
                    if w:
                        self.SetItemPosition(w, (r + 1, c))
                        w.Refresh()

    def ShiftColsLeft(self, startCol, endCol=None, startRow=None,
                      endRow=None):
        if endCol is None:
            endCol = self.GetCols()
        else:
            endCol += 1
        if endRow is None:
            endRow = self.GetRows()
        else:
            endRow += 1
        if startRow is None:
            startRow = 0
        for r in range(startRow, endRow):
            for c in range(startCol, endCol):
                item = self.FindItemAtPosition((r, c))
                if item:
                    w = item.GetWindow()
                    if w:
                        self.SetItemPosition(w, (r, c - 1))
                        w.Refresh()

    def ShiftColsRight(self, startCol, endCol=None, startRow=None,
                       endRow=None):
        if endCol is None:
            endCol = self.GetCols()
        else:
            endCol += 1
        if endRow is None:
            endRow = self.GetRows()
        else:
            endRow += 1
        if startRow is None:
            startRow = 0
        for r in range(startRow, endRow):
            for c in range(endCol, startCol - 1, -1):
                item = self.FindItemAtPosition((r, c))
                if item:
                    w = item.GetWindow()
                    if w:
                        self.SetItemPosition(w, (r, c + 1))
                        w.Refresh()

    def DeleteEmptyRows(self):
        rows2delete = []
        for r in range(0, self.GetRows()):
            f = True
            for c in range(0, self.GetCols()):
                if self.FindItemAtPosition((r, c)) is not None:
                    f = False
            if f:
                rows2delete.append(r)
        for i in range(0, len(rows2delete)):
            self.ShiftRowsUp(rows2delete[i] + 1)
            rows2delete = [x - 1 for x in rows2delete]

    def DeleteEmptyCols(self):
        cols2delete = []
        for c in range(0, self.GetCols()):
            f = True
            for r in range(0, self.GetRows()):
                if self.FindItemAtPosition((r, c)) is not None:
                    f = False
            if f:
                cols2delete.append(c)
        for i in range(0, len(cols2delete)):
            self.ShiftColsLeft(cols2delete[i] + 1)
            cols2delete = [x - 1 for x in cols2delete]

    def Insert(self, *args, **kwargs):
        # Uses the API for the Add method, plus a kwarg named shiftDirection,
        # which controls whether rows should be shifted down (shiftDirection =
        # wx.VERTICAL) or left (shiftDirection = wx.HORIZONTAL).
        #
        # That kwarg is just a hint and won't force shifting; shifting
        # will only take place if the position passed is already occupied by
        # another control.
        #
        pos = kwargs.get("pos", args[1])
        shiftDirection = kwargs.pop("shiftDirection", wx.VERTICAL)
        if not self.FindItemAtPosition(pos):
            self.Add(*args, **kwargs)
        else:
            objs = self._resetSpan()
            r, c = pos
            if shiftDirection == wx.HORIZONTAL:
                self.ShiftColsRight(c, startRow=r, endRow=r)
            else:
                self.ShiftRowsDown(r, startCol=c, endCol=c)
            self.Add(*args, **kwargs)
            self._setSpan(objs)
        self.Layout()


class ListWidget(GlobSizer):
    """A widget for handling a list of dicts of identical structure.
    Has one row per entry and a +/- buttons at end to add/insert/remove from
    the list
    """

    def __init__(self, parent, value=None, order=None):
        """value should be a list of dictionaries with identical field names

        order should be used to specify the order in which the fields appear
        (left to right)
        """
        GlobSizer.__init__(self, hgap=2, vgap=2)
        self.parent = parent
        self.value = value if value else [{"Field":"", "Default": ""}]
        if type(value) != list:
            msg = 'The initial value for a ListWidget must be a list of dicts'
            raise AttributeError(msg)
        # sort fieldNames using order information where possible
        allNames = list(self.value[0].keys())
        self.fieldNames = []
        if order is None:
            order = []
        for name in order:
            if name not in allNames:
                msg = ('psychopy.dialogs.ListWidget was given a field name '
                       '`%s` in order that was not in the dictionary')
                logging.error(msg % name)
                continue
            allNames.remove(name)
            self.fieldNames.append(name)
        # extend list by the remaining (no explicit order)
        self.fieldNames.extend(allNames)
        # set up controls
        self.createGrid()
        self.AddGrowableCol(0)
        self.AddGrowableCol(1)

    def createGrid(self):
        row = 0
        if len(self.fieldNames) > 0:
            for col, field in enumerate(self.fieldNames):
                self.Add(wx.StaticText(self.parent, -1, label=_translate(field)),
                         (row, col), flag=wx.ALL)
            for entry in self.value:
                row += 1
                self.addEntryCtrls(row, entry)
        self.Layout()

    def addEntryCtrls(self, row, entry):
        for col, field in enumerate(self.fieldNames):
            c = wx.TextCtrl(self.parent, -1, str(entry[field]))
            self.Add(c, (row, col), flag=wx.ALL | wx.EXPAND)
        plusBtn = wx.Button(self.parent, -1, '+', style=wx.BU_EXACTFIT)
        self.Add(plusBtn, (row, col + 1), flag=wx.ALL)
        plusBtn.Bind(wx.EVT_BUTTON, self.onAddElement)
        minusBtn = wx.Button(self.parent, -1, '-', style=wx.BU_EXACTFIT)
        self.Add(minusBtn, (row, col + 2), flag=wx.ALL)
        minusBtn.Bind(wx.EVT_BUTTON, self.onRemoveElement)

    def onAddElement(self, event):
        """The plus button has been pressed
        """
        btn = self.FindItem(event.GetEventObject())
        row, col = btn.GetPos()
        self.InsertRow(row)
        newEntry = {}
        for fieldName in self.fieldNames:
            newEntry[fieldName] = ""
        self.addEntryCtrls(row + 1, newEntry)
        self.Layout()
        self.parent.Fit()

    def onRemoveElement(self, event=None):
        """Called when the minus button is pressed.
        """
        btn = self.FindItem(event.GetEventObject())
        row, col = btn.GetPos()
        self.DeleteRow(row)
        self.Layout()
        self.parent.Fit()

    def getListOfDicts(self):
        """Retrieve the current list of dicts from the grid
        """
        currValue = []
        # skipping the first row (headers)
        for rowN in range(self.GetRows())[1:]:
            thisEntry = {}
            for colN, fieldName in enumerate(self.fieldNames):
                ctrl = self.FindItemAtPosition((rowN, colN)).GetWindow()
                thisEntry[fieldName] = ctrl.GetValue()
            currValue.append(thisEntry)
        return currValue

    def GetValue(self):
        """Provided for compatibility with other wx controls. Returns the
        current value of the list of dictionaries represented in the grid
        """
        return self.getListOfDicts()

    def SetToolTipString(self, tip):
        """This isn't implemented yet.
        Set every control to have the same tooltip?
        """
        pass


if __name__ == '__main__':
    if parse_version(wx.__version__) < parse_version('2.9'):
        app = wx.PySimpleApp()
    else:
        app = wx.App(False)
    dlg = wx.Dialog(None)
    init = [{'Field': 'Participant', 'Default': ''},
            {'Field': 'Session', 'Default': '001'}]
    listCtrl = ListWidget(dlg, value=init, order=['Field', 'Default'])
    dlg.SetSizerAndFit(listCtrl)
    dlg.ShowModal()