-
Notifications
You must be signed in to change notification settings - Fork 3
/
QClickEdit.py
447 lines (347 loc) · 15.4 KB
/
QClickEdit.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
import datetime
from functools import partial
from PySide2.QtWidgets import QApplication, QWidget
from PySide2.QtWidgets import QHBoxLayout, QPushButton, QLabel
from PySide2.QtCore import Qt, QTime
from PySide2.QtWidgets import QSpinBox as SpinBox
from PySide2.QtWidgets import QLineEdit as LineEdit
from PySide2.QtWidgets import QTimeEdit as TimeEdit
from PySide2.QtWidgets import QComboBox as ComboBox
class QClickEdit(QWidget):
"""Displays text, changes to the specified user input field when clicked
on, then reverts to text again when the widget loses focus.
Self.input_widget holds the Qt user input widget. Any of the functions
inherent to the widget can be executed, though compatability with this
module cannot be guaranteed. Self.text holds the value displayed when a
QClickEdit object is out of focus. Text is displayed as a QPushButton
widget with flat text. When a QClickEdit widget is clicked on, it hides
the text and displays the underlying Qt user input widget. When the user
clicks elseware or the input widget loses focus, a QClickEdit widget
reverts back to the flat text in self.text, displaying the current value
of the underlying widget.
Input widgets currently supported: QSpinBox, QLineEdit, QTimeEdit, and
QComboBox.
Values can be set for QClickEdit widgets, regardless of the type of input
widget used, with the function setValue(), and values can be returned with
getValue(). QLineEdit and QComboBox return as a string, QSpinBox returns
as an integer, and QTimeEdit returns as a QTime Object.
"""
# Registry saves instances of this class to iterate through them and
# determine when to freeze edit fields
_registry = []
# Registry to keep track of which widgets have modified mousePressEvent()
# functions, so they don't get rewritten every time a new QClickEdit object
# is created.
_top_widgets_modified = []
def __init__(self, current_value, type_of_field=False, suffix=False,
bold=False, parent=None):
"""Arguments:
current_value -- The desired default value of the input widget
type_of_field -- Optional argument - This string will precede the
displayed current value
suffix -- suffix to follow current value displayed when self.text is
visible.
"""
if not (isinstance(type_of_field, str) or (type_of_field is False)):
raise TypeError("type_of_field argument is a descriptive prefix and must be a string")
if not (isinstance(suffix, str) or (suffix is False)):
raise TypeError("Suffix must be a string")
QWidget.__init__(self)
self.suffix = suffix
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.layout.setMargin(0)
self.layout.setContentsMargins(0, 0, 0, 0)
if type_of_field:
tof = QLabel(type_of_field + ": ", self)
if bold:
tof.setStyleSheet('font-weight: bold')
self.layout.addWidget(tof)
self.destroyed.connect(lambda: self._registry.remove(self))
self._registry.append(self)
self._createInputWidget()
self._createTextWidget()
self.setValue(current_value)
top_widgets = QApplication.topLevelWidgets()
for tw in top_widgets:
if tw in self._top_widgets_modified:
continue
self._top_widgets_modified.append(tw)
original_MPE = tw.mousePressEvent
MPE = partial(self._topWidgetMousePressEvent, tw, original_MPE)
tw.mousePressEvent = MPE
# Private Functions #
def _topWidgetMousePressEvent(self, parent, original_mousePressEvent,
event):
"""Overrides a class's mouse press event while still triggering the
original mouse press event. self._freezeInputPrecheck() runs
afterwards.
"""
original_mousePressEvent(event)
self._freezeInputPrecheck()
def _setToEdit(self):
"""When the text of this QClickEdit object is clicked upon, this
function is triggered, which reverts the input field of any other
QClickEdit object in the window to flat text with
_freezeInputPrecheck(), then displays the input field of this object
"""
self._freezeInputPrecheck()
self._showInputField()
def _freezeInputPrecheck(self):
"""Runs _showText() for any input widgets not under mouse"""
for ClickEdit_widget in self._registry:
if (ClickEdit_widget.input_widget.isVisible()) and \
(not ClickEdit_widget.input_widget.underMouse()):
ClickEdit_widget._showText()
def _createTextWidget(self):
"""Creates QPushButton widget that will display the current value as
text when self.input_widget is not displayed."""
self.text = QPushButton("-", self)
self.text.setStyleSheet("text-align: left; margin: 2")
self.text.setFlat(True)
text = self._addSuffix(self.getValue())
self.text.setText(text)
self.text.clicked.connect(self._setToEdit)
self.layout.addWidget(self.text)
def _createInputWidget(self):
"""Creates the user input widget as determined by the child class,
changes this object's focusOutEvent function, then hides the input
widget."""
self.input_widget = self.widget_()
self.input_widget.focusOutEvent = self.focusOutEvent
self.layout.addWidget(self.input_widget)
self.input_widget.hide()
def _addSuffix(self, current_value):
"""Adds specified suffix to displayed text"""
if self.suffix:
text = str(current_value) + ' ' + self.suffix
else:
text = str(current_value)
return text
def _showInputField(self):
"""Hides self.text and displays the input widget"""
self.text.hide()
self.input_widget.show()
def _showText(self):
"""Hides the input widget and displays self.text"""
self.input_widget.hide()
self.text.show()
##########################################
# Public Functions (modified inherited) ###
##########################################
def focusOutEvent(self, event):
"""Runs the original Qt focusOutEvent function, then runs
self._freezeInputPrecheck, which determines the display state of each
QClickEdit object in the window.
The original focusOutEvent function is executed to ensure that any
modifications to it from outside the QClickEdit module will still run.
"""
super(QClickEdit, self).focusOutEvent(event)
self._freezeInputPrecheck()
#####################
# Public Functions ###
#####################
def setSuffix(self, suffix):
"""Set string that will follow displayed value"""
self.setValue(self.getValue(), suffix)
class QSpinBox(QClickEdit):
"""QSpinBox QClickEdit object.
Text displayed becomes QSpinBox field when clicked upon and back to 'flat'
text when clicked away from.
Arguments:
current_value -- integer for QSpinBox to display initially
type_of_field -- if included, this string will precede text/input field
suffix -- if included, this string will appear after text/input field
"""
def __init__(self, current_value, type_of_field=False, suffix=False,
maximum=100, minimum=0, **kwargs):
self.widget_ = SpinBox
QClickEdit.__init__(self, current_value, type_of_field, suffix,
parent=None)
# Execute any kwargs as methods of input widget
# NOT YET IMPLEMENTED OR TESTED ON ALL QCLIKEDEDITS
for key, value in kwargs.items():
widget_func = self.input_widget.__getattribute__(key)
widget_func(value)
self.input_widget.setMaximum(maximum)
self.input_widget.setMinimum(minimum)
self.input_widget.setValue(current_value)
# Private Functions #
def _createInputWidget(self):
QClickEdit._createInputWidget(self)
self.input_widget.setFocusPolicy(Qt.StrongFocus)
self.input_widget.valueChanged.connect(self._updateCurrentValue)
def _updateCurrentValue(self):
self.text.setText(self._addSuffix(self.input_widget.value()))
####################
# Public Functions #
####################
def getValue(self):
"""Returns the current value"""
return self.input_widget.value()
def setValue(self, value, suffix=False):
"""Sets the current value"""
if suffix:
self.suffix = str(suffix)
text = self._addSuffix(value)
self.text.setText(text)
self.input_widget.setValue(value)
class QLineEdit(QClickEdit):
"""QLineEdit QClickEdit object.
Text displayed becomes QLineEdit field when clicked upon and back to 'flat'
text when clicked away from.
Arguments:
current_value -- string to display initially
type_of_field -- if included, this string will precede text/input field
suffix -- if included, this string will appear after text/input field
"""
def __init__(self, current_value, type_of_field=False, suffix=False):
self.widget_ = LineEdit
self._current_value = current_value
QClickEdit.__init__(self, current_value, type_of_field, suffix,
parent=None)
# Private Functions #
def _createInputWidget(self):
QClickEdit._createInputWidget(self)
self.input_widget.setFocusPolicy(Qt.StrongFocus)
self.input_widget.textChanged.connect(self._updateCurrentValue)
def _updateCurrentValue(self):
self.text.setText(self._addSuffix(self.input_widget.text()))
####################
# Public Functions #
####################
def getValue(self):
"""Returns the current value"""
return self.input_widget.text()
def setValue(self, value, suffix=False):
"""Sets the current text"""
if suffix:
self.setSuffix(suffix)
current_value = str(value)
self.input_widget.setText(current_value)
class QTimeEdit(QClickEdit):
"""QTimeEdit QClickEdit object.
Text displayed becomes QTimeEdit field when clicked upon and back to 'flat'
text when clicked away from.
Arguments:
current_time -- Accepts datetime.time or QTime object
type_of_field -- if included, this string will precede text/input field
"""
def __init__(self, current_time, type_of_field=False,
display_format='h:mm:ss a'):
self._inputCheck(current_time)
self._display_format = display_format
self.widget_ = TimeEdit
QClickEdit.__init__(self, self._current_value, type_of_field,
parent=None)
self.setMinimumWidth(100)
self.setMaximumWidth(100)
self.setStyleSheet('margin-left: 0;')
if type_of_field:
type_of_field_space = len(type_of_field) * 5
self.setMaximumWidth(type_of_field_space + 200)
# Private Functions #
def _createInputWidget(self):
QClickEdit._createInputWidget(self)
self.input_widget.setFocusPolicy(Qt.StrongFocus)
self.input_widget.timeChanged.connect(self._updateCurrentValue)
def _setToEdit(self):
QClickEdit._setToEdit(self)
self.input_widget.setDisplayFormat(self._display_format)
def _updateCurrentValue(self):
current_value = self.input_widget.time()
self.text.setText(current_value.toString(self._display_format))
def _inputCheck(self, value):
"""Checks if given time is proper type"""
if isinstance(value, datetime.time):
self._current_value = QTime(value)
elif isinstance(value, QTime):
self._current_value = value
elif value is False:
self._current_value = QTime(0, 0, 0, 0)
else:
raise TypeError("current_time must be datetime.time or QTime "
"object, or set to False")
####################
# Public Functions #
####################
def getValue(self, toPython=False):
"""Returns the currently selected time
as QTime by default, or as datetime object if toPython is True"""
if toPython is True:
return self.input_widget.time().toPython()
return self.input_widget.time()
def setValue(self, value, suffix=False):
"""Set the current time"""
if suffix:
self.setSuffix(suffix)
self._inputCheck(value)
self.text.setText(value.toString('h:mm:ss a'))
self.input_widget.setTime(value)
def setDisplayFormat(self, format_string):
"""Sets format of time displayed in flattened text and QTimeEdit.
Arguments:
format_string -- Use the same formatting for the string as
QTimeEdit.setDisplayFormat()
"""
self.text.setText(self.input_widget.time().toString(format_string))
self.input_widget.setDisplayFormat(format_string)
self._display_format = format_string
class QComboBox(QClickEdit):
"""QComboBox QClickEdit object.
__init__ function argument accepts a list, of which the items will become
the selectable items of the QComboBox. It also accepts a single string or
number, or any other object that can be passed to a str() function, which
will become the sole item of the QComboBox. Additional items may be added
with the addItem() function. Or, more directly, with
self.input_widget.addItem().
"""
def __init__(self, items):
items = self._inputCheck(items)
self.widget_ = ComboBox
QClickEdit.__init__(self, self._current_value, False, parent=None)
for item in items:
self.input_widget.addItem(item)
# Private Functions #
def _createInputWidget(self):
QClickEdit._createInputWidget(self)
self.input_widget.setFocusPolicy(Qt.StrongFocus)
self.input_widget.currentIndexChanged.connect(self._updateCurrentValue)
def _inputCheck(self, values):
items = []
if isinstance(values, list):
self._current_value = str(values[0])
for v in values:
item = str(v)
items.append(item)
else:
items.append(str(values))
return items
def _updateCurrentValue(self):
self.text.setText(self.input_widget.currentText())
####################
# Public Functions #
####################
def getValue(self):
"""Returns the current item in QComboBox input widget"""
return self.input_widget.currentText()
def setValue(self, v):
"""Set current item of QComboBox by value"""
value = str(v)
self.input_widget.setCurrentIndex(self.input_widget.findText(value))
self.text.setText(value)
def setIndex(self, index):
"""Set value of QComboBox by Index"""
self.input_widget.setCurrentIndex(index)
self.text.setText(self.input_widget.currentText())
def getCurrentIndex(self):
return self.input_widget.currentIndex()
def removeIndex(self, index):
self.input_widget.removeItem(index)
def addItem(self, item):
"""Adds an item to the QComboBox"""
item = str(item)
self.input_widget.addItem(item)
def removeItem(self, item):
item = str(item)
self.input_widget.removeItem(self.input_widget.findText(item))