-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
193 lines (170 loc) · 6.44 KB
/
main.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
<application name>
Copyright ©<year> <author>
Licensed under the terms of the <LICENSE>.
See LICENSE for details.
@author: <author>
"""
# Built-in imports
from __future__ import division, unicode_literals, print_function
import sys
import os
import os.path as osp
import subprocess
import ctypes
import logging
import argparse
#%% Setup PyQt's v2 APIs. Must be done before importing PyQt or PySide
import rthook
#%% Third-party imports
from qtpy import QtCore, QtGui, QtWidgets, uic
import six
#%% Global functions
# PyInstaller utilities
def frozen(filename):
"""Returns the filename for a frozen file (program file which may be
included inside the executable created by PyInstaller).
"""
if getattr(sys, 'frozen', False):
return osp.join(sys._MEIPASS, filename)
else:
return filename
# I usually need some sort of file/dir opening function
if sys.platform == 'darwin':
def show_file(path):
subprocess.Popen(['open', '--', path])
def open_default_program(path):
subprocess.Popen(['start', path])
elif sys.platform == 'linux2':
def show_file(path):
subprocess.Popen(['xdg-open', '--', path])
def open_default_program(path):
subprocess.Popen(['xdg-open', path])
elif sys.platform == 'win32':
def show_file(path):
subprocess.Popen(['explorer', '/select,', path])
open_default_program = os.startfile
#%% Simple thread example (always useful to avoid locking the GUI)
class CallbackThread(QtCore.QThread):
"""Simple threading example.
The thread executes a callback function. Use self if you want to store
variables as the thread instance's attributes. It is also useful to use
arguments as default values. This examples prints after 2 seconds:
>>> def callback_fcn(self, t=2):
... self.sleep(t)
... print("Thread Finished")
...
>>> thread = CallbackThread()
>>> thread.callback = callback_fcn
>>> thread.start() # Finishes after 2 seconds
"""
def __init__(self, *args, **kwargs):
super(CallbackThread, self).__init__(*args, **kwargs)
self.callback = lambda *args: None
self.ret = None
def __del__(self):
self.wait()
def run(self):
self.ret = self.callback(self)
#%% Qt-enabled logging handler. Allows logging to GUI
class ConsoleWindowLogHandler(logging.Handler, QtCore.QObject):
"""Qt-enabled logging handler
Allows logging to GUI by connecting the ``log`` signal to the receiving
object's slot.
"""
# Qt signals
log = QtCore.Signal(str, name="log")
def __init__(self, parent=None):
super(ConsoleWindowLogHandler, self).__init__()
QtCore.QObject.__init__(self, parent)
def emit(self, logRecord):
message = six.text_type(self.format(logRecord))
self.log.emit(message)
#%% Main window class
class WndMain(QtWidgets.QMainWindow):
### Initialization
def __init__(self, *args, **kwargs):
super(WndMain, self).__init__(*args, **kwargs)
# Setup settings storage
self.settings = QtCore.QSettings("settings.ini",
QtCore.QSettings.IniFormat)
# Initialize UI (open main window)
self.initUI()
# Logging setup
consoleHandler = ConsoleWindowLogHandler(self.txtLog)
logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
consoleHandler.setFormatter(logger.handlers[0].formatter)
logger.name = "<app_name>"
logger.addHandler(consoleHandler)
consoleHandler.log.connect(self.on_consoleHandler_log)
self.logger = logger
# Threading example with new-style connections
self.thread = CallbackThread(self)
def callback_fcn(self, t=2): # Use defaults to pass arguments
self.sleep(t)
logging.info("Thread finished.") # Shouldn't translate log msgs
self.thread.callback = callback_fcn
self.thread.finished.connect(self.on_thread_finished)
self.thread.start()
def initUI(self):
ui_file = frozen(osp.join('data', 'wndmain.ui'))
uic.loadUi(ui_file, self)
# Load window geometry and state
self.restoreGeometry(self.settings.value("geometry", b""))
self.restoreState(self.settings.value("windowState", b""))
self.show()
### Function overrides:
def closeEvent(self, e):
# Write window geometry and state to config file
self.settings.setValue("geometry", self.saveGeometry())
self.settings.setValue("windowState", self.saveState())
e.accept()
### Qt slots
@QtCore.Slot()
def on_thread_finished(self):
QtWidgets.QMessageBox.information(self,
self.tr("Information"),
self.tr("Thread finished."))
@QtCore.Slot(str)
def on_consoleHandler_log(self, message):
self.txtLog.appendPlainText(message)
#%% Main execution
# Runs when executing script directly (not importing).
if __name__ == '__main__':
### Properly register window icon
myappid = u'br.com.dapaixao.pyqtskeleton.1.0'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
### Grab existing QApplication
# Only one QApplication is allowed per process. This allows running inside
# Qt-based IDEs like Spyder.
existing = QtWidgets.qApp.instance()
if existing:
app = existing
else:
app = QtWidgets.QApplication(sys.argv)
### Parsing command-line arguments/options
parser = argparse.ArgumentParser()
parser.add_argument("--lang", nargs="?",
help="Language to run (override system language)")
try:
args = parser.parse_args()
except:
parser.print_help()
sys.exit(-1)
lang = args.lang or QtCore.QLocale.system().name()
### Setup internationalization/localization (i18n/l10n)
translator = QtCore.QTranslator()
translator.load(frozen(osp.join("data", "main_{}.qm".format(lang))))
QtWidgets.qApp.installTranslator(translator)
QtCore.QLocale().setDefault(QtCore.QLocale(lang))
### Create main window and run
wnd = WndMain()
if existing:
self = wnd # Makes it easier to debug with Spyder's F9 inside a class
else:
sys.exit(app.exec_())