forked from mottosso/qargparse.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qargparse.py
1249 lines (914 loc) · 35.9 KB
/
qargparse.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
import re
import types
import logging
from collections import OrderedDict as odict
# User-specified style, either write to this directly,
# or copy it and pass it to QArgumentParser(style=yourStyle)
DefaultStyle = {
# Should comboboxes cover the full horizontal width?
"comboboxFillWidth": False,
# Should the QArgument(help=) be used as a tooltip?
"useTooltip": True,
}
__version__ = "0.5.10"
_log = logging.getLogger(__name__)
_type = type # used as argument
_dpi = None
try:
# Python 2
_basestring = basestring
except NameError:
_basestring = str
# Support for both PyQt5 and PySide2
QtCompat = types.ModuleType("QtCompat")
try:
from PySide2 import (
QtWidgets,
QtCore,
QtGui,
)
from shiboken2 import wrapInstance, getCppPointer
QtCompat.wrapInstance = wrapInstance
QtCompat.getCppPointer = getCppPointer
try:
from PySide2 import QtUiTools
QtCompat.loadUi = QtUiTools.QUiLoader
except ImportError:
_log.debug("QtUiTools not provided.")
except ImportError:
try:
from PyQt5 import (
QtWidgets,
QtCore,
QtGui,
)
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
QtCore.Property = QtCore.pyqtProperty
from sip import wrapinstance, unwrapinstance
QtCompat.wrapInstance = wrapinstance
QtCompat.getCppPointer = unwrapinstance
try:
from PyQt5 import uic
QtCompat.loadUi = uic.loadUi
except ImportError:
_log.debug("uic not provided.")
except ImportError:
_log.error(
"Could not find either the required PySide2 or PyQt5"
)
_stylesheet = """\
QWidget {
font-size: 8pt;
}
*[type="Button"] {
text-align:left;
}
*[type="Info"] {
background: transparent;
border: none;
}
QLabel[type="Separator"] {
min-height: 20px;
text-decoration: underline;
}
QWidget[type="QArgparse:reset"] {
/* Ensure size fixed */
max-width: 11px;
max-height: 11px;
min-width: 11px;
min-height: 11px;
padding-top: 0px;
padding-bottom: 0px;
padding-left: 0px;
padding-right: 0px;
}
#description, #icon {
padding-bottom: 10px;
}
"""
def px(value):
"""Return a scaled value, for HDPI resolutions"""
global _dpi
if not _dpi:
# We can get system DPI from a window handle,
# but I haven't figured out how to get a window handle
# without first making a widget. So here we make one
# as invisibly as we can, as an invisible tooltip.
# This doesn't create a taskbar icon nor changes focus
# and in fact *should* happen without any noticeable effect
# to the user. Welcome to provide a less naughty alternative
any_widget = QtWidgets.QWidget()
any_widget.setWindowFlags(QtCore.Qt.ToolTip)
any_widget.show()
window = any_widget.windowHandle()
any_widget.deleteLater()
# E.g. 1.5 or 2.0
scale = window.screen().logicalDotsPerInch() / 96.0
# Store for later
_dpi = scale
return value * _dpi
def _scaled_stylesheet():
"""Replace any mention of <num>px with scaled version
This way, you can still use px without worrying about what
it will look like at HDPI resolution.
"""
output = []
for line in _stylesheet.splitlines():
line = line.rstrip()
if line.endswith("px;"):
key, value = line.rsplit(" ", 1)
value = px(int(value[:-3]))
line = "%s %dpx;" % (key, value)
output += [line]
return "\n".join(output)
DoNothing = None
class QArgumentParser(QtWidgets.QWidget):
"""User interface arguments
Arguments:
arguments (list, optional): Instances of QArgument
description (str, optional): Long-form text of what this parser is for
storage (QSettings, optional): Persistence to disk, providing
value() and setValue() methods
style (dict, optional): User-specified overrides to style choices
parent (QWidget, optional): Parent of this widget
"""
changed = QtCore.Signal(QtCore.QObject) # A QArgument
entered = QtCore.Signal(QtCore.QObject)
exited = QtCore.Signal(QtCore.QObject)
def __init__(self,
arguments=None,
description=None,
storage=None,
style=None,
parent=None):
super(QArgumentParser, self).__init__(parent)
self.setAttribute(QtCore.Qt.WA_StyledBackground)
# Create internal settings
if storage is True:
storage = QtCore.QSettings(
QtCore.QSettings.IniFormat,
QtCore.QSettings.UserScope,
__name__, "QArgparse",
)
if storage is not None:
_log.info("Storing settings @ %s" % storage.fileName())
arguments = arguments or []
assert hasattr(arguments, "__iter__"), "arguments must be iterable"
assert isinstance(storage, (type(None), QtCore.QSettings)), (
"storage must be of type QSettings"
)
layout = QtWidgets.QGridLayout(self)
layout.setRowStretch(999, 1)
icon = QtWidgets.QLabel()
description = QtWidgets.QLabel(description or "")
layout.addWidget(icon, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
layout.addWidget(description, 0, 1, 1, 1, QtCore.Qt.AlignVCenter)
# Shown when set
icon.setVisible(False)
description.setVisible(bool(description.text()))
# For CSS
icon.setObjectName("icon")
description.setObjectName("description")
self._row = 1
self._storage = storage
self._arguments = odict()
self._resets = dict()
self._description = description
self._icon = icon
self._style = style or DefaultStyle
for arg in arguments or []:
self._addArgument(arg)
# Prevent getting squashed on the vertical
self.setSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.MinimumExpanding)
self.setStyleSheet(_scaled_stylesheet())
def __iter__(self):
"""Make parser iterable
Arguments yield in the order they were added.
Example
>>> args = [Float("age"), Boolean("alive")]
>>> parser = QArgumentParser(args)
>>> for arg in parser:
... print(arg["name"])
...
age
alive
"""
for _, arg in self._arguments.items():
yield arg
def setDescription(self, text):
self._description.setText(text or "")
self._description.setVisible(bool(text))
def setIcon(self, fname):
self._icon.setPixmap(QtGui.QPixmap(fname))
self._icon.setVisible(bool(fname))
def addArgument(self, name, type=None, default=None, **kwargs):
# Infer type from default
if type is None and default is not None:
type = _type(default)
# Default to string
type = type or str
Argument = {
None: String,
int: Integer,
float: Float,
bool: Boolean,
str: String,
list: Enum,
tuple: Enum,
}.get(type, type)
arg = Argument(name, default=default, **kwargs)
self._addArgument(arg)
return arg
def _addArgument(self, arg):
if arg["name"] in self._arguments:
raise ValueError("Duplicate argument '%s'" % arg["name"])
if self._storage is not None:
default = self._storage.value(arg["name"])
# Qt's native storage doesn't handle booleans
# in either of the Python bindings, so we need
# some jujitsu here to translate values it gives
# us into something useful to Python
if default:
if isinstance(arg, Boolean):
default = bool({
None: QtCore.Qt.Unchecked,
0: QtCore.Qt.Unchecked,
1: QtCore.Qt.Checked,
2: QtCore.Qt.Checked,
"0": QtCore.Qt.Unchecked,
"1": QtCore.Qt.Checked,
"2": QtCore.Qt.Checked,
# May be stored as string, if used with IniFormat
"false": QtCore.Qt.Unchecked,
"true": QtCore.Qt.Checked,
}.get(default))
if isinstance(arg, Number):
if isinstance(arg, Float):
default = float(default)
else:
default = int(default)
arg["default"] = default
# Argument label and editor widget
label = QtWidgets.QLabel(arg["label"])
if isinstance(arg, Enum):
widget = arg.create(fillWidth=self._style["comboboxFillWidth"])
else:
widget = arg.create()
for widget in (label, widget):
widget.setObjectName(arg["name"]) # useful in CSS
widget.setProperty("type", type(arg).__name__)
widget.setAttribute(QtCore.Qt.WA_StyledBackground)
widget.setEnabled(arg["enabled"])
if self._style.get("useTooltip"):
widget.setToolTip(arg["help"])
# Reset btn widget
reset_container = QtWidgets.QWidget()
reset_container.setProperty("type", "QArgparse:reset")
reset = QtWidgets.QPushButton("") # default
reset.setToolTip(arg.compose_reset_tip())
reset.hide() # shown on edit
# Align label on top of row if widget is over two times higher
height = (lambda w: w.sizeHint().height())
label_on_top = height(label) * 2 < height(widget)
alignment = (QtCore.Qt.AlignTop,) if label_on_top else ()
# Layout
layout = QtWidgets.QVBoxLayout(reset_container)
layout.addWidget(reset)
layout.setContentsMargins(0, 0, 0, 0)
layout = self.layout()
# ___________________________________________
# | | | |
# | label | editor | reset |
# |_________|_________________________|_______|
#
if not isinstance(arg, Boolean):
# Checkboxes have their own label to the right
layout.addWidget(label, self._row, 0, QtCore.Qt.AlignRight)
layout.addWidget(widget, self._row, 1)
layout.addWidget(reset_container, self._row, 2, *alignment)
layout.setColumnStretch(1, 1)
# Packed tightly on the vertical
layout.setHorizontalSpacing(px(10))
layout.setVerticalSpacing(px(2))
# Signals
reset.pressed.connect(lambda: arg.write(arg["default"]))
# Prevent button from getting stuck in down-state, since
# it is hidden right after having been pressed
reset.pressed.connect(lambda: reset.setDown(False))
arg.changed.connect(lambda: self.on_changed(arg))
arg.entered.connect(lambda: self.on_entered(arg))
arg.exited.connect(lambda: self.on_exited(arg))
# Take ownership for clean deletion alongside parser
arg.setParent(self)
self._row += 1
self._arguments[arg["name"]] = arg
self._resets[arg["name"]] = reset
# Establish initial state, taking "initial" value into account
self.on_changed(arg)
def clear(self):
assert self._storage, "Cannot clear without persistent storage"
self._storage.clear()
_log.info("Clearing settings @ %s" % self._storage.fileName())
def find(self, name):
return self._arguments[name]
def on_changed(self, arg):
reset = self._resets[arg["name"]]
reset.setVisible(arg.isEdited())
arg["edited"] = arg.isEdited()
self.changed.emit(arg)
def on_entered(self, arg):
"""Emitted when an argument is entered"""
self.entered.emit(arg)
def on_exited(self, arg):
"""Emitted when an argument is exited"""
self.exited.emit(arg)
# Optional PEP08 syntax
add_argument = addArgument
class QArgument(QtCore.QObject):
"""Base class of argument user interface"""
changed = QtCore.Signal()
entered = QtCore.Signal()
exited = QtCore.Signal()
# Provide a left-hand side label for this argument
label = True
# For defining default value for each argument type
default = None
def __init__(self, name, default=None, **kwargs):
super(QArgument, self).__init__(kwargs.pop("parent", None))
args = {}
args["name"] = name
args["label"] = kwargs.pop("label", camel_to_title(name))
args["default"] = self.default if default is None else default
args["initial"] = kwargs.pop("initial", None)
args["help"] = kwargs.pop("help", "")
args["read"] = kwargs.pop("read", None)
args["write"] = kwargs.pop("write", None)
args["items"] = kwargs.pop("items", [])
args["min"] = kwargs.pop("min", 0)
args["max"] = kwargs.pop("max", 99)
args["enabled"] = bool(kwargs.pop("enabled", True))
args["edited"] = False
# Anything left is an error
for arg in kwargs:
raise TypeError(
"%s() got an unexpected keyword argument '%s' #"
% (type(self).__name__, arg)
)
self._data = args
def __str__(self):
return self["name"]
def __repr__(self):
return "%s(\"%s\")" % (type(self).__name__, self["name"])
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
self._data[key] = value
def __eq__(self, other):
if isinstance(other, _basestring):
return self["name"] == other
return super(QArgument, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
def isEdited(self):
return self.read() != self["default"]
def create(self):
return QtWidgets.QWidget()
def read(self):
return self._read()
def write(self, value):
self._write(value)
self.changed.emit()
def compose_reset_tip(self):
return "Reset%s" % (
"" if self["default"] is None else " to %s" % str(self["default"])
)
def _with_entered_exited(cls, obj):
"""Factory function to append `enterEvent` and `leaveEvent`"""
class WidgetHoverFactory(cls):
def enterEvent(self, event):
obj.entered.emit()
return super(WidgetHoverFactory, self).enterEvent(event)
def leaveEvent(self, event):
obj.exited.emit()
return super(WidgetHoverFactory, self).leaveEvent(event)
return WidgetHoverFactory
class Boolean(QArgument):
"""Boolean type user interface
Presented by `QtWidgets.QCheckBox`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (bool, optional): Argument's default value, default None
enabled (bool, optional): Whether to enable this widget, default True
"""
def create(self):
Widget = _with_entered_exited(QtWidgets.QCheckBox, self)
widget = Widget(self._data["label"])
if isinstance(self, Tristate):
self._read = lambda: widget.checkState()
state = {
0: QtCore.Qt.Unchecked,
1: QtCore.Qt.PartiallyChecked,
2: QtCore.Qt.Checked,
"1": QtCore.Qt.PartiallyChecked,
"0": QtCore.Qt.Unchecked,
"2": QtCore.Qt.Checked,
}
else:
self._read = lambda: bool(widget.checkState())
state = {
None: QtCore.Qt.Unchecked,
0: QtCore.Qt.Unchecked,
1: QtCore.Qt.Checked,
2: QtCore.Qt.Checked,
"0": QtCore.Qt.Unchecked,
"1": QtCore.Qt.Checked,
"2": QtCore.Qt.Checked,
# May be stored as string, if used with QSettings(..IniFormat)
"false": QtCore.Qt.Unchecked,
"true": QtCore.Qt.Checked,
}
self._write = lambda value: widget.setCheckState(state[value])
widget.clicked.connect(self.changed.emit)
initial = self["initial"]
if initial is None:
initial = self["default"]
if initial is not None:
self._write(initial)
return widget
def read(self):
return self._read()
class Tristate(QArgument):
"""Not implemented"""
class FractionSlider(QtWidgets.QSlider):
"""Slider capable of sliding between whole numbers
Qt, surprisingly, doesn't provide this out of the box
"""
_floatValueChanged = QtCore.Signal(float)
entered = QtCore.Signal()
exited = QtCore.Signal()
def __init__(self, steps=100, parent=None):
super(FractionSlider, self).__init__(parent=parent)
self.steps = steps
self.valueChanged.connect(self._onValueChanged)
# Masquerade as native signal, now that we're connected
# to and will translate that into a float value
self.valueChanged = self._floatValueChanged
def _onValueChanged(self, value):
self._floatValueChanged.emit(value / float(self.steps))
def setMinimum(self, value):
super(FractionSlider, self).setMinimum(value * self.steps)
def setMaximum(self, value):
super(FractionSlider, self).setMaximum(value * self.steps)
def setValue(self, value):
super(FractionSlider, self).setValue(value * self.steps)
def value(self):
return super(FractionSlider, self).value() / float(self.steps)
class Number(QArgument):
"""Base class of numeric type user interface"""
default = 0
def create(self):
if isinstance(self, Float):
slider = _with_entered_exited(FractionSlider, self)()
widget = _with_entered_exited(QtWidgets.QDoubleSpinBox, self)()
widget.setMinimum(self._data.get("min", 0.0))
widget.setMaximum(self._data.get("max", 99.99))
# Account for small values
delta = widget.maximum() - widget.minimum()
stepsize = 0.1 if delta < 10 else 1.0
widget.setSingleStep(stepsize)
else:
slider = _with_entered_exited(QtWidgets.QSlider, self)()
widget = _with_entered_exited(QtWidgets.QSpinBox, self)()
widget.setMinimum(self._data.get("min", 0))
widget.setMaximum(self._data.get("max", 99))
widget.setMinimumWidth(px(50))
container = QtWidgets.QWidget()
slider.setMaximum(widget.maximum())
slider.setMinimum(widget.minimum())
slider.setOrientation(QtCore.Qt.Horizontal)
layout = QtWidgets.QHBoxLayout(container)
layout.addWidget(widget)
layout.addWidget(slider)
layout.setContentsMargins(0, 0, 0, 0)
self._slider = slider
self._widget = widget
# Synchonise spinbox with slider
widget.editingFinished.connect(self.changed.emit)
widget.valueChanged.connect(self.on_spinbox_changed)
slider.valueChanged.connect(self.on_slider_changed)
self._read = lambda: widget.value()
self._write = lambda value: widget.setValue(value)
initial = self["initial"]
if initial is None:
initial = self["default"]
if initial != self.default:
self._write(initial)
return container
def on_spinbox_changed(self, value):
self._slider.setValue(value)
# Spinbox emits a signal all on its own
def on_slider_changed(self, value):
self._widget.setValue(value)
# Help spinbox emit this change
self.changed.emit()
class Integer(Number):
"""Integer type user interface
A subclass of `qargparse.Number`, presented by `QtWidgets.QSpinBox`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (int, optional): Argument's default value, default 0
min (int, optional): Argument's minimum value, default 0
max (int, optional): Argument's maximum value, default 99
enabled (bool, optional): Whether to enable this widget, default True
"""
class Float(Number):
"""Float type user interface
A subclass of `qargparse.Number`, presented by `QtWidgets.QDoubleSpinBox`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (float, optional): Argument's default value, default 0.0
min (float, optional): Argument's minimum value, default 0.0
max (float, optional): Argument's maximum value, default 99.99
enabled (bool, optional): Whether to enable this widget, default True
"""
class Range(Number):
"""Range type user interface
A subclass of `qargparse.Number`, not production ready.
"""
class Double3(QArgument):
"""Double3 type user interface
Presented by three `QtWidgets.QLineEdit` widget
with `QDoubleValidator` installed.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (tuple or list, optional): Default (0, 0, 0).
enabled (bool, optional): Whether to enable this widget, default True
"""
default = (0, 0, 0)
def create(self):
widget = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
x, y, z = (self.child_arg(layout, i) for i in range(3))
self._read = lambda: (
float(x.text()), float(y.text()), float(z.text()))
self._write = lambda value: [
w.setText(str(float(v))) for w, v in zip([x, y, z], value)]
initial = self["initial"]
if initial is None:
initial = self["default"]
if initial != self.default:
self._write(initial)
return widget
def child_arg(self, layout, index):
widget = _with_entered_exited(QtWidgets.QLineEdit, self)()
widget.setValidator(QtGui.QDoubleValidator())
default = str(float(self["default"][index]))
widget.setText(default)
def focusOutEvent(event):
if not widget.text():
widget.setText(default) # Ensure value exists for `_read`
QtWidgets.QLineEdit.focusOutEvent(widget, event)
widget.focusOutEvent = focusOutEvent
widget.editingFinished.connect(self.changed.emit)
widget.returnPressed.connect(widget.editingFinished.emit)
layout.addWidget(widget)
return widget
class String(QArgument):
"""String type user interface
Presented by `QtWidgets.QLineEdit`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (str, optional): Argument's default value, default None
placeholder (str, optional): Placeholder message for the widget
enabled (bool, optional): Whether to enable this widget, default True
"""
def __init__(self, *args, **kwargs):
super(String, self).__init__(*args, **kwargs)
self._previous = None
def create(self):
widget = _with_entered_exited(QtWidgets.QLineEdit, self)()
widget.editingFinished.connect(self.onEditingFinished)
self._read = lambda: widget.text()
self._write = lambda value: widget.setText(value)
if isinstance(self, Info):
widget.setReadOnly(True)
widget.setPlaceholderText(self._data.get("placeholder", ""))
initial = self["initial"]
if initial is None:
initial = self["default"]
if initial is not None:
self._write(initial)
self._previous = initial
return widget
def onEditingFinished(self):
current = self._read()
if current != self._previous:
self._previous = current
self.changed.emit()
class Info(String):
"""String type user interface but read-only
A subclass of `qargparse.String`, presented by `QtWidgets.QLineEdit`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (str, optional): Argument's default value, default None
enabled (bool, optional): Whether to enable this widget, default True
"""
class Color(String):
"""Color type user interface
A subclass of `qargparse.String`, not production ready.
"""
class Button(QArgument):
"""Button type user interface
Presented by `QtWidgets.QPushButton`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (bool, optional): Argument's default value, default None
enabled (bool, optional): Whether to enable this widget, default True
"""
label = False
def create(self):
Widget = _with_entered_exited(QtWidgets.QPushButton, self)
widget = Widget(self["label"])
widget.clicked.connect(self.changed.emit)
state = [
QtCore.Qt.Unchecked,
QtCore.Qt.Checked,
]
if isinstance(self, Toggle):
widget.setCheckable(True)
self._read = lambda: widget.checkState()
self._write = (
lambda value: widget.setCheckState(state[int(value)])
)
else:
self._read = lambda: "clicked"
self._write = lambda value: None
initial = self["initial"]
if initial is None:
initial = self["default"]
if initial is not None:
self._write(initial)
return widget
class Toggle(Button):
"""Checkable `Button` type user interface
Presented by `QtWidgets.QPushButton`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
default (bool, optional): Argument's default value, default None
enabled (bool, optional): Whether to enable this widget, default True
"""
class InfoList(QArgument):
"""String list type user interface
Presented by `QtWidgets.QListView`, not production ready.
"""
def __init__(self, name, **kwargs):
kwargs["default"] = kwargs.pop("default", ["Empty"])
super(InfoList, self).__init__(name, **kwargs)
def create(self):
class Model(QtCore.QStringListModel):
def data(self, index, role):
return super(Model, self).data(index, role)
model = QtCore.QStringListModel(self["default"])
widget = _with_entered_exited(QtWidgets.QListView, self)()
widget.setModel(model)
widget.setEditTriggers(widget.NoEditTriggers)
self._read = lambda: model.stringList()
self._write = lambda value: model.setStringList(value)
initial = self["initial"]
if initial is None:
initial = self["default"]
if initial is not None:
self._write(initial)
return widget
class Choice(QArgument):
"""Argument user interface for selecting one from list
Presented by `QtWidgets.QListView`.
Arguments:
name (str): The name of argument
label (str, optional): Display name, convert from `name` if not given
help (str, optional): Tool tip message of this argument
items (list, optional): List of strings for select, default `["Empty"]`
default (str, optional): Default item in `items`, use first of `items`
if not given.
enabled (bool, optional): Whether to enable this widget, default True
"""
def __init__(self, name, **kwargs):
kwargs["items"] = kwargs.get("items", ["Empty"])
kwargs["default"] = kwargs.pop("default", kwargs["items"][0])
super(Choice, self).__init__(name, **kwargs)
def index(self, value):
"""Return numerical equivalent to self.read()"""
return self["items"].index(value)
def create(self):
def on_changed(selected, deselected):
try:
selected = selected.indexes()[0]
except IndexError:
# At least one item must be selected at all times
selected = deselected.indexes()[0]
value = selected.data(QtCore.Qt.DisplayRole)
set_current(value)
self.changed.emit()