-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathformlayout.py
1314 lines (1172 loc) · 49.9 KB
/
formlayout.py
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 -*-
"""
formlayout
==========
Module creating Qt form dialogs/layouts to edit various type of parameters
formlayout License Agreement (MIT License)
------------------------------------------
Copyright (c) 2009-2015 Pierre Raybaut
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import print_function
__version__ = '2.0.0alpha'
__license__ = __doc__
DEBUG_FORMLAYOUT = False
import os
import sys
import datetime
STDERR = sys.stderr
# ---+- PyQt-PySide compatibility -+----
_modname = os.environ.setdefault('QT_API', 'pyqt5')
assert _modname in ('pyqt', 'pyqt5', 'pyside')
if os.environ['QT_API'].startswith('pyqt'):
try:
if os.environ['QT_API'] == 'pyqt5':
import PyQt5 # analysis:ignore
else:
import PyQt4 # analysis:ignore
except ImportError:
# Switching to PySide
os.environ['QT_API'] = _modname = 'pyside'
try:
import PySide # analysis:ignore
except ImportError:
raise ImportError("formlayout requires PyQt4, PyQt5 or PySide")
if os.environ['QT_API'] == 'pyqt':
try:
from PyQt4.QtGui import QFormLayout
except ImportError:
raise ImportError("formlayout requires PyQt4, PyQt5 or PySide")
from PyQt4.QtGui import * # analysis:ignore
from PyQt4.QtCore import * # analysis:ignore
from PyQt4.QtCore import pyqtSlot as Slot
from PyQt4.QtCore import pyqtProperty as Property
QT_LIB = 'PyQt4'
if os.environ['QT_API'] == 'pyqt5':
from PyQt5.QtWidgets import * # analysis:ignore
from PyQt5.QtGui import * # analysis:ignore
from PyQt5.QtCore import * # analysis:ignore
from PyQt5.QtCore import pyqtSignal as Signal # analysis:ignore
from PyQt5.QtCore import pyqtSlot as Slot # analysis:ignore
from PyQt5.QtCore import pyqtProperty as Property # analysis:ignore
SIGNAL = None # analysis:ignore
QT_LIB = 'PyQt5'
if os.environ['QT_API'] == 'pyside':
from PySide.QtGui import * # analysis:ignore
from PySide.QtCore import * # analysis:ignore
QT_LIB = 'PySide'
# ---+- Python 2-3 compatibility -+----
PY2 = sys.version[0] == '2'
if PY2:
# Python 2
import codecs
def u(obj):
"""Make unicode object"""
return codecs.unicode_escape_decode(obj)[0]
else:
# Python 3
def u(obj):
"""Return string as it is"""
return obj
def is_text_string(obj):
"""Return True if `obj` is a text string, False if it is anything else,
like binary data (Python 3) or QString (Python 2, PyQt API #1)"""
if PY2:
# Python 2
return isinstance(obj, basestring)
else:
# Python 3
return isinstance(obj, str)
def is_binary_string(obj):
"""Return True if `obj` is a binary string, False if it is anything else"""
if PY2:
# Python 2
return isinstance(obj, str)
else:
# Python 3
return isinstance(obj, bytes)
def is_string(obj):
"""Return True if `obj` is a text or binary Python string object,
False if it is anything else, like a QString (Python 2, PyQt API #1)"""
return is_text_string(obj) or is_binary_string(obj)
def to_text_string(obj, encoding=None):
"""Convert `obj` to (unicode) text string"""
if PY2:
# Python 2
if encoding is None:
return unicode(obj)
else:
return unicode(obj, encoding)
else:
# Python 3
if encoding is None:
return str(obj)
elif isinstance(obj, str):
# In case this function is not used properly, this could happen
return obj
else:
return str(obj, encoding)
class ColorButton(QPushButton):
"""
Color choosing push button
"""
__pyqtSignals__ = ("colorChanged(QColor)",)
if SIGNAL is None:
colorChanged = Signal("QColor")
def __init__(self, parent=None):
QPushButton.__init__(self, parent)
self.setFixedSize(20, 20)
self.setIconSize(QSize(12, 12))
if SIGNAL is None:
self.clicked.connect(self.choose_color)
else:
self.connect(self, SIGNAL("clicked()"), self.choose_color)
self._color = QColor()
def choose_color(self):
color = QColorDialog.getColor(self._color, self.parentWidget())
if color.isValid():
self.set_color(color)
def get_color(self):
return self._color
@Slot(QColor)
def set_color(self, color):
if color != self._color:
self._color = color
if SIGNAL is None:
self.colorChanged.emit(self._color)
else:
self.emit(SIGNAL("colorChanged(QColor)"), self._color)
pixmap = QPixmap(self.iconSize())
pixmap.fill(color)
self.setIcon(QIcon(pixmap))
color = Property("QColor", get_color, set_color)
def text_to_qcolor(text):
"""
Create a QColor from specified string
Avoid warning from Qt when an invalid QColor is instantiated
"""
color = QColor()
if not is_string(text): # testing for QString (PyQt API#1)
text = str(text)
if not is_text_string(text):
return color
if text.startswith('#') and len(text)==7:
correct = '#0123456789abcdef'
for char in text:
if char.lower() not in correct:
return color
elif text not in list(QColor.colorNames()):
return color
color.setNamedColor(text)
return color
class ColorLayout(QHBoxLayout):
"""Color-specialized QLineEdit layout"""
def __init__(self, color, parent=None):
QHBoxLayout.__init__(self)
assert isinstance(color, QColor)
self.lineedit = QLineEdit(color.name(), parent)
if SIGNAL is None:
self.lineedit.textChanged.connect(self.update_color)
else:
self.connect(self.lineedit, SIGNAL("textChanged(QString)"),
self.update_color)
self.addWidget(self.lineedit)
self.colorbtn = ColorButton(parent)
self.colorbtn.color = color
if SIGNAL is None:
self.colorbtn.colorChanged.connect(self.update_text)
else:
self.connect(self.colorbtn, SIGNAL("colorChanged(QColor)"),
self.update_text)
self.addWidget(self.colorbtn)
def update_color(self, text):
color = text_to_qcolor(text)
if color.isValid():
self.colorbtn.color = color
def update_text(self, color):
self.lineedit.setText(color.name())
def text(self):
return self.lineedit.text()
def setStyleSheet(self, style):
self.lineedit.setStyleSheet(style)
self.colorbtn.setStyleSheet(style)
class FileLayout(QHBoxLayout):
"""File-specialized QLineEdit layout"""
def __init__(self, value, parent=None):
QHBoxLayout.__init__(self)
self.value = value
self.lineedit = QLineEdit('', parent)
self.addWidget(self.lineedit)
self.filebtn = QPushButton('Browse')
self.filebtn.clicked.connect(self.getfile)
self.addWidget(self.filebtn)
def getfile(self):
if self.value.startswith('file'):
name = QFileDialog.getOpenFileName(None, 'Select file',
filter=self.value[5:])
if QT_LIB == 'PyQt5':
name, _filter = name
elif self.value == 'dir':
name = QFileDialog.getExistingDirectory(None, 'Select directory')
if name:
self.lineedit.setText(name)
def text(self):
return self.lineedit.text()
def setStyleSheet(self, style):
self.lineedit.setStyleSheet(style)
class SliderLayout(QHBoxLayout):
"""QSlider with QLabel"""
def __init__(self, value, parent=None):
QHBoxLayout.__init__(self)
index = value.find('@')
if index != -1:
value, default = value[:index], int(value[index+1:])
else:
default = False
parsed = value.split(':')
self.slider = QSlider(Qt.Horizontal)
if parsed[-1] == '':
self.slider.setTickPosition(2)
parsed.pop(-1)
if len(parsed) == 2:
self.slider.setMaximum(int(parsed[1]))
elif len(parsed) == 3:
self.slider.setMinimum(int(parsed[1]))
self.slider.setMaximum(int(parsed[2]))
if default:
self.slider.setValue(default) # always set value in last
if SIGNAL is None:
self.slider.valueChanged.connect(self.update)
else:
self.connect(self.slider, SIGNAL("valueChanged(int)"), self.update)
self.cpt = QLabel(str(self.value()))
self.addWidget(self.slider)
self.addWidget(self.cpt)
def update(self):
self.cpt.setText(str(self.value()))
def value(self):
return self.slider.value()
def setStyleSheet(self, style):
self.slider.setStyleSheet(style)
self.cpt.setStyleSheet(style)
class RadioLayout(QVBoxLayout):
"""Radio buttons layout with QButtonGroup"""
def __init__(self, buttons, index, parent=None):
QVBoxLayout.__init__(self)
self.setSpacing(0)
self.group = QButtonGroup()
for i, button in enumerate(buttons):
btn = QRadioButton(button)
if i == index:
btn.setChecked(True)
self.addWidget(btn)
self.group.addButton(btn, i)
def currentIndex(self):
return self.group.checkedId()
def setStyleSheet(self, style):
for btn in self.group.buttons():
btn.setStyleSheet(style)
class CheckLayout(QVBoxLayout):
"""Check boxes layout with QButtonGroup"""
def __init__(self, boxes, checks, parent=None):
QVBoxLayout.__init__(self)
self.setSpacing(0)
self.group = QButtonGroup()
self.group.setExclusive(False)
for i, (box, check) in enumerate(zip(boxes, checks)):
cbx = QCheckBox(box)
cbx.setChecked(eval(check))
self.addWidget(cbx)
self.group.addButton(cbx, i)
def values(self):
return [cbx.isChecked() for cbx in self.group.buttons()]
def setStyleSheet(self, style):
for cbx in self.group.buttons():
cbx.setStyleSheet(style)
class PushLayout(QHBoxLayout):
"""Push buttons horizontal layout"""
def __init__(self, buttons, parent=None):
QHBoxLayout.__init__(self)
self.result = parent.result
self.dialog = parent.get_dialog()
for button in buttons:
label, callback = button
self.btn = QPushButton(label)
if SIGNAL is None:
self.btn.clicked.connect(self.call(callback))
else:
self.connect(self.btn, SIGNAL("clicked()"), self.call(callback))
self.addWidget(self.btn)
def call(self, callback):
return lambda: self.apply(callback)
def apply(self, callback):
if self.result == 'XML':
app = ET.Element('App')
app.attrib['title'] = self.dialog.title
child = ET.fromstring(self.dialog.formwidget.get())
app.append(child)
callback(ET.tostring(app),
self.dialog.formwidget.get_widgets())
else:
callback(self.dialog.formwidget.get(),
self.dialog.formwidget.get_widgets())
class CountLayout(QHBoxLayout):
"""Field with a QSpinBox"""
def __init__(self, field, parent=None):
QHBoxLayout.__init__(self)
self.field = field
self.count = QSpinBox()
self.count.setFixedWidth(45)
self.addWidget(self.field)
self.addWidget(self.count)
def text(self):
return self.field.text()
def currentIndex(self):
return self.field.currentIndex()
def n(self):
return self.count.value()
def setStyleSheet(self, style):
self.field.setStyleSheet(style)
self.count.setStyleSheet(style)
def font_is_installed(font):
"""Check if font is installed"""
return [fam for fam in QFontDatabase().families()
if to_text_string(fam) == font]
def tuple_to_qfont(tup):
"""
Create a QFont from tuple:
(family [string], size [int], italic [bool], bold [bool])
"""
if not isinstance(tup, tuple) or len(tup) != 4 \
or not is_text_string(tup[0]) \
or not isinstance(tup[1], int) \
or not isinstance(tup[2], bool) \
or not isinstance(tup[3], bool):
return None
font = QFont()
family, size, italic, bold = tup
font.setFamily(family)
font.setPointSize(size)
font.setItalic(italic)
font.setBold(bold)
return font
def qfont_to_tuple(font):
return (to_text_string(font.family()), int(font.pointSize()),
font.italic(), font.bold())
class FontLayout(QGridLayout):
"""Font selection"""
def __init__(self, value, parent=None):
QGridLayout.__init__(self)
if not font_is_installed(value[0]):
print("Warning: Font `%s` is not installed" % value[0],
file=sys.stderr)
font = tuple_to_qfont(value)
assert font is not None
# Font family
self.family = QFontComboBox(parent)
self.family.setCurrentFont(font)
self.addWidget(self.family, 0, 0, 1, -1)
# Font size
self.size = QComboBox(parent)
self.size.setEditable(True)
sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72]
size = font.pointSize()
if size not in sizelist:
sizelist.append(size)
sizelist.sort()
self.size.addItems([str(s) for s in sizelist])
self.size.setCurrentIndex(sizelist.index(size))
self.addWidget(self.size, 1, 0)
# Italic or not
self.italic = QCheckBox(self.tr("Italic"), parent)
self.italic.setChecked(font.italic())
self.addWidget(self.italic, 1, 1)
# Bold or not
self.bold = QCheckBox(self.tr("Bold"), parent)
self.bold.setChecked(font.bold())
self.addWidget(self.bold, 1, 2)
def get_font(self):
font = self.family.currentFont()
font.setItalic(self.italic.isChecked())
font.setBold(self.bold.isChecked())
font.setPointSize(int(self.size.currentText()))
return qfont_to_tuple(font)
def setStyleSheet(self, style):
self.family.setStyleSheet(style)
self.size.setStyleSheet(style)
self.italic.setStyleSheet(style)
self.bold.setStyleSheet(style)
def is_float_valid(edit):
text = edit.text()
state = edit.validator().validate(text, 0)[0]
return state == QDoubleValidator.Acceptable
def is_required_valid(edit, widget_color):
required_color = "background-color:rgb(255, 175, 90);"
if widget_color:
widget_color = "background-color:" + widget_color + ";"
else:
widget_color = ""
if isinstance(edit, (QLineEdit, FileLayout)):
if edit.text():
edit.setStyleSheet(widget_color)
return True
else:
edit.setStyleSheet(required_color)
elif isinstance(edit, (QComboBox, RadioLayout)):
if edit.currentIndex() != -1:
edit.setStyleSheet(widget_color)
return True
else:
edit.setStyleSheet(required_color)
elif isinstance(edit, QTextEdit):
if edit.toPlainText():
edit.setStyleSheet(widget_color)
return True
else:
edit.setStyleSheet(required_color)
return False
class FormWidget(QWidget):
def __init__(self, data, comment="", parent=None):
QWidget.__init__(self, parent)
from copy import deepcopy
self.data = deepcopy(data)
self.result = parent.result
self.type = parent.type
self.widget_color = parent.widget_color
self.widgets = []
self.formlayout = QFormLayout(self)
if comment:
self.formlayout.addRow(QLabel(comment))
self.formlayout.addRow(QLabel(" "))
if DEBUG_FORMLAYOUT:
print("\n"+("*"*80))
print("DATA:", self.data)
print("*"*80)
print("COMMENT:", comment)
print("*"*80)
def get_dialog(self):
"""Return FormDialog instance"""
dialog = self.parent()
while not isinstance(dialog, QDialog):
dialog = dialog.parent()
return dialog
def setup(self):
for label, value in self.data:
if DEBUG_FORMLAYOUT:
print("value:", value)
if label is None and value is None:
# Separator: (None, None)
separator = QFrame()
separator.setFrameShape(QFrame.HLine)
separator.setFrameShadow(QFrame.Sunken)
self.formlayout.addRow(separator)
self.widgets.append(None)
continue
if label is None:
if isinstance(value, (list, tuple)):
field = PushLayout(value, self)
self.formlayout.addRow(field)
else:
img_fmt = tuple(['.'+str(bytes(ext).decode()) for ext
in QImageReader.supportedImageFormats()])
if value.endswith(img_fmt):
# Image
pixmap = QPixmap(value)
lab = QLabel()
lab.setPixmap(pixmap)
self.formlayout.addRow(lab)
else:
# Comment
self.formlayout.addRow(QLabel(value))
self.widgets.append(None)
continue
if tuple_to_qfont(value) is not None:
field = FontLayout(value, self)
elif text_to_qcolor(value).isValid():
field = ColorLayout(QColor(value), self)
elif is_text_string(value):
if value in ['file', 'dir'] or value.startswith('file:'):
field = FileLayout(value, self)
elif value == 'slider' or value.startswith('slider:') \
or value.startswith('slider@'):
field = SliderLayout(value, self)
elif value == 'password':
field = QLineEdit(self)
field.setEchoMode(QLineEdit.Password)
elif value in ['calendar', 'calendarM'] \
or value.startswith(('calendar:', 'calendarM:')) \
or value.startswith(('calendar@', 'calendarM@')):
index = value.find('@')
if index != -1:
value, date = value[:index], value[index+1:]
else:
date = False
field = QCalendarWidget(self)
field.setVerticalHeaderFormat(field.NoVerticalHeader)
parsed = value.split(':')
if parsed[-1] == '':
field.setGridVisible(True)
parsed.pop(-1)
if parsed[0] == 'calendarM':
field.setFirstDayOfWeek(Qt.Monday)
if len(parsed) == 2:
field.setMaximumDate(datetime.date(*eval(parsed[1])))
elif len(parsed) == 3:
field.setMinimumDate(datetime.date(*eval(parsed[1])))
field.setMaximumDate(datetime.date(*eval(parsed[2])))
if date:
field.setSelectedDate(datetime.date(*eval(date)))
elif '\n' in value:
if value == '\n':
value = ''
for linesep in (os.linesep, '\n'):
if linesep in value:
value = value.replace(linesep, u("\u2029"))
field = QTextEdit(value, self)
else:
field = QLineEdit(value, self)
elif isinstance(value, (list, tuple)) and is_text_string(value[0])\
and value[0].startswith('0b'):
field = CheckLayout(value[1:], value[0][2:], self)
elif isinstance(value, (list, tuple)):
save_value = value
value = list(value) # always needed to protect self.data
selindex = value.pop(0)
if isinstance(selindex, int):
selindex = selindex - 1
if isinstance(value[0], (list, tuple)):
keys = [ key for key, _val in value ]
value = [ val for _key, val in value ]
else:
keys = value
if selindex in value:
selindex = value.index(selindex)
elif selindex in keys:
selindex = keys.index(selindex)
elif not isinstance(selindex, int):
print("Warning: '%s' index is invalid (label: "\
"%s, value: %s)" % (selindex, label, value),
file=STDERR)
selindex = -1
if isinstance(save_value, list):
field = QComboBox(self)
field.addItems(value)
field.setCurrentIndex(selindex)
elif isinstance(save_value, tuple):
field = RadioLayout(value, selindex, self)
elif isinstance(value, bool):
field = QCheckBox(self)
field.setChecked(value)
elif isinstance(value, float):
field = QLineEdit(QLocale().toString(value), self)
field.setValidator(QDoubleValidator(field))
dialog = self.get_dialog()
dialog.register_float_field(field)
if SIGNAL is None:
field.textChanged.connect(dialog.float_valid)
else:
self.connect(field, SIGNAL('textChanged(QString)'),
dialog.float_valid)
elif isinstance(value, int):
field = QSpinBox(self)
field.setRange(-1e9, 1e9)
field.setValue(value)
elif isinstance(value, datetime.datetime):
field = QDateTimeEdit(self)
field.setDateTime(value)
elif isinstance(value, datetime.date):
field = QDateEdit(self)
field.setDate(value)
elif isinstance(value, datetime.time):
field = QTimeEdit(self)
field.setTime(value)
else:
field = QLineEdit(repr(value), self)
# Eventually catching the 'countfield' feature and processing it
if label.startswith('n '):
label = label[2:]
if isinstance(field, QLineEdit) and is_text_string(value) or\
isinstance(field, QComboBox):
field = CountLayout(field)
else:
print("Warning: '%s' doesn't support 'nfield' feature"\
% label, file=STDERR)
# Eventually extracting tooltip from label and processing it
index = label.find('::')
if index != -1:
label, tooltip = label[:index], label[index+2:]
field.setToolTip(tooltip)
# Eventually catching the 'required' feature and processing it
if label.endswith(' *'):
label = label[:-1] + '<font color="red">*</font>'
if isinstance(field, (QLineEdit, QTextEdit, QComboBox,
FileLayout, RadioLayout)):
dialog = self.get_dialog()
dialog.register_required_field(field)
else:
print("Warning: '%s' doesn't support 'required' feature"\
% type(field), file=STDERR)
if isinstance(field, QLineEdit):
if SIGNAL is None:
field.textChanged.connect(dialog.required_valid)
else:
self.connect(field, SIGNAL('textChanged(QString)'),
dialog.required_valid)
elif isinstance(field, QTextEdit):
if SIGNAL is None:
field.textChanged.connect(dialog.required_valid)
else:
self.connect(field, SIGNAL('textChanged()'),
dialog.required_valid)
elif isinstance(field, QComboBox):
if SIGNAL is None:
field.currentIndexChanged.connect(\
dialog.required_valid)
else:
self.connect(field,
SIGNAL('currentIndexChanged(QString)'),
dialog.required_valid)
elif isinstance(field, FileLayout):
if SIGNAL is None:
field.lineedit.textChanged.connect(\
dialog.required_valid)
else:
self.connect(field.lineedit,
SIGNAL('textChanged(QString)'),
dialog.required_valid)
elif isinstance(field, RadioLayout):
if SIGNAL is None:
field.group.buttonClicked.connect(\
dialog.required_valid)
else:
self.connect(field.group, SIGNAL('buttonClicked(int)'),
dialog.required_valid)
# Eventually setting the widget_color
if self.widget_color:
style = "background-color:" + self.widget_color + ";"
field.setStyleSheet(style)
if self.type == 'form':
self.formlayout.addRow(label, field)
elif self.type == 'questions':
self.formlayout.addRow(QLabel(label))
self.formlayout.addRow(field)
self.widgets.append(field)
def get(self):
valuelist = []
for index, (label, value) in enumerate(self.data):
field = self.widgets[index]
if label is None:
# Separator / Comment
continue
if label.startswith('n '):
label = label[2:]
if tuple_to_qfont(value) is not None:
value = field.get_font()
elif is_text_string(value):
if isinstance(field, QTextEdit):
value = to_text_string(field.toPlainText()
).replace(u("\u2029"), os.linesep)
elif isinstance(field, SliderLayout):
value = field.value()
elif isinstance(field, QCalendarWidget):
value = field.selectedDate()
try:
value = value.toPyDate() # PyQt
except AttributeError:
value = value.toPython() # PySide
else:
value = to_text_string(field.text())
elif isinstance(field, CheckLayout):
value = field.values()
elif isinstance(value, (list, tuple)):
index = int(field.currentIndex())
if isinstance(value[0], int):
# Return an int index, if initialization was an int
value = index + 1
else:
value = value[index+1]
if isinstance(value, (list, tuple)):
value = value[0]
elif isinstance(value, bool):
value = field.checkState() == Qt.Checked
elif isinstance(value, float):
value = float(QLocale().toDouble(field.text())[0])
elif isinstance(value, int):
value = int(field.value())
elif isinstance(value, datetime.datetime):
value = field.dateTime()
try:
value = value.toPyDateTime() # PyQt
except AttributeError:
value = value.toPython() # PySide
elif isinstance(value, datetime.date):
value = field.date()
try:
value = value.toPyDate() # PyQt
except AttributeError:
value = value.toPython() # PySide
elif isinstance(value, datetime.time):
value = field.time()
try:
value = value.toPyTime() # PyQt
except AttributeError:
value = value.toPython() # PySide
else:
value = eval(str(field.text()))
if isinstance(field, CountLayout):
value = (value, field.n())
valuelist.append((label, value))
if self.result == 'list':
return [value for label, value in valuelist]
elif self.result in ['dict', 'OrderedDict', 'JSON']:
if self.result == 'dict':
dic = {}
else:
dic = OrderedDict()
for label, value in valuelist:
if label in dic.keys():
print("Warning: '%s' is duplicate and '%s' doesn't "\
"handle it, you should use 'list' or 'XML' instead"\
% (label, self.result), file=STDERR)
if isinstance(value, (datetime.date, datetime.time,
datetime.datetime)) and self.result == 'JSON':
dic[label] = value.isoformat()
else:
dic[label] = value
if self.result == 'JSON':
return json.dumps(dic)
else:
return dic
elif self.result == 'XML':
form = ET.Element('Form')
for label, value in valuelist:
tooltip = ''
index = label.find('::')
if index != -1:
label, tooltip = label[:index], label[index+2:]
required = 'false'
if label.endswith(' *'):
label = label[:-2]
required = 'true'
child = ET.SubElement(form, label)
if isinstance(value, tuple):
child.text = to_text_string(value[0])
child.attrib['amount'] = to_text_string(value[1])
else:
if isinstance(value, datetime.datetime):
child.text = value.isoformat()
else:
child.text = to_text_string(value)
child.attrib['tooltip'] = tooltip
child.attrib['required'] = required
return ET.tostring(form)
def get_widgets(self):
return self.widgets
class FormComboWidget(QWidget):
def __init__(self, datalist, comment="", parent=None):
QWidget.__init__(self, parent)
layout = QVBoxLayout()
self.setLayout(layout)
self.combobox = QComboBox()
layout.addWidget(self.combobox)
self.stackwidget = QStackedWidget(self)
layout.addWidget(self.stackwidget)
if SIGNAL is None:
self.combobox.currentIndexChanged.connect(
self.stackwidget.setCurrentIndex)
else:
self.connect(self.combobox, SIGNAL("currentIndexChanged(int)"),
self.stackwidget, SLOT("setCurrentIndex(int)"))
self.result = parent.result
self.widget_color = parent.widget_color
if self.widget_color:
style = "background-color:" + self.widget_color + ";"
self.combobox.setStyleSheet(style)
self.type = parent.type
self.widgetlist = []
for data, title, comment in datalist:
self.combobox.addItem(title)
widget = FormWidget(data, comment=comment, parent=self)
self.stackwidget.addWidget(widget)
self.widgetlist.append((title, widget))
def setup(self):
for title, widget in self.widgetlist:
widget.setup()
def get(self):
if self.result == 'list':
return [widget.get() for title, widget in self.widgetlist]
elif self.result in ['dict', 'OrderedDict', 'JSON']:
if self.result == 'dict':
dic = {}
else:
dic = OrderedDict()
for title, widget in self.widgetlist:
if self.result == 'JSON':
dic[title] = json.loads(widget.get(),
object_pairs_hook=OrderedDict)
else:
dic[title] = widget.get()
if self.result == 'JSON':
return json.dumps(dic)
else:
return dic
elif self.result == 'XML':
combos = ET.Element('Combos')
for title, widget in self.widgetlist:
combo = ET.SubElement(combos, 'Combo')
combo.attrib['title'] = title
child = ET.fromstring(widget.get())
combo.append(child)
return ET.tostring(combos)
def get_widgets(self):
widgets = []
for title, widget in self.widgetlist:
widgets.extend(widget.get_widgets())
return widgets
class FormTabWidget(QWidget):
def __init__(self, datalist, comment="", parent=None):
QWidget.__init__(self, parent)
layout = QVBoxLayout()
self.tabwidget = QTabWidget()
layout.addWidget(self.tabwidget)
self.setLayout(layout)
self.result = parent.result
self.widget_color = parent.widget_color
self.type = parent.type
self.widgetlist = []
for data, title, comment in datalist:
if len(data[0])==3:
widget = FormComboWidget(data, comment=comment, parent=self)
else:
widget = FormWidget(data, comment=comment, parent=self)
index = self.tabwidget.addTab(widget, title)
self.tabwidget.setTabToolTip(index, comment)
self.widgetlist.append((title, widget))
def setup(self):
for title, widget in self.widgetlist:
widget.setup()
def get(self):
if self.result == 'list':
return [widget.get() for title, widget in self.widgetlist]
elif self.result in ['dict', 'OrderedDict', 'JSON']:
if self.result == 'dict':
dic = {}
else:
dic = OrderedDict()
for title, widget in self.widgetlist:
if self.result == 'JSON':
dic[title] = json.loads(widget.get(),
object_pairs_hook=OrderedDict)
else:
dic[title] = widget.get()
if self.result == 'JSON':
return json.dumps(dic)
else:
return dic
elif self.result == 'XML':
tabs = ET.Element('Tabs')
for title, widget in self.widgetlist:
tab = ET.SubElement(tabs, 'Tab')
tab.attrib['title'] = title
child = ET.fromstring(widget.get())
tab.append(child)
return ET.tostring(tabs)
def get_widgets(self):
widgets = []
for title, widget in self.widgetlist:
widgets.extend(widget.get_widgets())
return widgets