-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScopePy_widgets.py
More file actions
2963 lines (2050 loc) · 86 KB
/
ScopePy_widgets.py
File metadata and controls
2963 lines (2050 loc) · 86 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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 17 21:11:38 2014
@author: john
"""
#==============================================================================
#%% License
#==============================================================================
"""
Copyright 2015 John Bainbridge
This file is part of ScopePy.
ScopePy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScopePy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ScopePy. If not, see <http://www.gnu.org/licenses/>.
"""
#=============================================================================
#%% Imports
#=============================================================================
import logging
import copy
import sqlite3
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from widgets.color import *
import numpy as np
#import pyqtgraph as pg
import ScopePy_channel as ch
import ScopePy_colours_and_shapes as col_shapes
#import mandatory as manargs
#==============================================================================
#%% Logger
#==============================================================================
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Add do nothing handler
logger.addHandler(logging.NullHandler())
# create console handler and set level to debug
con = logging.StreamHandler()
con.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('[%(asctime)s:%(name)s:%(levelname)s]: %(message)s')
# add formatter to ch
con.setFormatter(formatter)
# add ch to logger
logger.addHandler(con)
#=============================================================================
#%% Constants
#=============================================================================
DEBUG = False
# TODO : Centralise colours and styles somewhere and make it modular
# enough that they could be customised in the future.
lineColours = col_shapes.COLOURS
lineStyles = [Qt.SolidLine, Qt.DashLine, Qt.DashDotLine, Qt.DashDotDotLine, Qt.NoPen]
# Symbols - adapted from pyqtgraph
Symbols = col_shapes.make_markers()
#=============================================================================
#%% New legendline alternative
#=============================================================================
class legendDialog(QDialog):
def __init__(self,parent=None):
"""
Newer version of LegendLine, this dialog is to be used like this:
>>>form = legendDialog()
>>>if form.exec_():
... print('linestyle:',form.lineStyle)
>>>"""
super(legendDialog,self).__init__(parent)
self.setWindowTitle('LineStyle Selector Dialog')
mh = QVBoxLayout()
self.stack = QStackedWidget()
mh.addWidget(self.stack)
bl = QVBoxLayout()
p1 = QPushButton('>>')
p1.clicked.connect(self.forward)
p2 = QPushButton('<<')
p2.clicked.connect(self.backward)
p3 = QPushButton('Done')
p3.clicked.connect(self.donePressed)
bl.addWidget(p1)
bl.addWidget(p3)
bl.addWidget(p2)
mh.addLayout(bl)
self.setLayout(mh)
self.markerSelect()
self.lineselect()
self.outline()
self.stack.setCurrentIndex(0)
def markerSelect(self):
mw = QWidget()
l = QVBoxLayout()
label = QLabel('Please Select a type of marker, then select a color for the fill of the marker')
#l.addWidget(l)
self.markcombo = QComboBox()
self.markcombo.addItems(['dot','square','circle','triangle','cross'])
self.fillcolor = colorpicker()
l.addWidget(label)
l.addWidget(self.markcombo)
l.addWidget(self.fillcolor)
mw.setLayout(l)
self.stack.addWidget(mw)
def lineselect(self):
mw = QWidget()
l = QVBoxLayout(self)
label = QLabel('Select a color for the lines')
self.linecolor = colorpicker()
l.addWidget(label)
l.addWidget(self.linecolor)
mw.setLayout(l)
self.stack.addWidget(mw)
def outline(self):
mw = QWidget()
l = QVBoxLayout(self)
label = QLabel('Select a color for the outline of the marker')
self.outcolor = colorpicker()
l.addWidget(label)
l.addWidget(self.outcolor)
mw.setLayout(l)
self.stack.addWidget(mw)
def forward(self):
index = self.stack.currentIndex()
tobe = index+1
if tobe == 3:
tobe = 0
self.stack.setCurrentIndex(tobe)
def backward(self):
index = self.stack.currentIndex()
tobe = index-1
if tobe < 0:
tobe = 2
self.stack.setCurrentIndex(tobe)
def getMarkerType(self):
txt = self.markcombo.currentText()
if txt == 'dot':
return '.'
elif txt == 'square':
return 's'
elif txt == 'triangle':
return '^'
elif txt == 'circle':
return 'c'
elif txt == 'cross':
return 'x'
def donePressed(self):
self.lineStyle = ch.plotLineStyle(lineColour=self.linecolor.name,marker=self.getMarkerType(),
markerColour=self.outcolor.name,markerFillColour=self.fillcolor.name)
self.accept()
#=============================================================================
#%% legendLine widget class definition
#=============================================================================
class legendLine(QWidget):
""" Legend line/marker display item
Displays a line with a marker, for inserting into legends or tables
Allows changing of the colour, line style and shape of the line and the
marker by selecting either and rolling the mouse wheel over them.
Actions are:
Left button click - select line or marker
Line options:
roll wheel with no keys held down to change the line colour
roll wheel with Ctrl key held down to change line style
Marker options
roll wheel with no keys to change colour
roll wheel with Ctrl key down to change the marker shape
"""
def __init__(self, parent=None,lineColour='#ff0000',
markerColour = '#0000ff',
markerFillColour='#ff00ff',
lineStyle = Qt.SolidLine):
super(legendLine, self).__init__(parent)
# selected flag
self.selected = False
self.changed = False
# Physical lengths in pixels
self.minBoxWidth_px = 40
self.minBoxHeight_px = 10
# Logical lengths
self.LogicalWidth = 40.0
self.LogicalHeight = 8
# Line
self.lineLength_lg = 30
self.lineWidth = 1
# Symbol/Marker
self.marker = 'o'
self.markerSize = 7
self.markerScalingFactor = 2
# Selection criteria
self.lineSelectionTolerance_lg = 5
self.lineSelected = False
self.markerSelected = False
# Colours & styles
self.lineColour = lineColour
self.lineColourList = incrementer(lineColours)
self.lineDashStyle = lineStyle
self.lineDashStyleList = incrementer(lineStyles)
self.markerColour = markerColour
self.markerColourList = incrementer(lineColours)
self.markerFillColour = markerFillColour
self.markerFillColourList = incrementer(lineColours)
self.markerList = incrementer(list(Symbols.keys()))
# Sizing
self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,
QSizePolicy.Fixed))
#self.setMinimumSize(self.minimumSizeHint())
# Focus
self.setFocusPolicy(Qt.WheelFocus)
self.setMouseTracking(True)
# Status bar function
self.setStatusTip( "Click on line or marker, roll mouse wheel to change colour, CTRL+Mouse wheel to change shape, SHIFT + Mouse wheel to change marker outline colour")
# Tool tip
self.setToolTip("Line styles - double click or F2 to edit")
self.update()
def setLineStyles(self,lineStyleObject):
""" Set all line colours and styles in one shot using a
container such as the plotLineStyle class in ScopePy_channels.
This is a convenience function for other parts of ScopePy
Input
---------
lineStyleObject = object with attributes:
lineColour
lineDashStyle
marker
markerColour
markerFillColour
"""
self.lineColour = lineStyleObject.lineColour
self.lineDashStyle = lineStyleObject.lineDashStyle
self.markerColour = lineStyleObject.markerColour
self.marker = lineStyleObject.marker
self.markerFillColour = lineStyleObject.markerFillColour
self.update()
def getLineStyles(self):
""" Return all line colours and styles in one shot using a
container such as the plotLineStyle class in ScopePy_channels.
This is a convenience function for other parts of ScopePy
Output
---------
lineStyleObject = object with attributes:
lineColour
lineDashStyle
marker
markerColour
markerFillColour
"""
lineStyleObject = ch.plotLineStyle()
lineStyleObject.lineColour = self.lineColour
lineStyleObject.lineDashStyle = self.lineDashStyle
lineStyleObject.markerColour = self.markerColour
lineStyleObject.marker = self.marker
lineStyleObject.markerFillColour = self.markerFillColour
return lineStyleObject
# Setup lineStyle as a property
lineStyles = property(fget = getLineStyles, fset = setLineStyles)
def getSelectionStatus(self):
""" Returns the selection status of the line and marker items
Outputs
---------
(isLineSelected,isMarkerSelected) = boolean tuple
"""
return (self.lineSelected,self.markerSelected)
def setSelectionStatus(self,selectionFlags):
""" Convenience function for delegates
Sets the selected flags in one shot from outside
Inputs
---------
(isLineSelected,isMarkerSelected) = boolean tuple
TODO : May not need this
"""
(self.lineSelected,self.markerSelected) = selectionFlags
self.update()
selectionStatus = property(fget = getSelectionStatus, fset = setSelectionStatus)
def sizeHint(self):
return self.minimumSizeHint()
def minimumSizeHint(self):
return QSize(self.minBoxHeight_px,self.minBoxHeight_px)
def mousePressEvent(self,event):
""" Mouse clicked over widget
Check if the line was clicked
"""
if event.button() == Qt.LeftButton:
# Check mouse coordinates
# Convert from pixels to logical coordinates
x_lg,y_lg = self.pix2logical(event.x(),event.y())
# Define rectangle for line
lineRect = QRectF(-self.lineLength_lg/2,
-self.lineSelectionTolerance_lg,
self.lineLength_lg,
2*self.lineSelectionTolerance_lg)
# Define rectangle for marker
markerRect = QRectF(-2.0,-2.0,4.0,4.0)
if DEBUG:
print("--------------------\nMarker selection rectangle")
print(markerRect)
print('Mouse clicked at point:')
print(QPointF(x_lg,y_lg))
print("--------------------\n")
# Check if mouse was clicked on the marker
if markerRect.contains(QPointF(x_lg,y_lg)):
self.markerSelected = not self.markerSelected
if self.lineSelected == True:
self.lineSelected = False
# Check if click was on the line
#if abs(y_lg -self.lineY_lg) <= self.lineSelectionTolerance_lg:
elif lineRect.contains(QPointF(x_lg,y_lg)):
# invert the selected state if line was clicked on
self.lineSelected = not self.lineSelected
if self.markerSelected == True:
self.markerSelected = False
else:
self.lineSelected = False
self.markerSelected = False
self.update()
event.accept()
elif event.button() == Qt.RightButton:
# Dump line styles to console
print(self.lineStyles)
else:
QWidget.mousePressEvent(self,event)
def wheelEvent(self,event):
""" Mouse wheel turned over widget
If mouse is over line or marker and the wheel is turning then
change the colour, line style or shape
See main class for the actions
"""
# Get how much the wheel has turned
numDegrees = event.delta()/8
numSteps = numDegrees/15
direction = np.sign(numSteps)
# Get any keyboard modifiers
modifiers = event.modifiers()
# Change colours and styles according to what's selected
# emit signals to tell other objects that the colours have changed
if self.lineSelected and modifiers==Qt.NoModifier : # TODO : Put check on mouse coordinates as well
self.lineColour = self.lineColourList.getNextItem(direction)
self.changed = True
event.accept()
if self.lineSelected and modifiers==Qt.ControlModifier :
self.lineDashStyle = self.lineDashStyleList.getNextItem(direction)
self.changed = True
event.accept()
elif self.markerSelected and modifiers==Qt.ControlModifier:
self.marker = self.markerList.getNextItem(direction)
self.changed = True
event.accept()
elif self.markerSelected and modifiers==Qt.ShiftModifier:
self.markerColour = self.markerColourList.getNextItem(direction)
self.changed = True
event.accept()
elif self.markerSelected and modifiers==Qt.NoModifier:
self.markerFillColour = self.markerFillColourList.getNextItem(direction)
self.changed = True
event.accept()
else:
#QWidget.wheelEvent(self,event)
event.ignore()
self.update()
def focusOutEvent(self,event):
""" When focus is lost, de-select everything and update
This works!
"""
if DEBUG:
print('\n+++++++++++++++++++++++++++++++++++++++++++')
print("lineLegend has lost focus")
print("+++++++++++++++++++++++++++++++++++++++++++\n")
self.lineSelected = False
self.markerSelected = False
self.update()
self.leaveEvent(event)
def leaveEvent(self,event):
"""
signal end of editing
"""
# Not exactly sure what to do with event, but it must be there
# otherwise an error occurs
if self.changed:
self.emit(SIGNAL("LegendLineChanged"))
else:
self.emit(SIGNAL("LegendLineEditFinished"))
def paintEvent(self, event=None):
# Setup painter object
# =================================
painter = QPainter(self)
if DEBUG:
print("\n-------------------------------------")
print("legendLine : paintEvent method")
print("-------------------------------------\n")
# sub contract to paint function
self.paint(painter)
def paint(self,painter,rect=None,selected=False):
noRect = False # TODO : Temporary
if not rect:
noRect = True
rect = QRect(0,0,self.width(),self.height())
# Aspect ratio conversion factor
# =============================================
# multiply a vertical length by this to get the equivalent
# number of pixels to the same distance in the horizontal plane
pixConv = self.LogicalHeight*rect.width()/(self.LogicalWidth*rect.height())
if DEBUG:
print("\n-------------------------------------")
print("legendLine : paint method")
print("Pixel to logical = %0.4f" % pixConv)
print("\nself.width = %d, self.height = %d" % (self.width(),self.height()))
print("\nLegend line self rectangle")
print(self.rect())
print("\nSupplied rectangle:")
print(rect)
if noRect:
print("<<< No rect supplied - using default>>>")
print("-------------------------------------\n")
# Setup painter
# ========================
painter.setRenderHint(QPainter.Antialiasing)
#painter.setViewport(0,0,self.width(),self.height())
painter.setViewport(rect)
painter.setWindow(-self.LogicalWidth/2, -self.LogicalHeight/2, self.LogicalWidth, self.LogicalHeight)
palette = QApplication.palette()
handleColour = palette.highlight().color()
backgroundColour = palette.background().color() if selected else Qt.black #palette.base().color()
# Background
# =========================
pen = QPen(Qt.SolidLine)
pen.setWidth(1)
pen.setColor(backgroundColour)
painter.setPen(pen)
painter.setBrush(backgroundColour)
painter.drawRect(-self.LogicalWidth/2, -self.LogicalHeight/2, self.LogicalWidth, self.LogicalHeight)
# Line
# ========================================================
# Setup pen colours for line and draw it
# ------------------------------------------
pen = QPen(self.lineDashStyle)
pen.setWidth(self.lineWidth)
lineColour = QColor()
#logger.debug("legendLine:Paint: Line colour = %s" % self.lineColour)
lineColour.setNamedColor(self.lineColour)
pen.setColor(lineColour)
painter.setPen(pen)
# Draw the line
painter.drawLine(-self.lineLength_lg/2,0,self.lineLength_lg/2,0)
# Handle line selection
# -----------------------------------
# If line is selected draw some handles
if self.lineSelected:
pen = QPen(Qt.SolidLine)
pen.setWidth(1)
pen.setColor(handleColour)
painter.setPen(pen)
painter.setBrush(handleColour)
# Set radius
# Horizontal dimension of the handles
radius = 1
# Handle at start of line
rs = QPoint(-self.lineLength_lg/2,0)
painter.drawEllipse(rs,radius,radius*pixConv)
# Handle at start of line
re = QPoint(self.lineLength_lg/2,0)
painter.drawEllipse(re,radius,radius*pixConv)
# Symbol
# ========================================================
# Scale to make the marker a constant size in pixels
# logical marker width = pixel width*logical widget width/actual pixel width
# and the same for height
xscale = self.markerSize*self.LogicalWidth/rect.width()
yscale = self.markerSize*self.LogicalHeight/rect.height()
# Colours and lines
pen = QPen(Qt.SolidLine)
pen.setWidth(0)
markerColour = QColor()
markerColour.setNamedColor(self.markerColour)
pen.setColor(markerColour)
markerFillColour = QColor()
markerFillColour.setNamedColor(self.markerFillColour)
brush = QBrush(markerFillColour)
painter.setPen(pen)
painter.setBrush(brush)
# Convert marker text symbol to a path
markerPath = Symbols[self.marker] #.translated(symbolOrigin)
# Draw the symbol, scaled up
painter.save() # Store the state
tr = QTransform() # Transform coordinate system
tr.scale(xscale,yscale) # Scale marker to constant pixel size
finalPath = tr.map(markerPath)
painter.drawPath(finalPath)
if self.markerSelected:
# Draw Handle line on marker
pen = QPen(Qt.DashLine)
pen.setWidth(0)
pen.setColor(handleColour)
painter.setPen(pen)
painter.setBrush(Qt.NoBrush)
markerHandleRect = QRectF(-4.5,-4.5*pixConv,9.0,9.0*pixConv)
print(markerHandleRect)
painter.drawRect(markerHandleRect)
painter.restore()
def pix2logical(self,x_px,y_px):
""" Convert pixel coordinates to logical coordinates
x_lg,y_lg = self.pix2logical(x_px,y_px)
"""
x_lg = round( x_px*self.LogicalWidth/self.width() - self.LogicalWidth/2 )
y_lg = round( y_px*self.LogicalHeight/self.height() - self.LogicalHeight/2)
return x_lg,y_lg
def logical2pix(self,x_lg,y_lg):
""" Convert logical coordinates to pixel coordinates
x_px,y_px = logical2pix(x_lg,y_lg)
"""
# TODO : Calculation not correct for (0,0) in centre
x_px = x_lg*self.width()//self.LogicalWidth
y_px = y_lg*self.height()//self.LogicalHeight
return x_px,y_px
#=============================================================================
#%% Support functions/classes
#=============================================================================
class incrementer():
""" Class for containing a finite list that spits out a current
value and then increments to the next
"""
def __init__(self,listOfItems,initialIndex = 0):
self.items = listOfItems
self.index = initialIndex
self.itemCount = len(self.items)
def getItem(self):
""" Get current item in list
"""
return self.items[self.index]
def getNextItem(self,direction = 1):
""" Get next item on the list
Optional direction specifies whether to get next or previous
item
"""
# increment to next index depending on direction
if direction == 1:
self.increment()
else:
self.decrement()
# Get item to return
item = self.items[self.index]
return item
def increment(self):
""" circular incrementation of internal index, self.index
If it's greater than the number of items in the list it
goes back to zero
"""
if self.index < self.itemCount-1:
self.index +=1
else:
self.index = 0
def decrement(self):
""" circular incrementation of internal index, self.index
If it's less than zero it goes to max items
"""
if self.index > 0:
self.index -=1
else:
self.index = self.itemCount-1
#=============================================================================
#%% multiple plot widget class definition
#=============================================================================
# Constants
MAX_COLUMNS = 2
class FlexiDock(QSplitter):
""" Flexible Dock widget
Widgets can be put in their own dock
The layout of the widgets can be adjusted with the mouse using
splitter bars
Widgets can be inserted to fill from top down or to fill across
Creating a dock area
------------------------
dock = FlexiDock(fillDirection = 'fill across')
or
dock = FlexiDock(fillDirection = 'fill down')
Adding widgets
------------------
dock.addDock(widget2add,title = 'My dock')
Get currently selected dock
------------------------------
widget = dock.getCurrentWidget()
"""
def __init__(self,parent=None,fillDirection = 'fill across',groupName = "new group"):
# Initialise base class
super(FlexiDock, self).__init__(parent)
self.setOpaqueResize(False)
# Group name
# This gets added to all Dock objects so that Docks attached
# to this FlexiDock can be identified in drag and drop operations
self.groupName = groupName
# Allow drag and drop on this widget
self.setAcceptDrops(True)
# Set default orientation based on how the widgets are
# populated into the dock grid,
if fillDirection == 'fill across':
self.topLevelSplit = Qt.Horizontal
self.subLevelSplit = Qt.Vertical
else: # 'fill down'
self.topLevelSplit = Qt.Vertical
self.subLevelSplit = Qt.Horizontal
self.setOrientation(self.topLevelSplit)
# Dictionary to hold plot positions
# the key is a tuple of coordinates (row,column)
# TODO : Is this used?
self.widgetTable = []
# Separate variables to hold table dimensions
self.nColumns = 0
self.nRows = 0
# List of Dock objects contained in the FlexiDock
# use this to find the current dock
self.dockWidgetList = []
# Count of how many widgets are in the dock
self.dockCount = 0
# Current widget and its index
self.currentWidget = None
self.currentIndex = None
# Next plot tuple
# This determines where the next plot goes
self.nextPlot = (1,1)
def addDock(self,Widget,row=None,col=None,title="untitled",userData=None):
"""
Add a widget in a dock at the row,column specified or just place it
Inputs
-----------
row,col = optional row column coordinates, if not specified then the
dock will be added according to the fillDirection
title = title shown on the dock label
group = string for the group that
"""
# Add plotWidget to plotTable
# ---------------------------------
# If nothing specified then use next plot
if row==None or col==None:
(row,col) = self.nextPlot
# If no title then add one
if title == "untitled":
title = "%s %d" % (self.groupName,self.dockCount)
# Create a docking widget
# ----------------------------------
# this is to give the dock a border, title and any other
# decorations
dockWidget = Dock(Widget,title,ID=self.dockCount,groupName = self.groupName)
self.connect(dockWidget, SIGNAL("clicked()"),self.selectWidget)
# add user data
dockWidget.userData = userData
# Log dock and widget to their lists
# ---------------------------------------
# This allows them to track each other
# Add dockLabel to list
self.dockWidgetList.append(dockWidget)
# Add to widgetTable at row,column
self.widgetTable.append(Widget)
# Make this dock the current one
self.currentIndex = self.dockCount
self.currentWidget = Widget
# Make this the selected widget
self.selectWidget(sender = dockWidget)
# Increment dockCount
self.dockCount += 1
# Find the position of the new widget
# ------------------------------------
# Expand if necessary
# Check if we need a new column
if col > self.nColumns:
# Add a new column, containing a vertical splitter
columnWidget = QSplitter(self.subLevelSplit)
columnWidget.setOpaqueResize(False)
self.addWidget(columnWidget)
# Increment column count
self.nColumns +=1
# Update the sizes of the horizontal widgets
if self.nColumns > 1:
col_sizes = [round(0.9*self.width()/self.nColumns)]*self.nColumns
self.setSizes(col_sizes)
else:
columnWidget = self.widget(col-1)
# check if we need a new row
rowCount = columnWidget.count()
if row > rowCount:
# add a new row
columnWidget.addWidget(dockWidget)
# Increment rows
self.nRows += 1
# Update vertical heights
if self.nRows > 1:
row_sizes = [round(0.9*columnWidget.height()/self.nRows)]*self.nRows