-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgui.py
234 lines (171 loc) · 6.4 KB
/
gui.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
'''Utility functions, decorators and classes to help Qt GUI design.
This file is part of the EARS project <https://github.com/nalamat/ears>
Copyright (C) 2017-2021 Nima Alamatsaz <nima.alamatsaz@gmail.com>
'''
import os
import sys
import logging
import traceback
import functools
from PyQt5 import QtCore, QtWidgets, QtGui
import config
log = logging.getLogger(__name__)
def showError(text1, text2=None, text3=None, title='Error'):
showNormalCursor()
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.setText(text1)
if text2: msg.setInformativeText(text2)
if text3: msg.setDetailedText(text3)
msg.setWindowTitle(title)
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg.setWindowIcon(QtGui.QIcon(config.APP_LOGO))
msg.exec_()
def showException(e=None):
try:
if e: raise e
finally:
text1 = str(sys.exc_info()[1])
if not text1: text1 = 'Unhandled exception occured'
text2 = traceback.format_exc(-1)
text3 = traceback.format_exc()
showError(text1, text2, text3, 'Exception')
def showExceptions(func):
'''Function decorator to log and show exceptions during GUI callbacks.'''
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
log.exception('')
showException()
return wrapper
def logExceptions(func):
'''Function decorator to log exceptions.'''
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except:
log.exception('')
return wrapper
def showQuestion(text1, text2=None, title=config.APP_NAME):
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Question)
msg.setText(text1)
if text2: msg.setInformativeText(text2)
msg.setWindowTitle(title)
msg.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
msg.setWindowIcon(QtGui.QIcon(config.APP_LOGO))
if msg.exec_() == QtWidgets.QMessageBox.Yes:
return True
else:
return False
def getFile(acceptMode, fileMode, nameFilters='', select=''):
if isinstance(nameFilters, str):
nameFilters = [nameFilters]
dlg = QtWidgets.QFileDialog()
dlg.setAcceptMode(acceptMode)
dlg.setFileMode(fileMode)
dlg.setNameFilters(nameFilters)
if select:
select = os.path.realpath(select)
if os.path.isdir(select) or fileMode in (
QtWidgets.QFileDialog.Directory,
QtWidgets.QFileDialog.DirectoryOnly):
dlg.setDirectory(select)
else:
directory, file = os.path.split(select)
dlg.setDirectory(directory)
dlg.selectFile(file)
# dlg.setWindowTitle('Test')
if dlg.exec_() == QtWidgets.QDialog.Accepted:
return dlg.selectedFiles()[0]
else:
return None
def openFile(nameFilters='All files (*)', select=''):
return getFile(QtWidgets.QFileDialog.AcceptOpen,
QtWidgets.QFileDialog.ExistingFile, nameFilters, select)
def saveFile(nameFilters='All files (*)', select=''):
return getFile(QtWidgets.QFileDialog.AcceptSave,
QtWidgets.QFileDialog.AnyFile, nameFilters, select)
def openDirectory(select=''):
return getFile(QtWidgets.QFileDialog.AcceptOpen,
QtWidgets.QFileDialog.DirectoryOnly, '', select)
def makeFileButton(toolTip=''):
btn = QtWidgets.QPushButton()
btn.setIcon(QtGui.QIcon(config.ICONS_DIR + 'folder.svg'))
btn.setFlat(True)
btn.setStyleSheet('padding:0px')
btn.setToolTip(toolTip)
btn.setMaximumWidth(btn.sizeHint().width())
return btn
def centerWindow(window, screenNumber=-1):
'''Center window in the specified screen.
Args:
screenNumber (int): Use -1 for the primary screen and -2 for an
alternate screen (if available). Defaults to the primary screen.
'''
desktop = QtWidgets.QApplication.desktop()
if screenNumber == -1:
# primary screen
screenNumber = desktop.primaryScreen()
elif screenNumber == -2:
# alternate screen
screenNumber = (desktop.primaryScreen()+1) % desktop.screenCount()
elif 0 <= screenNumber < desktop.screenCount():
# selected screen
pass
else:
# invalid screen number, use primary screen
screenNumber = desktop.primaryScreen()
window.move(desktop.availableGeometry(screenNumber).center() -
window.rect().center())
def setCheckState(checkBox, checkState, blockSignals=True):
'''Set check state of a QCheckBox while optionally blocking its signals.'''
if not isinstance(checkBox, QtWidgets.QCheckBox):
raise TypeError('`checkBox` should be an instance of `QCheckBox`')
if blockSignals: checkBox.blockSignals(True)
checkBox.setCheckState(checkState)
if blockSignals: checkBox.blockSignals(False)
def showBusyCursor():
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
def showNormalCursor():
QtWidgets.QApplication.restoreOverrideCursor()
class BusyCursor():
'''Show busy cursor when entering the context manager.
Example:
with BusyCursor():
do_a_long_process()
'''
def __enter__(self):
showBusyCursor()
def __exit__(self, *args):
showNormalCursor()
def busyCursor(func):
'''Function decorator to show busy cursor when executing `func`.'''
@functools.wraps(func)
def wrapper(*args, **kwargs):
with BusyCursor():
func(*args, **kwargs)
return wrapper
class QSeparator(QtWidgets.QFrame):
def __init__(self, orientation, *args, **kwargs):
super().__init__(*args, **kwargs)
orientation = orientation.lower()
if orientation=='v' or orientation=='ver' or orientation=='vertical':
self.setFrameShape(QtWidgets.QFrame.VLine)
elif orientation=='h' or orientation=='hor' or orientation=='horizontal':
self.setFrameShape(QtWidgets.QFrame.HLine)
else:
raise ValueError('Invalid orientation')
self.setFrameShadow(QtWidgets.QFrame.Raised)
class QVSeparator(QSeparator):
def __init__(self, *args, **kwargs):
super().__init__('v', *args, **kwargs)
class QHSeparator(QSeparator):
def __init__(self, *args, **kwargs):
super().__init__('h', *args, **kwargs)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
print(openFile())