def __init__(self, *args): QApplication.__init__(self, *args) try: # Импорт модулей from classes import constants from classes.logger import log, reroute_output # Отметка начала сессии import time self.__start_time = time.time() # Время начала инициализации log.info("------------------------------------------------") locale.setlocale(locale.LC_ALL, 'ru') log.info( time.strftime("%d %B %Y %H:%M:%S", time.localtime()).center( 48)) # Пример: 26 Август 2019 16:14:04 log.info('Запуск новой сессии'.center(48)) from classes import ui_util # Перенаправляем stdout и stderr в логер reroute_output() except (ImportError, ModuleNotFoundError) as ex: tb = traceback.format_exc() QMessageBox.warning( None, "Ошибка импорта модулей", "Модуль: %(name)s\n\n%(tb)s" % { "name": ex.name, "tb": tb }) # Остановить запуск и выйти sys.exit() except Exception: sys.exit() # Запись служебной информации try: log.info("------------------------------------------------") log.info(("%s (version %s)" % (constants.APP_NAME, constants.VERSION)).center(48)) log.info("------------------------------------------------") log.info("Платформа: %s" % platform.platform()) log.info("Процессор: %s" % platform.processor()) log.info("Тип: %s" % platform.machine()) log.info("Python: %s" % platform.python_version()) log.info("Qt: %s" % QT_VERSION_STR) log.info("PyQt: %s" % PYQT_VERSION_STR) log.info("------------------------------------------------") except Exception: pass log.info("Подключаем сигнал окончания сессии") self.aboutToQuit.connect(self.on_log_the_end) log.info( "Подключаем переменные необходимые для правильной работы приложения" ) self.setApplicationName(constants.APP_NAME) self.setApplicationDisplayName(constants.APP_NAME_RUS) self.setOrganizationName(constants.COMPANY) self.setApplicationVersion(constants.VERSION) log.info("Инициализация настроек") App.settings = QSettings() log.info("Инициализируем ловца необработанных исключений") from classes import exceptions sys.excepthook = exceptions.exception_handler log.info("Подключаем файл ресурсов приложения") from resources import resources resources.qInitResources() log.info("Создаем объект базы данных") from classes.database import Database App.db = Database() App.user_id = None log.info("Установка темы Fusion") self.setStyle(QStyleFactory.create("Fusion")) log.info("Загружаем и устанавливаем шрифт приложения") try: font_path = ":/fonts/roboto.ttf" font_id = QFontDatabase.addApplicationFont(font_path) font_family = QFontDatabase.applicationFontFamilies(font_id)[0] font = QFont(font_family) font.setPointSizeF(12) QApplication.setFont(font) except Exception as ex: log.error("Ошибка установки шрифта roboto.ttf: %s" % str(ex)) log.info("Создаем главное окно приложения") from view.main_window import MainWindow App.main_window = MainWindow() log.info("------------------------------------------------") log.info("Инициализация приложения завершена".center(48)) elapsed_time = time.time() - self.__start_time log.info(("Потребовалось времени: %.3f сек" % elapsed_time).center(48)) log.info("------------------------------------------------") # Сигнал о завершении загрузки приложения self.app_loading_is_complete.emit()
def main(): app = QtWidgets.QApplication(sys.argv) view = MainWindow() model = Repository() presenter = Presenter(view, model) view.show() sys.exit(app.exec_())
class StartupWidget(QWidget): def __init__(self): QWidget.__init__(self) self.ui = Ui_StartupWidget() self.ui.setupUi(self) self.ui.new_project_button.clicked.connect( self.on_clicked_new_project_button) self.ui.open_project_button.clicked.connect( self.on_clicked_open_project_button) self.new_project_window = NewProjectDialog() self.main_window = None self.new_project_window.back_to_startup.connect( self.open_start_up_widget) self.new_project_window.new_project_canceled.connect( self.open_start_up_widget) self.new_project_window.close_old_project.connect( self.close_old_project) def on_clicked_new_project_button(self): self.new_project_window.setWindowTitle('新規プロジェクトを作成') self.new_project_window.come_from_main_window_flag = False self.new_project_window.show() self.close() def on_clicked_open_project_button(self): project_file_path = QFileDialog.getOpenFileName( self, 'プロジェクトを開く', os.path.expanduser('~'), AppInfo().app_name() + ' プロジェクト(*.sdt);;すべてのファイル(*.*)')[0] if not project_file_path: return self.move_to_main_window(project_file_path) def move_to_main_window(self, project_file_path): Project.load_settings_file(project_file_path) project_name = os.path.basename(os.path.splitext(project_file_path)[0]) window_title = project_name + ' - ' + AppInfo().app_name( ) + ' Version ' + AppInfo().version() self.main_window = MainWindow() self.main_window.setWindowTitle(window_title) self.main_window.show() self.close() self.main_window.back_to_new_project.connect( self.new_project_window.open_new_project_widget) self.main_window.back_to_startup.connect(self.open_start_up_widget) def open_start_up_widget(self): self.setWindowTitle(AppInfo().app_name() + ' Version ' + AppInfo().version()) if self.main_window: self.main_window = MainWindow() self.show() def close_old_project(self): self.main_window = self.new_project_window.main_window
def handle_login(self, login_result): if login_result == 1: msg_box(self, '提示', '用户名不存在,请重试!') return if login_result == 11: msg_box(self, '提示', '用户名或密码错误!') return if login_result == 111: username = self.username_lineEdit.text() self.main_window = MainWindow(username=username, role=self.role) self.main_window.show() self.close()
def move_to_main_window(self, project_file_path): Project.load_settings_file(project_file_path) project_name = os.path.basename(os.path.splitext(project_file_path)[0]) window_title = project_name + ' - ' + AppInfo().app_name( ) + ' Version ' + AppInfo().version() self.main_window = MainWindow() self.main_window.setWindowTitle(window_title) self.main_window.show() self.close() self.main_window.back_to_new_project.connect( self.new_project_window.open_new_project_widget) self.main_window.back_to_startup.connect(self.open_start_up_widget)
def handle_login(self, login_result): """ 执行登陆结果 :param login_result: 登陆处理TAG :return: 登陆出错返回 """ if login_result == 1: msg_box(self, '提示', '用户名不存在,请重试!') return if login_result == 11: msg_box(self, '提示', '用户名或密码错误!') return if login_result == 111: username = self.username_lineEdit.text() self.main_window = MainWindow(login=self, username=username, role=self.role) self.main_window.show() self.close()
def on_clicked_create_button(self): save_location_path = self.ui.save_location_line.text() project_name = os.path.basename(self.ui.project_name_line.text()) if not self.is_valid_character(project_name, save_location_path): self.msgBox = QMessageBox() self.msgBox.setText( 'プロジェクト名またはディレクトリ名に、使用できない文字が含まれています。\n' '全角文字や特殊記号が使われている場合は、名前を変えるか別のディレクトリに変更してください。') self.msgBox.exec() return dir_paths = [ os.path.join(save_location_path, 'dataset/test/OK'), os.path.join(save_location_path, 'dataset/test/NG'), os.path.join(save_location_path, 'dataset/train/OK'), os.path.join(save_location_path, 'dataset/truncated'), os.path.join(save_location_path, 'inspection_results'), os.path.join(save_location_path, 'inspection_results/images'), os.path.join(save_location_path, 'tmp'), os.path.join(save_location_path, 'models') ] for dir_path in dir_paths: os.makedirs(dir_path, exist_ok=True) # プロジェクトファイル作成部分 project_path = save_location_path Project.generate_project_file(project_path, project_name) window_title = project_name + ' - ' + AppInfo().app_name( ) + ' Version ' + AppInfo().version() self.main_window = MainWindow() self.main_window.setWindowTitle(window_title) self.main_window.show() self.close_old_project.emit() self.close() self.main_window.back_to_new_project.connect( self.open_new_project_widget) self.main_window.back_to_startup.connect( self.on_back_to_startup_signal)
def build(self): main_window = MainWindow(self.__reversed_mode) if self.__geo_file_name is not None: main_window.load_geometry([self.__geo_file_name]) if self.__words_file_name is not None: main_window.load_words([self.__words_file_name]) return main_window
def __init__(self): self.mod = Model() self.mw = MainWindow() for button, t in [(self.mw.unity_radio_button, 'umf_'), \ (self.mw.percent_wt_radio_button, 'mass_perc_'), \ (self.mw.percent_mol_radio_button, 'mole_perc_')]: button.config(command=partial(self.update_oxide_entry_type, t)) self.mw.file_menu.add_command(label="Recipes", command=self.open_recipe_menu) self.mw.file_menu.add_command(label="Save", command=self.save_recipe) self.mw.file_menu.add_command(label="Save as new recipe", command=self.save_new_recipe) #self.mw.options_menu.add_command(label="Edit Oxides", command=None) self.mw.options_menu.add_command(label="Edit Ingredients", command=self.open_ingredient_editor) self.mw.options_menu.add_command( label="Edit Other Restrictions", command=self.open_other_restriction_editor) #self.mw.options_menu.add_command(label="Restriction Settings", command=self.open_ingredient_editor) self.mw.calc_button.config(command=self.calc_restr) # Create and grid ingredient selection buttons: for r, i in enumerate(self.mod.order["ingredients"]): self.mw.ingredient_select_button[i] = ttk.Button(self.mw.ingredient_vsf.interior, text=self.mod.ingredient_dict[i].name, \ width=20, command=partial(self.toggle_ingredient, i)) self.mw.ingredient_select_button[i].grid(row=r) # Create and grid other selection buttons: for r, j in enumerate(self.mod.order["other"]): self.mw.other_select_button[j] = ttk.Button(self.mw.other_vsf.interior, text=prettify(self.mod.other_dict[j].name), \ width=20, command=partial(self.toggle_other, j)) self.mw.other_select_button[j].grid(row=r + 1) # Create DisplayRestriction dictionary self.display_restr_dict = {} for key in self.mod.restr_keys(): self.display_restr_dict[key] = DisplayRestriction(self.mw.restriction_sf.interior, self.mw.x_lab, self.mw.y_lab, \ key, self.mod.restr_dict[key].name, self.mod.restr_dict[key].default_low, self.mod.restr_dict[key].default_upp) # Open default recipe. self.open_recipe('0') self.reset_relations = True
def __init__(self, argv): super(BrenoColaApplication, self).__init__(argv) self.__state = self.STATES["NONE"] self.__list_elements = [] self.__clipb = self.clipboard() self.__clipb.dataChanged.connect(self.copy) self.__ignore_paste = False self.w = MainWindow() self.w.window.stackRadioButton.toggled.connect( lambda toggle: self.change_state(toggle, self.STATES["STACK"])) self.w.window.listRadioButton.toggled.connect( lambda toggle: self.change_state(toggle, self.STATES["LIST"])) self.w.window.concatRadioButton.toggled.connect( lambda toggle: self.change_state(toggle, self.STATES["CONCAT"])) self.w.window.randomRadioButton.toggled.connect( lambda toggle: self.change_state(toggle, self.STATES["RANDOM"])) self.paste_signal.connect(self.paste) self.thread_listen_paste = PasteEventSignal(self, self.paste_signal) self.thread_listen_paste.start() self.update_info_labels()
from PySide import QtCore from PySide import QtGui from model.KerasWrapper import KerasWrapper from model.parameters import Parameters import sys from view.main_window import MainWindow # @NoMove if __name__ == '__main__': app = QtGui.QApplication(sys.argv) # pixmap = QtGui.QPixmap('./../poster_data/Valar-Morghulis.png') pixmap = QtGui.QPixmap('./../poster_data/havran_super.png') pixmap = pixmap.scaled(QtCore.QSize(600, 400), aspectMode=QtCore.Qt.KeepAspectRatio, mode=QtCore.Qt.SmoothTransformation) splash = QtGui.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint) splash.setMask(pixmap.mask()) app.processEvents() splash.show() neural_network = KerasWrapper() #neural_network.run_for_all_characters() #neural_network.raw_data.to_csv('./../datasets/cleaned_data.csv') app.setStyle('Plastique') ex = MainWindow(neural_network) ex.show() splash.finish(ex) sys.exit(app.exec_())
from db.models.bill import Bill from db.models.address import Address from db.models.costumer import Costumer from db.models.store import Store from db.models.food import Food from db.models.logs import Log from db.connect import Base, engine from view.main_window import MainWindow if __name__ == '__main__': import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG) Base.metadata.create_all(engine) view = MainWindow() # view.show_menu() # for reserve view.run() # for add and update
class LoginWindow(Ui_Form, QWidget): login_done_signal = pyqtSignal(int) def __init__(self): """ 登陆界面类构造函数,初始化类属性等. """ super(LoginWindow, self).__init__() self.setupUi(self) self.role = None self.init_ui() self.main_window = None self.register_win = None self.init_slot() def init_ui(self): """ 初始化界面UI元素 """ self.setWindowTitle('用户登录') self.setWindowIcon(QIcon(APP_ICON)) self.login_pushButton.setProperty('class', 'Aqua') self.register_pushButton.setProperty('class', 'Aqua') self.setStyleSheet(SYS_STYLE) self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint) def init_slot(self): """ 初始化信号槽连接 """ self.register_pushButton.clicked.connect( lambda: self.btn_slot('register')) self.login_pushButton.clicked.connect(lambda: self.btn_slot('login')) self.login_done_signal.connect(self.handle_login) def btn_slot(self, tag): """ 按钮点击事件槽函数 :param tag: 点击的按钮的TAG :return: 出错返回,不执行后续操作逻辑 """ # 注册 if tag == 'register': self.register_win = RegisterWindow() self.register_win.show() # 登陆 if tag == 'login': username = self.username_lineEdit.text() password = self.password_lineEdit.text() if '' in [username, password]: msg_box(self, '提示', '请输入用户名或密码!') return login_th = Thread(target=self.login, args=(username, password)) login_th.start() def login(self, username, password): """ 登陆子线程用户验证 :param username: 需要验证的用户名 :param password: 匹配的密码 :return: 验证出错返回,并发射相应TAG的信号 """ db = DBHelp() count, res = db.query_super(table_name='user', column_name='username', condition=username) if count == 0: self.login_done_signal.emit(1) return if get_md5(password) != res[0][2]: self.login_done_signal.emit(11) return self.role = res[0][3] self.login_done_signal.emit(111) def handle_login(self, login_result): """ 执行登陆结果 :param login_result: 登陆处理TAG :return: 登陆出错返回 """ if login_result == 1: msg_box(self, '提示', '用户名不存在,请重试!') return if login_result == 11: msg_box(self, '提示', '用户名或密码错误!') return if login_result == 111: username = self.username_lineEdit.text() self.main_window = MainWindow(login=self, username=username, role=self.role) self.main_window.show() self.close() def keyPressEvent(self, QKeyEvent): """ 监听键盘触发事件,通过判断是否按下的按键为Enter或者Return键 :param QKeyEvent: 键盘触发事件 """ if QKeyEvent.key() == Qt.Key_Enter or QKeyEvent.key() == Qt.Key_Return: self.login_pushButton.click()
import sys import os base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(base_dir) from PyQt5.QtWidgets import QApplication from model.experiment import Experiment from view.main_window import MainWindow # from view.monitor import MonitorWindow as MainWindow experiment = Experiment() experiment.load_config('experiment.yml') experiment.initialize() app = QApplication([]) window = MainWindow(experiment) window.show() app.exec() experiment.finalize()
def open_start_up_widget(self): self.setWindowTitle(AppInfo().app_name() + ' Version ' + AppInfo().version()) if self.main_window: self.main_window = MainWindow() self.show()
def on_back_to_startup_signal(self): self.back_to_startup.emit() self.main_window = MainWindow()
class NewProjectDialog(QWidget): # Signal for cancel button back_to_startup = pyqtSignal() new_project_canceled = pyqtSignal() close_old_project = pyqtSignal() def __init__(self): QWidget.__init__(self) self.ui = Ui_NewProjectDialog() self.ui.setupUi(self) self.ui.project_name_line.textEdited.connect( self.sync_project_name_edit) self.ui.save_location_line.textEdited.connect( self.sync_save_location_edit) self.ui.reference_button.clicked.connect( self.on_clicked_reference_button) self.ui.create_button.clicked.connect(self.on_clicked_create_button) self.ui.cancel_button.clicked.connect(self.on_clicked_cancel_button) self.ui.save_location_line.returnPressed.connect( self.on_clicked_create_button) self.ui.project_name_line.returnPressed.connect( self.on_clicked_create_button) self.set_create_button_enabled() self.ui.save_location_line.setText(os.path.expanduser('~') + '/') self.main_window = None self.come_from_main_window_flag = False self.msgBox = None # '/'の入力を制限(validation) reg_ex = QRegExp("[^\\\/:\*\?\"<>|]+") validator = QRegExpValidator(reg_ex, self.ui.project_name_line) self.ui.project_name_line.setValidator(validator) def on_clicked_reference_button(self): save_location_path = QFileDialog.getExistingDirectory( self, '保存先フォルダを選択', os.path.expanduser('~')) if save_location_path: self.ui.save_location_line.setText(save_location_path + '/') def on_clicked_create_button(self): save_location_path = self.ui.save_location_line.text() project_name = os.path.basename(self.ui.project_name_line.text()) if not self.is_valid_character(project_name, save_location_path): self.msgBox = QMessageBox() self.msgBox.setText( 'プロジェクト名またはディレクトリ名に、使用できない文字が含まれています。\n' '全角文字や特殊記号が使われている場合は、名前を変えるか別のディレクトリに変更してください。') self.msgBox.exec() return dir_paths = [ os.path.join(save_location_path, 'dataset/test/OK'), os.path.join(save_location_path, 'dataset/test/NG'), os.path.join(save_location_path, 'dataset/train/OK'), os.path.join(save_location_path, 'dataset/truncated'), os.path.join(save_location_path, 'inspection_results'), os.path.join(save_location_path, 'inspection_results/images'), os.path.join(save_location_path, 'tmp'), os.path.join(save_location_path, 'models') ] for dir_path in dir_paths: os.makedirs(dir_path, exist_ok=True) # プロジェクトファイル作成部分 project_path = save_location_path Project.generate_project_file(project_path, project_name) window_title = project_name + ' - ' + AppInfo().app_name( ) + ' Version ' + AppInfo().version() self.main_window = MainWindow() self.main_window.setWindowTitle(window_title) self.main_window.show() self.close_old_project.emit() self.close() self.main_window.back_to_new_project.connect( self.open_new_project_widget) self.main_window.back_to_startup.connect( self.on_back_to_startup_signal) def on_clicked_cancel_button(self): if self.come_from_main_window_flag: self.close() return self.new_project_canceled.emit() self.close() def sync_project_name_edit(self, text): project_name = text save_location_path = self.ui.save_location_line.text() save_dir_path = os.path.dirname(save_location_path) path = os.path.join(save_dir_path, project_name) self.ui.save_location_line.setText(path) self.set_create_button_enabled() def sync_save_location_edit(self, text): save_location_path = text project_name = os.path.basename(save_location_path) self.ui.project_name_line.setText(project_name) self.set_create_button_enabled() def set_create_button_enabled(self): if self.ui.project_name_line.text(): self.ui.create_button.setEnabled(True) elif not self.ui.project_name_line.text(): self.ui.create_button.setEnabled(False) def open_new_project_widget(self): self.come_from_main_window_flag = True self.show() def on_back_to_startup_signal(self): self.back_to_startup.emit() self.main_window = MainWindow() def is_valid_character(self, project_name, save_location_path): forbidden_characters = ['\\', ':', '*', '?', '"', '<', '>', '|'] for letter in project_name: if unicodedata.east_asian_width( letter) != 'Na' or letter in forbidden_characters: return False else: continue for letter2 in save_location_path: if unicodedata.east_asian_width(letter2) != 'Na': return False else: continue return True
import os.path from sys import argv, exit from qtpy.QtWidgets import QApplication from controller import RegisterController from controller.main_controller import MainController from model import init_database, Account from utils import get_app_folder from view import RegisterDialog from view.main_window import MainWindow if __name__ == '__main__': app = QApplication(argv) init_database(os.path.join(get_app_folder(), "database.sqlite")) accounts = Account.select() if not accounts: register_controller = RegisterController() register_dialog = RegisterDialog(register_controller) register_dialog.exec() controller = MainController() window = MainWindow(controller) exit(app.exec_())
class LoginWindow(Ui_Form, QWidget): login_done_signal = pyqtSignal(int) def __init__(self): super(LoginWindow, self).__init__() self.setupUi(self) self.role = None self.init_ui() self.main_window = None self.register_win = None self.init_slot() def init_ui(self): self.setWindowTitle('用户登录') self.setWindowIcon(QIcon(APP_ICON)) def init_slot(self): self.register_pushButton.clicked.connect( lambda: self.btn_slot('register')) self.login_pushButton.clicked.connect(lambda: self.btn_slot('login')) self.login_done_signal.connect(self.handle_login) def btn_slot(self, tag): if tag == 'register': self.register_win = RegisterWindow() self.register_win.show() if tag == 'login': username = self.username_lineEdit.text() password = self.password_lineEdit.text() if username == '' or password == '': msg_box(self, '提示', '请输入用户名或密码!') return login_th = Thread(target=self.login, args=(username, password)) login_th.start() def login(self, username, password): db = DBHelp() count, res = db.query_super(table_name='user', column_name='username', condition=username) if count == 0: self.login_done_signal.emit(1) return if get_md5(password) != res[0][2]: self.login_done_signal.emit(11) return self.role = res[0][3] self.login_done_signal.emit(111) def handle_login(self, login_result): if login_result == 1: msg_box(self, '提示', '用户名不存在,请重试!') return if login_result == 11: msg_box(self, '提示', '用户名或密码错误!') return if login_result == 111: username = self.username_lineEdit.text() self.main_window = MainWindow(username=username, role=self.role) self.main_window.show() self.close()