def main(): import time os.chdir(civiltools_path) app = QtWidgets.QApplication(sys.argv) splash_pix = QPixmap("./images/civil-engineering.jpg") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(False) # adding progress bar progressBar = QProgressBar(splash) progressBar.setMaximum(10) progressBar.setGeometry(50, splash_pix.height() - 30, splash_pix.width() - 100, 20) splash.show() splash.showMessage("<h1><font color='DarkRed'>civiltools by Ebrahim Raeyat Roknabadi </font></h1>", Qt.AlignCenter | Qt.AlignCenter, Qt.black) for i in range(1, 11): progressBar.setValue(i) t = time.time() while time.time() < t + 0.1: app.processEvents() # Simulate something that takes time time.sleep(1) # translator = QtCore.QTranslator() # translator.load("main_form.qm") # app.installTranslator(translator) window = FormWidget() window.setWindowTitle(_appname + ' ' + _version) window.show() splash.finish(window) sys.exit(app.exec_())
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. """ setup_logging() logging.info('Starting Mu {}'.format(__version__)) # The app object is the application running on your computer. app = QApplication(sys.argv) # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('icon')) splash.show() # Create the "window" we'll be looking at. editor_window = Window() # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.theme) editor.restore_session() # Connect the various buttons in the window to the editor. button_bar = editor_window.button_bar button_bar.connect("new", editor.new, "Ctrl+N") button_bar.connect("load", editor.load, "Ctrl+O") button_bar.connect("save", editor.save, "Ctrl+S") button_bar.connect("flash", editor.flash) button_bar.connect("repl", editor.toggle_repl) button_bar.connect("zoom-in", editor.zoom_in) button_bar.connect("zoom-out", editor.zoom_out) button_bar.connect("theme", editor.toggle_theme) button_bar.connect("quit", editor.quit) # Finished starting up the application, so hide the splash icon. splash.finish(editor_window) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def main(): if sys.version_info < REQUIRED_PYTHON_VERSION: raise SystemExit("Python {}.{} or higher is required".format( REQUIRED_PYTHON_VERSION[0], REQUIRED_PYTHON_VERSION[1])) # QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = Application(sys.argv) loop = quamash.QEventLoop(app) asyncio.set_event_loop(loop) pixmap = QPixmap('OptoStimLogo.jpeg') splash = QSplashScreen(pixmap) splash.show() w = OptoStimMainWindow() w.show() splash.finish(w) hook = ExceptHook(sentry_key=SENTRY_KEY, non_exit_exceptions=[DeviceException, OptoStimException]) sys.excepthook = hook.except_hook signal.signal(signal.SIGINT, w.clean_up) signal.signal(signal.SIGTERM, w.clean_up) try: with loop: sys.exit(loop.run_forever()) finally: w.clean_up()
def run(image_path = None): # Global exceptions sys.excepthook = excepthook app = QApplication(sys.argv) # Splash screen splash_pix = QPixmap('resources/splash.jpg') splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Load translation locale_code = SettingsModel().get('Language', 'code') if locale_code != "en_US": # Standard language # Standard translator for the generated GUI translator = QTranslator() translator.load('localization/' + locale_code + '.qm') app.installTranslator(translator) # Translator for various GUI elements translator_2 = QTranslator() translator_2.load('localization/' + locale_code + '_2.qm') app.installTranslator(translator_2) # Start m = Hitagi(image_path) # Pass image path splash.finish(m) sys.exit(app.exec())
def init(bootstrap_function): """ Init gui. Concat all files from style directory and apply stylesheet. Run `bootstrap_function` to prepare app. """ app = QApplication(sys.argv) app.setWindowIcon(QIcon(os.path.join(options.STATIC_DIR, 'splash.png'))) splash_img = QPixmap(os.path.join(options.STATIC_DIR, 'splash.png')) splash = QSplashScreen(splash_img) splash.show() app.processEvents() items = bootstrap_function() style = [] style_dir = os.path.join(options.STATIC_DIR, 'style') for f in os.listdir(style_dir): if not f.endswith('.qss'): continue with open(os.path.join(style_dir, f), 'r') as qss: style.append(qss.read()) app.setStyleSheet('\n'.join(style)) mw = MainWindow(items) splash.finish(mw) sys.exit(app.exec_())
def welcomeExactDialog(app, settingsObject, mainwindow): # Create and display the about screen splash_pix = QPixmap(ARTWORK_DIR_NAME+'ExactWelcomeScreen.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) btn = QPushButton('Enable EXACT', splash) btn.move(140, 320) btn.clicked.connect(partial(enableAndClose, splash, settingsObject,mainwindow)) btn = QPushButton('Disable EXACT',splash) btn.move(350, 320) btn.clicked.connect(partial(disableAndClose, splash, settingsObject,mainwindow)) # layout.addWidget(btn, 1,1) # splash.showMessage('Version %s\n'%version, alignment = Qt.AlignHCenter + Qt.AlignBottom, color=Qt.black) splash.setMask(splash_pix.mask()) splash.show() splash.mousePressEvent = partial(closeDlg, splash) start = time() while splash.isActiveWindow() & (time() - start < 10): sleep(0.001) app.processEvents() if (splash.isActiveWindow()): splash.close()
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. """ setup_logging() logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__)) logging.info(platform.uname()) # The app object is the application running on your computer. app = QApplication(sys.argv) # Create the "window" we'll be looking at. editor_window = Window() # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) editor.setup(setup_modes(editor, editor_window)) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.debug_toggle_breakpoint, editor.theme) # capture the filename passed by the os, if there was one passed_filename = sys.argv[1] if len(sys.argv) > 1 else None editor.restore_session(passed_filename) # Connect the various UI elements in the window to the editor. status_bar = editor_window.status_bar status_bar.connect_logs(editor.show_logs, 'Ctrl+Shift+D') status_bar.connect_mode(editor.select_mode, 'Ctrl+Shift+M') # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('splash-screen')) splash.show() # Finished starting up the application, so hide the splash icon. splash_be_gone = QTimer() splash_be_gone.timeout.connect(lambda: splash.finish(editor_window)) splash_be_gone.setSingleShot(True) splash_be_gone.start(5000) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def main(sys): app = QApplication(sys.argv) show_splash = True for token in sys.argv: if token == '-nosplash' or token == '--nosplash': show_splash = False elif token == '-h' or token == '-help' or token == '--help': print('pdgui - graphical user interface to the PDielec package') print('pdgui [-help] [-debug] [program] [filename] [spreadsheet] [-script scriptname] [-nosplash] [-exit]') exit() if show_splash: dirname = os.path.dirname(os.path.realpath(sys.argv[0])) splashfile = os.path.join(dirname, 'Python/GUI/splash.png') pixmap = QPixmap(splashfile) splash = QSplashScreen(pixmap) progressbar = QProgressBar(splash) splash.show() else: progressbar = QProgressBar() progressbar = None ex = App(sys.argv, progressbar) ex.show() if show_splash: splash.finish(ex) sys.exit(app.exec_())
def make_splash(): splash_pic = QPixmap('oncat/img/splash.png') splash = QSplashScreen(splash_pic, Qt.WindowStaysOnTopHint) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(True) splash.show() return splash
def main(): # The app object is the application running on your computer. app = QApplication(sys.argv) app.setStyleSheet(load_stylesheet('puppy.css')) # A splash screen is a logo that appears when you start up the application. # The image to be "splashed" on your screen is in the resources/images # directory. splash = QSplashScreen(load_pixmap('splash')) # Show the splash. splash.show() # Make the editor with the Puppy class defined above. the_editor = Puppy() proj_root = os.path.join(ROOT, 'hello_world') proj = HelloWorld(proj_root, {}) if not os.path.isdir(proj_root): proj.init_files() the_editor.add_project(proj) the_editor.show() the_editor.autosize_window() # Remove the splash when the_editor has finished setting itself up. splash.finish(the_editor) # Stop the program after application finishes executing. sys.exit(app.exec_())
def show(): message = "{0} {1} ".format(appinfo.appname, appinfo.version) pixmap = QPixmap(os.path.join(__path__[0], 'splash3.png')) if QApplication.desktop().screenGeometry().height() < 640: fontsize = 23 pixmap = pixmap.scaledToHeight(240, Qt.SmoothTransformation) else: fontsize = 40 splash = QSplashScreen(pixmap, Qt.SplashScreen) font = splash.font() font.setPixelSize(fontsize) font.setWeight(QFont.Bold) splash.setFont(font) splash.showMessage(message, Qt.AlignRight | Qt.AlignTop, Qt.white) splash.show() QApplication.processEvents() def hide(): splash.deleteLater() app.appStarted.disconnect(hide) app.appStarted.connect(hide)
def main(): signal(SIGINT, SIG_DFL) app = QApplication(sys.argv) sys.excepthook = excepthook splash_pix = QPixmap(path.join(path.dirname(__file__), 'loading.png')) splash = QSplashScreen(splash_pix) splash.show() splash.raise_() app.processEvents() with open(path.join(path.dirname(__file__), "style.qss"), 'r') as f: app.setStyleSheet(f.read()) win = MainWindow() from argparse import ArgumentParser parser = ArgumentParser(description='Microchip Peripheral I/O Control') parser.add_argument('--fullscreen', dest='fullscreen', action='store_true', help='show the main window in fullscreen') parser.set_defaults(fullscreen=False) # ignore unknown arguments, necessary for ignoring only -smallresolution args, unknown = parser.parse_known_args() if args.fullscreen: win.setFixedSize(QApplication.desktop().size()) win.showFullScreen() else: win.show() win.setFocus() splash.finish(win) sys.exit(app.exec_())
def main(): QtWidgets.QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) # enable highdpi scaling Qt.HighDpiScaleFactorRoundingPolicy.Round scaleFactor = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100 if scaleFactor >= 1.5: os.environ["QT_SCREEN_SCALE_FACTORS"] = "1.5" else: os.environ[ "QT_SCREEN_SCALE_FACTORS"] = "scaleFactor" # das ist der richtige Skalierungsfaktor #os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "-1" #QT_SCREEN_SCALE_FACTORS #os.environ["QT_SCALE_FACTOR"] = "1.4" #os.environ["QT_DEVICE_PIXEL_RATIO"] = "0.5" app = QApplication(sys.argv) pixmap = QPixmap(os.path.dirname(sys.argv[0]) + "/pics/splesh.JPG") splash = QSplashScreen(pixmap) splash.show() splash.showMessage("Module werden geladen...") app.processEvents() app.setStyle("Fusion") time.sleep(3) window11 = myTab5.myTab5() #window11.setFixedSize(1100, 600) #window11.resize(window11.minimumSizeHint()) splash.finish(window11) showForUpdates(version, "https://digital-ies.de/wp-content/uploads", app, window11) app.exec_()
class MainWindow(QMainWindow): def __init__(self, settings, parent=None, **kwargs): QMainWindow.__init__(self, parent) self._splash = QSplashScreen(self, QPixmap('data/logo.tif')) self._splash.show() self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle("Iris Snooper GUI - %s" % kwargs['handle']['label']) self.setMinimumSize(800, 600) self._settings = settings #load previous settings print("Loading %s" % self._settings.fileName()) if self._settings.contains("MainWindow/geometry"): self.restoreGeometry(self._settings.value("MainWindow/geometry")) if self._settings.contains("MainWindow/state"): self.restoreState(self._settings.value("MainWindow/state")) #start the window self._plotters = PlotterWidgets(parent=self, **kwargs) self.setCentralWidget(self._plotters) #load complete self._splash.finish(self) def closeEvent(self, event): #stash settings self._settings.setValue("MainWindow/geometry", self.saveGeometry()) self._settings.setValue("MainWindow/state", self.saveState()) self._plotters.closeEvent(event)
def main(): app = QApplication(sys.argv) app.setStyle('cleanlooks') app.setApplicationName("Linguistica") # Get screen resolution # Why do we need to know screen resolution? # Because this information is useful for setting the size of particular # widgets, e.g., the webview for visualizing the word neighbor manifold # (the bigger the webview size, the better it is for visualization!) resolution = app.desktop().screenGeometry() screen_width = resolution.width() screen_height = resolution.height() # create and display splash screen splash_image_path = os.path.join(os.path.dirname(__file__), 'lxa_splash_screen.png') splash_image = QPixmap(splash_image_path) splash_screen = QSplashScreen(splash_image, Qt.WindowStaysOnTopHint) splash_screen.setMask(splash_image.mask()) splash_screen.show() app.processEvents() time.sleep(2) # launch graphical user interface form = MainWindow(screen_height, screen_width, __version__) form.show() splash_screen.finish(form) app.exec_()
def run(): app = QApplication(sys.argv) qtmodern.styles.dark(app) app.setWindowIcon(QIcon("resources/icon.ico")) if platform.system() == "Windows": ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( "quikplan") # App ID for taskbar icon splash = QSplashScreen( QPixmap("resources/quikplan.png").scaledToHeight( 400, QtCore.Qt.TransformationMode.SmoothTransformation)) splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) splash.show() main = Window() def showWindow(): splash.close() main.show() QtCore.QTimer.singleShot(1000, showWindow) sys.exit(app.exec_())
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. """ # The app object is the application running on your computer. app = QApplication(sys.argv) # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('icon')) splash.show() # Create the "window" we'll be looking at. editor_window = Window() # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.theme) editor.restore_session() # Connect the various buttons in the window to the editor. button_bar = editor_window.button_bar button_bar.connect("new", editor.new, "Ctrl+N") button_bar.connect("load", editor.load, "Ctrl+O") button_bar.connect("save", editor.save, "Ctrl+S") button_bar.connect("flash", editor.flash) button_bar.connect("repl", editor.toggle_repl) button_bar.connect("zoom-in", editor.zoom_in) button_bar.connect("zoom-out", editor.zoom_out) button_bar.connect("theme", editor.toggle_theme) button_bar.connect("quit", editor.quit) # Finished starting up the application, so hide the splash icon. splash.finish(editor_window) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def main(test_func): from pyminer2 import pmutil app = QApplication(sys.argv) path_logo = os.path.join(pmutil.get_root_dir(), r'ui\source\icons\logo.png') app.setWindowIcon(QIcon(path_logo)) # 设置应用logo path_splash = os.path.join(pmutil.get_root_dir(), r'ui\source\images\splash.png') splash = QSplashScreen(QPixmap(path_splash)) splash.showMessage("正在加载pyminer... 0%", Qt.AlignHCenter | Qt.AlignBottom, Qt.black) splash.show() # 显示启动界面 pmutil._application = app load_fonts(app) load_translator(app) # font = os.path.join(os.path.dirname(__file__), 'ui', 'source', 'font', 'SourceCodePro-Regular.ttf') app.default_font = 'Deng' f = QFont(app.default_font, 10) app.setFont(f) demo = MainWindow() demo.events_ready_signal.connect(test_func) splash.finish(demo) # 修复故障 I1VYVO 程序启动完成后,关闭启动界面 liugang 20200921 id(demo) sys.exit(app.exec_())
def main(): # define command line parameters parser = ArgumentParser() parser.add_argument("--no-splash", dest="splash", action="store_false") args = parser.parse_args() app = QApplication(sys.argv) # create splash screen with sponsors # default splash=True, use "-s" or "--splash" to set splash=False window = MainWindow() if args.splash: pixmap = QPixmap(os.path.join("resources","splash", "splash.jpg")) splash = QSplashScreen(pixmap) splash.showMessage(" Version: " + __version__, Qt.AlignBottom) # show the splash screen for 3 seconds splash.show() app.processEvents() QThread.sleep(3) window.show() splash.finish(window) else: window.show() sys.exit(app.exec())
def show_splash(version=''): splash_fname = utils.get_resource_path('icons/splash.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.35 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) numbers = {} for number in list(range(10)) + ['point']: fname = utils.get_resource_path('icons/{}.png'.format(number)) pix = QPixmap(fname) size = pix.size() * .65 numbers[str(number)] = pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) numbers['.'] = numbers['point'] painter = QPainter(splash_pix) painter.begin(splash_pix) x, y = 470, 70 for digit in version: painter.drawPixmap(x, y, numbers[digit]) x += numbers[digit].rect().width()/3 painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnBottomHint) splash.show() return splash
def splash(self): pixmap = QPixmap(".\\gui\\pyspec_less_ugly_shorter.png") smallerPixmap = pixmap.scaled(256, 256, Qt.KeepAspectRatio, Qt.SmoothTransformation) splash = QSplashScreen(smallerPixmap, Qt.WindowStaysOnTopHint) splash.setMask(smallerPixmap.mask()) splash.setWindowFlag(Qt.WindowStaysOnTopHint) splash.show() self.processEvents() self.init_logging() self.processEvents() log.info("Initialization of views, models, controllers...") time.sleep(2) self.processEvents() self.mainModel = MainModel() self.mainCtrl = MainController() self.mainWindow = MainWindow(self.mainModel, self.mainCtrl) self.mainWindow.setWindowTitle("PySpec Software") self.mainWindow.setAttribute(Qt.WA_AlwaysStackOnTop) self.processEvents() log.info("Initialization completed.") self.processEvents() self.mainWindow.show() log.info("This is the MAIN THREAD")
def init(): """ Init gui. Concat all files from style directory and apply stylesheet. Run `bootstrap_function` to prepare app. """ app = QApplication(sys.argv) app.setWindowIcon(QIcon('splash.png')) splash_img = QPixmap('splash.png') splash = QSplashScreen(splash_img) splash.show() app.processEvents() # items = bootstrap_function() items = '' style = [] style_dir = 'style' for f in os.listdir(style_dir): if not f.endswith('.qss'): continue with open(os.path.join(style_dir, f), 'r') as qss: style.append(qss.read()) app.setStyleSheet('\n'.join(style)) mw = MainWindow(items) splash.finish(mw) sys.excepthook = mw.excepthook sys.exit(app.exec_())
class GtoSplasher: def __init__(self, info): try: self.info = info self.splasher = None self.info.iface.mainWindow().showMinimized() qgisAppDataPath = QStandardPaths.standardLocations( QStandardPaths.AppDataLocation)[0] file = os.path.join(qgisAppDataPath, "splash.png") if not os.path.isfile(file): file = os.path.join(os.path.dirname(__file__), "splash.png") if os.path.isfile(file): pixmap = QPixmap(file) self.splasher = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) self.splasher.setPixmap(pixmap) self.splasher.show() except Exception as e: self.info.err(e) def log(self, msg): try: if self.splasher is not None: self.splasher.show() self.splasher.showMessage(msg, Qt.AlignCenter | Qt.AlignBottom) QApplication.instance().processEvents() self.info.log('Splasher:', msg) except Exception as e: self.info.err(e) def close(self): if self.splasher is not None: self.splasher.close()
def launch_main(xml_fname=None, introspect_fname=None): app = QApplication(sys.argv) import time start = time.time() splash_fname = utils.get_resource_path('icons/splash.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.35 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) # # below makes the pixmap half transparent painter = QPainter(splash_pix) painter.setCompositionMode(painter.CompositionMode_DestinationAtop) painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.show() app.processEvents() time.sleep(2) app.processEvents() mdwiz = PyMdWizardMainForm() mdwiz.show() splash.finish(mdwiz) if xml_fname is not None and os.path.exists(xml_fname): mdwiz.open_file(xml_fname) if introspect_fname is not None and os.path.exists(introspect_fname): mdwiz.metadata_root.eainfo.detaileds[0].populate_from_fname(introspect_fname) mdwiz.metadata_root.eainfo.ui.fgdc_eainfo.setCurrentIndex(1) app.exec_()
def run(): app = QApplication(sys.argv) app.setWindowIcon(QIcon(':/icons/windows/deeplisten-logo.png')) # splash screen # Create and display the splash screen splash_pix = QPixmap(':/icons/windows/start.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Simulate something that takes time time.sleep(1) mw = MainWindow() mw.show() splash.finish(mw) ##setup stylesheet # import qdarkstyle # app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) sys.exit(app.exec_())
def demo_run(): app = QApplication(sys.argv) # get screen size. desktop = QApplication.desktop().screenGeometry() ratio = QApplication.desktop().screen().devicePixelRatio() width = desktop.width() height = desktop.height() # setting up welcome screen. screen = QPixmap(icon["SCREEN"]) screen.setDevicePixelRatio(ratio) if ratio == 2: # under Mac Retina screen = screen.scaled(height * 0.9, height * 0.9) else: # under Windows and Linux screen = screen.scaled(height * 0.5, height * 0.5) splash = QSplashScreen(screen) splash.show() # handle the main process event. qApp.processEvents() # setting up main window. size = (width * 0.8, height * 0.8) editor = KMBMainWindow(size) stylesheet = load_stylesheet(SS_COMMON) app.setStyleSheet(stylesheet) # Mac: set the icon in dock. app.setWindowIcon(editor.win_icon) # compatible with Mac Retina screen. app.setAttribute(Qt.AA_UseHighDpiPixmaps, True) app.setAttribute(Qt.AA_EnableHighDpiScaling, True) # editor show up editor.show() splash.finish(editor) sys.exit(app.exec_())
def showSplashScreen(): splash_path = os.path.join(os.path.split(ilastik.__file__)[0], 'ilastik-splash.png') splashImage = QPixmap(splash_path) global splashScreen splashScreen = QSplashScreen(splashImage) splashScreen.showMessage( ilastik.__version__, Qt.AlignBottom | Qt.AlignRight ) splashScreen.show()
class SplashScreen: def __init__(self, parent, image=None, after=None): self.app = parent image = QPixmap(image) image = image.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.splash = QSplashScreen( image, Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) self.after = after def set_after(self, after): self.after = after def __enter__(self): self.splash.show() self.app.processEvents() return self def __exit__(self, exc_type, exc_value, traceback): self.after.show() self.splash.finish(self.after) def status_update(self, msg): self.splash.showMessage(msg, alignment=Qt.AlignHCenter, color=QColor(235, 239, 242)) self.app.processEvents()
class MainWindow(QMainWindow): def __init__(self, irises, settings, parent=None, chan=None, **kwargs): QMainWindow.__init__(self, parent) self._splash = QSplashScreen(self, QPixmap('data/logo.tif')) self._splash.show() self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle("CBRS Array Monitor") self.setMinimumSize(800, 600) self._settings = settings self.addDockWidget( Qt.TopDockWidgetArea, TopLevelControlPanel(irises=irises, settings=settings, parent=self)) #start the window self.setCentralWidget( MainStatusWindow(irises=irises, parent=self, chan=chan)) #load previous settings print("Loading %s" % self._settings.fileName()) if self._settings.contains("MainWindow/geometry"): self.restoreGeometry(self._settings.value("MainWindow/geometry")) if self._settings.contains("MainWindow/state"): self.restoreState(self._settings.value("MainWindow/state")) #load complete self._splash.finish(self) def closeEvent(self, event): #stash settings self._settings.setValue("MainWindow/geometry", self.saveGeometry()) self._settings.setValue("MainWindow/state", self.saveState())
def openDialog(self): # Only single instance of Plugin if self.exists == True: return else: self.exists = True self.resources = Resources(self.plugin_dir) self.dlg = PlanHeatDMMDialog(self) self.data = Data(plugin=False) splash = QSplashScreen( QtGui.QPixmap(self.plugin_dir + os.path.sep + 'resources/PlanHeatPrincipal.png'), QtCore.Qt.WindowStaysOnTopHint) splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) splash.setEnabled(False) splash.show() # Run the dialog event loop self.run() splash.finish(self.dlg) self.dlg.show() result = self.dlg.exec_() self.exists = False # See if OK was pressed if result: # Do something useful here pass else: pass
def run(self): """Run method that performs all the real work""" try: # locale.setlocale(locale.LC_ALL, 'en-GB') # Only single instance of Plugin if self.exists == True: return else: self.exists = True self.dlg = PlanHeatDMMDialog(self) self.resources = Resources(self.plugin_dir) self.data = Data(plugin=True) # Name of project self.data.projectName = master_mapping_config.CURRENT_PROJECT_NAME # Redirection dmm_folder = os.path.join(master_mapping_config.CURRENT_MAPPING_DIRECTORY, master_mapping_config.DMM_FOLDER) os.makedirs(dmm_folder, exist_ok=True) self.data.outputSaveFile = os.path.join(dmm_folder, master_mapping_config.DMM_PREFIX) splash = QSplashScreen(QtGui.QPixmap(self.plugin_dir + os.path.sep + 'resources/PlanHeatPrincipal.png'), QtCore.Qt.WindowStaysOnTopHint) splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) splash.setEnabled(False) splash.show() # Run the dialog event loop initWindowStatus(self) self.resources.loadAppResources() initWindowbehavior(self) # Deserialize the module DMMSerializer.deserialize(self) splash.finish(self.dlg) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() self.exists = False # See if OK was pressed if result: # Do something useful here - pass else: pass except Exception as e: self.exists = False print(str(e))
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. Specific tasks include: - set up logging - create an application object - create an editor window and status bar - display a splash screen while starting - close the splash screen after startup timer ends """ setup_logging() logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__)) logging.info(platform.uname()) logging.info('Python path: {}'.format(sys.path)) # The app object is the application running on your computer. app = QApplication(sys.argv) # By default PyQt uses the script name (run.py) app.setApplicationName('mu') # Set hint as to the .desktop files name app.setDesktopFileName('mu.codewith.editor') app.setApplicationVersion(__version__) app.setAttribute(Qt.AA_DontShowIconsInMenus) # Images (such as toolbar icons) aren't scaled nicely on retina/4k displays # unless this flag is set app.setAttribute(Qt.AA_UseHighDpiPixmaps) # Create the "window" we'll be looking at. editor_window = Window() # Make sure all windows have the Mu icon as a fallback app.setWindowIcon(load_icon(editor_window.icon)) # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) editor.setup(setup_modes(editor, editor_window)) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.debug_toggle_breakpoint, editor.theme) # Restore the previous session along with files passed by the os editor.restore_session(sys.argv[1:]) # Connect the various UI elements in the window to the editor. editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S') editor_window.connect_find_replace(editor.find_replace, 'Ctrl+F') editor_window.connect_find_replace(editor.toggle_comments, 'Ctrl+K') status_bar = editor_window.status_bar status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D') # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('splash-screen')) splash.show() # Hide the splash icon. splash_be_gone = QTimer() splash_be_gone.timeout.connect(lambda: splash.finish(editor_window)) splash_be_gone.setSingleShot(True) splash_be_gone.start(2000) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def main(args=None): # supply path to qgis install location QgsApplication.setPrefixPath("/usr", True) # create a reference to the QgsApplication # setting the second argument to True enables the IquaView GUI, # which we need to do since this is a custom application qgs = QgsApplication([], True) # init splash screen splash_pix = QPixmap(':/resources/iquaview.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) light_blue = QColor(165, 197, 192) dark_blue = QColor(11, 52, 70) # adding progress bar progress_bar = QProgressBar(splash) p = progress_bar.palette() p.setColor(QPalette.Highlight, light_blue) p.setColor(QPalette.HighlightedText, dark_blue) progress_bar.setPalette(p) progress_bar.setMaximum(10) progress_bar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) splash.show() splash.showMessage("Initializing interface...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # progress bar... for i in range(1, 11): progress_bar.setValue(i) t = time() if i == 5: splash.showMessage("Loading providers...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # load providers qgs.initQgis() LOGGER.info(qgs.showSettings()) if i == 10: # exec iquaview window window = MainWindow() window.setWindowIcon(QIcon(":/resources/iquaview_vector.svg")) splash.showMessage("IQUAview ready!", Qt.AlignBottom | Qt.AlignCenter, light_blue) while time() < t + 0.1: qgs.processEvents() window.showMaximized() splash.finish(window) qgs.exec_() window.deleteLater() # when app terminates, call exitQgis() to remove the provider and layer registries from memory qgs.exitQgis()
def launch(): frmmain = None log_path = os.path.join(USER_DATA_PATH, 'LOG.log') if os.path.isfile(log_path): file_size = os.stat(log_path).st_size if file_size > MAXIMUM_LOGFILE_SIZE: with open(log_path, 'rb') as f: file_contents = f.read() file_contents = file_contents[file_size - MAXIMUM_LOGFILE_SIZE:] with open(log_path, 'wb') as f: f.write(file_contents) elif os.path.isdir(log_path): print('Log file cannot be a directory.') sys.exit(1) tee = utils.Tee(log_path, 'a') print('Starting: ' + str(time.time())) try: sys.stdout = tee #os.environ['QTWEBENGINE_CHROMIUM_FLAGS'] = '--remote-debugging-port=4867 --reduced-referrer-granularity --disable-site-isolation-trials --disable-features=NetworkService,NetworkServiceInProcess' app = QApplication(sys.argv) splash = QSplashScreen(pix[BS_CHEER]) splash.show() app.processEvents() #app # Basic app theme here app.setStyle(QStyleFactory.create('Fusion')) app.setPalette(get_dark_palette()) # Initialize main window frmmain = Frm_Main(app, RELEASE_VER) Qt_common.check_win_icon('RAM.EnhOpt.Grave.1', app, frmmain, relative_path_covnert("favicon.ico")) #frmmain.load_file(common.DEFAULT_SETTINGS_PATH) frmmain.show() splash.finish(frmmain) app.setQuitOnLastWindowClosed(False) status_code = app.exec_() imgs.kill_pool() sys.exit(status_code) except Exception as e: exec_info = sys.exc_info()[0] if not exec_info is SystemExit: print("Traceback: ", exec_info) print(utils.getStackTrace()) print(e) except: exec_info = sys.exc_info()[0] if not exec_info is SystemExit: print("Unexpected error: ", exec_info) print(utils.getStackTrace()) finally: tee.flush() tee.file.close() if frmmain is not None: dlg_login = frmmain.dlg_login if dlg_login.connection_pool is not None: dlg_login.connection_pool.close()
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. Specific tasks include: - set up logging - create an application object - create an editor window and status bar - display a splash screen while starting - close the splash screen after startup timer ends """ setup_logging() logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__)) logging.info(platform.uname()) logging.info('Python path: {}'.format(sys.path)) # The app object is the application running on your computer. app = QApplication(sys.argv) app.setAttribute(Qt.AA_DontShowIconsInMenus) # Create the "window" we'll be looking at. editor_window = Window() # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) editor.setup(setup_modes(editor, editor_window)) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.debug_toggle_breakpoint, editor.theme) # Restore the previous session along with files passed by the os editor.restore_session(sys.argv[1:]) # Connect the various UI elements in the window to the editor. editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S') status_bar = editor_window.status_bar status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D') # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('splash-screen')) splash.show() # Finished starting up the application, so hide the splash icon. splash_be_gone = QTimer() splash_be_gone.timeout.connect(lambda: splash.finish(editor_window)) splash_be_gone.setSingleShot(True) splash_be_gone.start(5000) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def main(): # The app object is the application running on your computer. app = QApplication(sys.argv) app.setStyleSheet(load_stylesheet('mu.css')) # A splash screen is a logo that appears when you start up the application. # The image to be "splashed" on your screen is in the resources/images # directory. splash = QSplashScreen(load_pixmap('icon')) splash.show() # Make the editor with the Mu class defined above. the_editor = Mu() the_editor.show() the_editor.autosize_window() # Remove the splash when the_editor has finished setting itself up. splash.finish(the_editor) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. """ setup_logging() logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__)) logging.info(platform.uname()) logging.info('Python path: {}'.format(sys.path)) # The app object is the application running on your computer. app = QApplication(sys.argv) # Create the "window" we'll be looking at. editor_window = Window() # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) editor.setup(setup_modes(editor, editor_window)) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.debug_toggle_breakpoint, editor.theme) # capture the filename passed by the os, if there was one passed_filename = sys.argv[1] if len(sys.argv) > 1 else None editor.restore_session(passed_filename) # Connect the various UI elements in the window to the editor. editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S') status_bar = editor_window.status_bar status_bar.connect_logs(editor.show_logs, 'Ctrl+Shift+D') status_bar.connect_mode(editor.select_mode, 'Ctrl+Shift+M') # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('splash-screen')) splash.show() # Finished starting up the application, so hide the splash icon. splash_be_gone = QTimer() splash_be_gone.timeout.connect(lambda: splash.finish(editor_window)) splash_be_gone.setSingleShot(True) splash_be_gone.start(5000) # Stop the program after the application finishes executing. sys.exit(app.exec_())
from PyQt5.QtGui import QPixmap, QImage, QFont # from urllib.request import Request, urlopen # from urllib.error import URLError, HTTPError from vk_ui import Ui_MainWindow from vk_settings_ui import Ui_Form from add_ui import Ui_FormUrl from downloading_ui import Ui_FormDownload app = QApplication(sys.argv) image = QPixmap('./pic/111.jpg') splash = QSplashScreen(image) splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) splash.setMask(image.mask()) font = QFont(splash.font()) font.setPointSize(font.pointSize() + 5) splash.setFont(font) splash.show() app.processEvents() # time.sleep(2) # splash.showMessage(splash.tr('Processing %1...{0}'),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.white) # QtCore.QThread.msleep(1000) # QApplication.processEvents() for count in range(1, 6): # splash.showMessage(splash, str(count),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.blue) splash.showMessage('Loading: ' + str(count), QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft, QtCore.Qt.white) # print(str(count)) # app.processEvents() QtCore.QThread.msleep(1000)
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if sys.platform != 'win32': app.setCursorFlashTime(0) #Set the codec for strings (QString) print("codec:", QTextCodec.codecForName('utf-8')) #QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator #qsettings = QSettings() qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists(file_manager.create_path( resources.LANGS_DOWNLOAD, lang)): settings.LANGUAGE = file_manager.create_path( resources.LANGS_DOWNLOAD, lang) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA__THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE(start_server) #Showing GUI ide.show() #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab main_files = qsettings.value('openFiles/mainTab', []) if main_files is not None: mainFiles = list(main_files) else: mainFiles = list() tempFiles = [] for file_ in mainFiles: fileData = list(file_) if fileData: lineno = fileData[1] tempFiles.append((fileData[0], lineno)) mainFiles = tempFiles #Files in Secondary Tab sec_files = qsettings.value('openFiles/secondaryTab', []) if sec_files is not None: secondaryFiles = list(sec_files) else: secondaryFiles = list() tempFiles = [] for file_ in secondaryFiles: fileData = list(file_) lineno = fileData[1] tempFiles.append((fileData[0], lineno)) secondaryFiles = tempFiles # Recent Files recent = qsettings.value('openFiles/recentFiles', []) if recent is not None: recent_files = list(recent) else: recent_files = list() recent_files = [file_ for file_ in recent_files] #Current File current_file = qsettings.value('openFiles/currentFile', '', type='QString') #Projects projects_list = qsettings.value('openFiles/projects', []) if projects_list is not None: projects = list(projects_list) else: projects = list() projects = [project for project in projects] #Include files received from console args file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0) for f in filenames[len(linenos):]]) mainFiles += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects, current_file, recent_files) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() ide.show_python_detection() sys.exit(app.exec_())
class MainWindow(QMainWindow,Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.start_logo() self.setupUi(self) self.sysencoding =sys.stdout.encoding #self.centralWidget = PyPreviewer(self) #self.setCentralWidget(self.centralWidget) self.setupEditor() self.setWindowIcon(QIcon('PyPreviewer.ico')) #메뉴 이벤트 생성 self.createEvent() self.dirty = False self.plainTextEdit_2.textChanged.connect(self.setDirty) self.fileName = None self.plainTextEdit_2.setTabStopWidth(35) self.plainTextEdit_2.setPlainText("# -*- coding: utf-8 -*-\n# 반갑습니다~\n# #은 파이썬에서 주석입니다.\nprint(\"이 부분은 출력창입니다.\")\nprint(\"구구단 예제\")\nfor i in range(2,10):\n\tprint(i,\"단\")\n\tfor j in range(2,10):\n\t\tprint(i,\"X\", j, \"=\", i*j)\n# 파이썬 실행은 아래 실행버튼을 눌러주세요.\n# 파이썬 학습 관련 및 예제는 왼쪽 화면을 이용하시기 바랍니다.") #web view #self.exampleView.load(QUrl("http://www.google.com")) self.startfilepath=os.getcwd() +"/PyStudy_web/Main.html" self.exampleView.load(QUrl.fromLocalFile(self.startfilepath)) self.locationEdit = QLineEdit(self) self.locationEdit.setSizePolicy(QSizePolicy.Expanding, self.locationEdit.sizePolicy().verticalPolicy()) self.locationEdit.returnPressed.connect(self.changeLocation) toolBar = QToolBar() self.addToolBar(toolBar) self.insertToolBarBreak(toolBar) toolBar.addAction(self.exampleView.pageAction(QWebPage.Back)) toolBar.addAction(self.exampleView.pageAction(QWebPage.Forward)) toolBar.addAction(self.action_myHome) toolBar.addAction(self.exampleView.pageAction(QWebPage.Reload)) #toolBar.addAction(self.exampleView.pageAction(QWebPage.Stop)) toolBar.addWidget(self.locationEdit) #사용자 입력 파이썬 파일 실행 print ('Connecting process') self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.setInputChannelMode(QProcess.ManagedInputChannel) self.process.readyReadStandardOutput.connect(self.stdoutReady) self.process.readyReadStandardError.connect(self.stderrReady) self.process.started.connect(lambda: print('ExampleProgramStarted!')) self.process.finished.connect(lambda:print('ExampleProgramFinished!')) print('Starting process') #self.process.start('python', ['ExampleTest.py']) def start_logo(self): img_logo = QPixmap('pystudylogo.png') self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint) self.splash.setMask(img_logo.mask()) self.splash.show() time.sleep(1.8) self.splash.close() def show_logo(self): img_logo = QPixmap('pystudylogo.png') self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint) self.splash.setMask(img_logo.mask()) self.splash.show() self.splash.repaint() def createEvent(self): self.ProgramRunButton.clicked.connect(self.clickAction_ProgramRunButton) self.ProgramStopButton.clicked.connect(self.clickAction_ProgramStopButton) self.actionRun.triggered.connect(self.clickAction_ProgramRunButton) self.actionStop.triggered.connect(self.clickAction_ProgramStopButton) self.ClearButton.clicked.connect(self.clickAction_ProgramEraseButton) self.actionClear.triggered.connect(self.clickAction_ProgramEraseButton) self.actionNew_File.triggered.connect(self.clickAction_fileNew) self.actionFile_Open.triggered.connect(self.clickAction_fileOpen) self.actionFile_Save.triggered.connect(self.clickAction_fileSave) self.actionFile_Save_as.triggered.connect(self.clickAction_fileSaveAs) self.action_example.triggered.connect(self.clickAction_exampleOpen) self.actionPythonHelp.triggered.connect(self.clickAction_PythonHelp) self.actionHelp.triggered.connect(self.clickAction_ProgramHelp) self.MessagepushButton.clicked.connect(self.clickAction_MessagePushButton) self.actionStyleSheet_default.triggered.connect(self.clickAction_styleDefault) self.actionStyleSheet_Black.triggered.connect(self.clickAction_styleBlack) self.actionStyleSheet_Load.triggered.connect(self.clickAction_styleLoad) self.actionAbout_PyStudy.triggered.connect(self.show_logo) self.action_myHome.triggered.connect(self.go_myHome) self.action_exit.triggered.connect(self.close) def setDirty(self): #'On change of text in textEdit window, set the flag "dirty" to True'' if self.dirty: return True self.dirty = True self.updateStatus('소스 수정중...') def clearDirty(self): #'''Clear the dirty flag and update status''' self.dirty = False def updateStatus(self, message): if self.fileName is not None: flbase = os.path.basename(self.fileName) self.setWindowTitle("PyStudy Simple Editor - " + flbase + "[*]" ) self.statusBar().showMessage(message, 3000) self.setWindowModified(self.dirty) def clickAction_exampleOpen(self): fname, filter = QFileDialog.getOpenFileName(self, "예제파일 열기창", '.', "HTML File(*.html *.htm)") if not (fname == ""): #self.exampleView.load(QUrl(fname)) self.exampleView.setUrl(QUrl.fromLocalFile(fname)) #self.plainTextEdit_2.setPlainText(codecs.open(fname, "r", "utf-8" ).read()) #self.fileName = fname else: return self.updateStatus('example File opened.') def clickAction_exampleDirectOpen(self,fname): if not (fname == ""): fname = os.getcwd()+r"\\"+fname print(fname) self.exampleView.setUrl(QUrl.fromLocalFile(fname)) else: return self.updateStatus('example File opened.') def clickAction_fileNew(self): #'''Clear the editor window for a new file with name specified in fileSaveAs method.''' self.plainTextEdit_2.clear() self.statusBar().showMessage('새 소스파일 생성', 8000) self.dirty = False self.fileName = None def clickAction_fileOpen(self): fname, filter = QFileDialog.getOpenFileName(self, "소스파일 열기창", '.', "Python File(*.py)") if not (fname == ""): self.plainTextEdit_2.setPlainText(codecs.open(fname, "r", "utf-8" ).read()) self.fileName = fname else: return self.clearDirty() self.updateStatus('File opened.') def clickAction_fileSave(self): if self.fileName is None: return self.clickAction_fileSaveAs() else: fname = self.fileName fl = codecs.open(fname, "w", "utf-8" ) tempText = self.plainTextEdit_2.toPlainText() if tempText: fl.write(tempText) fl.close() self.clearDirty() self.updateStatus('Saved file') return True else: self.statusBar().showMessage('파일 저장 실패 ...', 5000) return False def clickAction_fileSaveAs(self): path = self.fileName if self.fileName is not None else "." fname,filter = QFileDialog.getSaveFileName(self, "다른이름으로 저장", path, "Python File(*.py)") if fname: if "." not in fname: fname += ".py" self.fileName = fname self.clickAction_fileSave() self.statusBar().showMessage('SaveAs file' + fname, 8000) self.clearDirty() def clickAction_ProgramRunButton(self): self.clickAction_fileSave() self.process.start('python', [self.fileName],QIODevice.ReadWrite) def clickAction_ProgramStopButton(self): self.process.kill() self.append_plainTextEdit_3("\n\n프로세스 정지 with exit code "+str(self.process.exitCode())+"\n\n") def clickAction_ProgramEraseButton(self): self.plainTextEdit_3.clear() def append_plainTextEdit_3(self, text): cursor = self.plainTextEdit_3.textCursor() cursor.movePosition(cursor.End) cursor.insertText(text) #self.output.ensureCursorVisible() def stdoutReady(self): if self.sysencoding == "cp949": text = str(self.process.readAllStandardOutput(), "cp949")#독립실행시 elif self.sysencoding == "UTF-8": text = str(self.process.readAllStandardOutput(), "utf-8")#pycharm else: text = str(self.process.readAllStandardOutput(), "cp949")#독립실행시 self.append_plainTextEdit_3(text) def stderrReady(self): if self.sysencoding == "cp949": text = str(self.process.readAllStandardError(), "cp949")#독립실행시 elif self.sysencoding == "UTF-8": text = str(self.process.readAllStandardError(), "utf-8")#pycharm else: text = str(self.process.readAllStandardError(), "cp949")#독립실행시 self.append_plainTextEdit_3(text) def clickAction_PythonHelp(self): temppath=os.path.abspath('..')+r"\파이썬도움말\animation.py" tempoption = os.path.abspath('..')+r"\파이썬도움말" pythonhelp_process=QProcess() pythonhelp_process.start('python', [temppath,tempoption]) pythonhelp_process.started() # TypeError: native Qt signal is not callable def clickAction_MessagePushButton(self): temp = self.messagelineEdit.text() self.append_plainTextEdit_3(temp) self.append_plainTextEdit_3("\n") bArray = QByteArray() if self.sysencoding == "cp949": bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시 elif self.sysencoding == "UTF-8": bArray.append(temp.encode(encoding='utf-8',errors='ignore'))#pycharm else: bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시 bArray.append("\n") if( self.process.write(bArray) == -1): print("chlidprocess write error") self.messagelineEdit.clear() def clickAction_styleLoad(self): fname, filter = QFileDialog.getOpenFileName(self, "QT스타일시트파일 불러오기", '.', "Qt-StyleSheet(*.qss)") if fname: file = QFile(fname) file.open(QFile.ReadOnly) styleSheet = file.readAll() styleSheet = str(styleSheet, encoding='utf8') # Python v3. self.setStyleSheet(styleSheet) print ("test") def clickAction_styleDefault(self): self.set_StyleSheet("default") def clickAction_styleBlack(self): self.set_StyleSheet("black") def clickAction_ProgramHelp(self): self.startfilepath=os.getcwd() +"/PyStudy_web/Pystudy.html" self.exampleView.load(QUrl.fromLocalFile(self.startfilepath)) def set_StyleSheet(self, sheetName): if sheetName: file = QFile('stylesheet/%s.qss' % sheetName.lower()) file.open(QFile.ReadOnly) styleSheet = file.readAll() styleSheet = str(styleSheet, encoding='utf8') # Python v3. self.setStyleSheet(styleSheet) def setupEditor(self): font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.editor = self.plainTextEdit_2 self.editor.setFont(font) self.highlighter = Highlighter(self.editor.document()) def changeLocation(self): url = QUrl.fromUserInput(self.locationEdit.text()) self.exampleView.load(url) self.exampleView.setFocus() def go_myHome(self): self.exampleView.load(QUrl.fromLocalFile(self.startfilepath)) self.exampleView.setFocus()
class tempapp(QMainWindow, tempwin): def __init__(self,parent=None): #splash screen initialisation self.splash_pix = QPixmap('data/loading.jpg') self.splash = QSplashScreen(self.splash_pix, QtCore.Qt.WindowStaysOnTopHint) self.splash.setMask(self.splash_pix.mask()) self.splash.show() super(tempapp, self).__init__(parent) self.setupUi(self) def main(self): #launching program self.hide() self.launch() def launch(self): #reading configuration config=open('data/configure') config=config.readlines() envir=main.principal self.result={} for info in range(len(config)) : temp=config[info].split('=') temp[1]=temp[1].split('\n')[0] self.result[temp[0]]=temp[1] if self.result['db']=='' : #if no databatse, asking user for creating/pointing h=QMessageBox(parent=self, text="No DB has been pointed. \nDo you want to create a new database or to load an existing database ?") h.addButton(QPushButton('Close'), QMessageBox.YesRole) h.addButton(QPushButton('Load an Existing DB'), QMessageBox.NoRole) h.addButton(QPushButton('New DB'), QMessageBox.HelpRole) self.splash.hide() tot = h.exec_() if tot==0 : self.terminer() if tot==1 : self.loaddb() if tot==2 : self.newdb() else : #if already configured : checking if the DB still exist if os.path.exists(self.result['db'])==True : None else : #if db do not exist : delete configuration and reboot program self.splash.hide() h=QMessageBox(parent=self, text="Corrupted file or non existent : Deleting configuration") self.result['db']="" new_conf='' for i in self.result : new_conf+='%s=%s\n' % (i,self.result[i]) config=open('data/configure','w') config.write(new_conf) config.close() h.exec_() python = sys.executable os.execl(python, python, * sys.argv) #launching program if all checkpoints are ok self.splash.hide() prog=main.principal() prog.main() sys.exit(app.exec_()) def loaddb (self) : #loading db file fname=QFileDialog.getOpenFileName(self, 'Choose a DB', '/','SQLite Databse (*.sqlite)')[0] if fname=='' : z=QMessageBox(parent=self, text="No DB has been selected, closing program") z.exec_() z.exec_() self.terminer() isvalid=cursor.verif(str(fname)) #checking is the DB is valid if isvalid==False : z=QMessageBox(parent=self, text="Wrong File/File Corruption. \nClosing programm") z.exec_() self.terminer() else : #writiing new configuration self.result['db']=str(fname) new_conf='' for i in self.result : new_conf+='%s=%s\n' % (i,self.result[i]) config=open('data/configure','w') config.write(new_conf) config.close() python = sys.executable os.execl(python, python, * sys.argv) def terminer (self) : #QApplication.quit() #sys.exit(app.exec_()) sys.exit(0) def newdb (self) : #new db creation fname=QFileDialog.getSaveFileName(self, 'Create a DB', '/','SQLite Databse (*.sqlite)')[0] shutil.copy('data/model.sqlite',fname) self.result['db']=str(fname) new_conf='' for i in self.result : new_conf+='%s=%s\n' % (i,self.result[i]) config=open('data/configure','w') config.write(new_conf) config.close() python = sys.executable os.execl(python, python, * sys.argv)
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. Specific tasks include: - set up logging - create an application object - create an editor window and status bar - display a splash screen while starting - close the splash screen after startup timer ends """ setup_logging() logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__)) logging.info(platform.uname()) logging.info('Python path: {}'.format(sys.path)) logging.info('Language code: {}'.format(language_code)) # The app object is the application running on your computer. app = QApplication(sys.argv) # By default PyQt uses the script name (run.py) app.setApplicationName('mu') # Set hint as to the .desktop files name app.setDesktopFileName('mu.codewith.editor') app.setApplicationVersion(__version__) app.setAttribute(Qt.AA_DontShowIconsInMenus) # Images (such as toolbar icons) aren't scaled nicely on retina/4k displays # unless this flag is set app.setAttribute(Qt.AA_UseHighDpiPixmaps) # Create the "window" we'll be looking at. editor_window = Window() @editor_window.load_theme.connect def load_theme(theme): if theme == 'contrast': app.setStyleSheet(CONTRAST_STYLE) elif theme == 'night': app.setStyleSheet(NIGHT_STYLE) else: app.setStyleSheet(DAY_STYLE) # Make sure all windows have the Mu icon as a fallback app.setWindowIcon(load_icon(editor_window.icon)) # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) editor.setup(setup_modes(editor, editor_window)) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.debug_toggle_breakpoint, editor.theme) # Restore the previous session along with files passed by the os editor.restore_session(sys.argv[1:]) # Connect the various UI elements in the window to the editor. editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S') editor_window.connect_find_replace(editor.find_replace, 'Ctrl+F') editor_window.connect_toggle_comments(editor.toggle_comments, 'Ctrl+K') status_bar = editor_window.status_bar status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D') # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('splash-screen')) splash.show() # Hide the splash icon. splash_be_gone = QTimer() splash_be_gone.timeout.connect(lambda: splash.finish(editor_window)) splash_be_gone.setSingleShot(True) splash_be_gone.start(2000) # Stop the program after the application finishes executing. sys.exit(app.exec_())
class Example(QMainWindow, Ui_MainWindow): DEBUG = True # Если TRUE, то выводим вспомогательную информацию в консоль result = {} # Variable for JSON photo_avg = [] # Сюда помещаются картинки приблизительно равные размеру, заданному в переменной photo_size photo_date = [] # Сюда помещаются даты, когда были выложены картинки photo_max = [] # Сюда помещаются самые большие картинки current_page = 1 # Текущая страница просмоторщика label = {} # Массив элементов label loading_image = [] # Сюда помещаем список загруженных фото button = {} # Массив кнопок icon = {} # Массив иконок для button pic_date = {} # Массив времени публикации для картинок prev_mode = 0 # Флаг где находимся. 0 - если в превиюхах. 1 - если в режима просмотра большой картинки group_id = 0 # ID группы, которую будем загружать dict_count = {} # Переменная через которую сопоставляется выделенный элемент в listWidget и ID для загрузки first_run = 0 # Если приложение запустилось первый раз, то при нажатии Load загрузить аватарки групп loading_error = False # Флаг удачной загрузки def __init__(self, MainWindow): super().__init__() # Сконфигурировать интерфейс методом из базового класса MainWindow self.setupUi(MainWindow) # Показываем заставку при загрузке self.downloading('Interface is initialized...') self.wait() # Подключить созданные нами слоты к виджетам self.connect_slots() try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() # Количество загружаемых страниц self.num_pages = self.settings['settings']['pages_load'][0]['num_pages'] # Количество строк self.num_line = self.settings['settings']['preview'][0]['num_line'] # Количество столбцов self.num_column = self.settings['settings']['preview'][0]['num_column'] # Размер preview self.photo_size = self.settings['settings']['preview'][0]['prev_size'] # Путь (каталог на диске) для сохранения изображений self.pic_save_path = self.settings['settings']['pic_save'][0]['path'] # Прокси self.proxy_host = self.settings['settings']['proxies'][0]['host'] self.proxy_port = self.settings['settings']['proxies'][0]['port'] self.proxy_username = self.settings['settings']['proxies'][0]['username'] self.proxy_password = self.settings['settings']['proxies'][0]['password'] if not self.proxy_host: self.proxies = {} self.auth = HTTPProxyAuth('', '') if self.proxy_host and self.proxy_port: self.proxies = {"http": "http://" + self.proxy_host + ":" + self.proxy_port, "https": "https://" + self.proxy_host + ":" + self.proxy_port} self.auth = HTTPProxyAuth('', '') if self.proxy_host and self.proxy_port and self.proxy_username and self.proxy_password: self.proxies = {"http": "http://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port, "https": "https://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port,} self.auth = HTTPProxyAuth(self.proxy_username, self.proxy_password) if self.DEBUG: print('Proxy: ' + str(self.proxies)) # Заполняем listVidget группами без аватарки self.group_fill() except IOError: self.statusbar.showMessage('settings.json not found!') self.num_pages = 2 self.num_line = 2 self.num_column = 2 self.photo_size = 50 # self.modalWindowDownloading.close() self.splash.close() # Подключаем слоты к виджетам def connect_slots(self): self.actionLoad.triggered.connect(self.load_pic) self.actionNext.triggered.connect(self.next_pic) self.actionPreview.triggered.connect(self.preview_pic) self.actionRefresh.triggered.connect(self.refresh) self.actionSettings.triggered.connect(self.settings_window) self.actionQuit.triggered.connect(qApp.quit) self.actionAbout.triggered.connect(self.about_vk) self.actionAbout_Qt.triggered.connect(self.about_qt) self.actionHelp.triggered.connect(self.help) self.actionOpen_saving_folder.triggered.connect(self.open_saving_folder) QMainWindow.resizeEvent = self.scale_pic # Заполняем listWidget списком групп def group_fill(self): self.listWidgetMain.clear() # Очищаем listWidgetMain try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() except IOError: self.statusbar.showMessage('settings.json not found!') # Заполняем listWidget списком групп self.dict = self.settings['vk_groups'] # print('DICT: ' + str(self.dict)) n = 0 self.dict_count = {} # Обнуляем for i in self.dict: self.listWidgetMain.addItem(self.dict[i]) self.dict_count[n] = str(i) n += 1 # Заполняем listWidget аватарками def group_fill_ava(self): self.listWidgetMain.clear() # Очищаем listWidgetMain # Формируем список групп для которых нужно загрузить аватарку и выполняем запрос text = '' for i in range(len(self.dict_count)): text = text + str(self.dict_count[i]) if i < len(self.dict_count) - 1: text = text + ',' # Загружаем, парсим JSON и вытаскиваем аватарки групп url_ava = 'https://api.vk.com/method/groups.getById?v=5.32&group_ids=' + text if self.DEBUG: print('Get JSON Avatars URL: ' + url_ava) self.splash.showMessage('Downloading Avatars', QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) try: response = requests.get(url_ava, proxies=self.proxies, auth=self.auth) except IOError: if self.DEBUG: print('ERROR Loading avatars!') self.group_fill() self.loading_error = True self.splash.close() if self.loading_error == False: result = json.loads(response.text) # Заполняем listWidget аватарками групп loading_ava = [] for i in range(len(self.dict_count)): if self.DEBUG: print(str(i) + ')' + result['response'][i]['photo_50']) self.splash.showMessage(os.path.basename(result['response'][i]['photo_50']), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) response = requests.get(result['response'][i]['photo_50'], proxies=self.proxies, auth=self.auth) image = QImage() image.loadFromData(response.content) loading_ava.append(image) item = QtWidgets.QListWidgetItem() icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(image), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(icon) self.listWidgetMain.addItem(item) # Заполняем listWidget названиями групп n = 0 for i in self.dict: item = self.listWidgetMain.item(n) item.setText(self.dict[i]) # item.setText(str(i) + ':' + self.dict[i]) # self.listWidgetMain.addItem(str(i) + ':' + self.dict[i]) n += 1 # Открываем каталок загрузок в текущем проводнике def open_saving_folder(self): if platform.system() == 'Linux': try: subprocess.check_call(['xdg-open', self.pic_save_path]) except subprocess.CalledProcessError: QMessageBox.critical(window, 'Error','Unable to open dir\n"File->Settings->Path"') # Помощь def help(self): print(self.dict_count) # # self.group_id = self.dict_count[self.listWidgetMain.currentRow()] # print(self.group_id) # # self.downloading() # Увеличение картинки при растяжении окна def scale_pic(self, e): if self.prev_mode == 1: self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Указываем путь для сохранения картинок def tool_button(self, e): print('tool button') fname = QFileDialog.getExistingDirectory(self, 'Dir', self.pic_save_path) if fname: self.lineEdit.setText(fname) # Обновить картинку def refresh(self): print('refresh') # self.load_big() self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled(self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # self.label.mousePressEvent = self.close_full_pic_view self.actionRefresh.setEnabled(True) def about_vk(self): QMessageBox.about(window, 'About VK Girls', 'VK Girls v.1.0') def about_qt(self): QMessageBox.aboutQt(window) # Загружаем картинки при нажатии кнопки Load def load_pic(self): # Проверяем есть ли и-нет соединение try: requests.get('http://vk.com', proxies=self.proxies, auth=self.auth) except IOError: if self.DEBUG: print('Check internet connection') msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'Check internet connection', QMessageBox.NoButton) msgBox.exec_() else: print('Поехали') self.current_page = 1 self.load_pic_list() self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.loading_error = False # Загружаем следующую картинку при нажатии кнопки Next def next_pic(self): # Если находимся в режиме preview, то загружаем следующие if self.prev_mode == 0: # Показываем заставку при загрузке self.downloading('Loading next pics...') self.wait() self.current_page += 1 self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.splash.close() # Если находимся в режима просмотра большой картинки, то показываем следующую else: print('--->') if self.photo_max_id < len(self.photo_max) - 1: self.photo_max_id += 1 self.load_big() self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1: self.actionNext.setEnabled(False) else: self.actionNext.setEnabled(True) # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной if self.photo_max_id <= 0 and self.prev_mode == 1: self.actionPreview.setEnabled(False) else: self.actionPreview.setEnabled(True) # Загружаем предыдущую картинку при нажатии кнопки Preview def preview_pic(self): if self.prev_mode == 0: # Показываем заставку при загрузке self.downloading('Loading prev pics...') self.wait() self.current_page -= 1 self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.splash.close() else: print('<---') if self.photo_max_id > 0: self.photo_max_id -= 1 self.load_big() self.big_check() # Сравниваем его размер с размером окна self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1: self.actionNext.setEnabled(False) else: self.actionNext.setEnabled(True) # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной if self.photo_max_id <= 0 and self.prev_mode == 1: self.actionPreview.setEnabled(False) else: self.actionPreview.setEnabled(True) # Просмотр большого фото def full_pic_view(self, event): # Показываем заставку при загрузке self.downloading('Loading full image...') self.wait() """Загрузка и просмотр большого изображения""" self.prev_mode = 1 # Выставляем флаг, что мы перешли в режим просмотра большого фото self.wat_is_button() # Какая кнопка с preview была нажата, чтобы загрузить большое фото self.clear_screen() # Удаляем все кнопки с изображениями (очищаем окно) self.check_buttons() # Проверяем флаги кнопок в меню и тулбаре # self.win_size() # Определяем текущий размер окна # Ищем большое фото mult_num = self.num_line * self.num_column self.photo_max_id = self.current_page *\ mult_num - mult_num + self.sender1 # Создаем Label в котором будем выводить фото self.label = QtWidgets.QLabel(self.centralwidget) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.load_big() # Загружаем большое фото self.big_check() # Сравниваем его размер с размером окна self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) self.gridLayout_2.addWidget(self.label, 0, 0, 0, 0) self.label.mousePressEvent = self.close_full_pic_view # Если фото последнее, то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1: self.actionNext.setEnabled(False) # Если фото первое, то делаем кнопку preview неактивной if self.photo_max_id == 0: self.actionPreview.setEnabled(False) # Закрываем заставку self.splash.close() # Загрузка большого фото def load_big(self): """Загружаем большое фото""" # req = Request(self.photo_max[self.photo_max_id]) # response = urlopen(req).read() # # Показываем заставку при загрузке # self.downloading() # self.wait() response = requests.get(self.photo_max[self.photo_max_id], proxies=self.proxies, auth=self.auth) self.image = QImage() self.image.loadFromData(response.content) # self.modalWindowDownloading.close() # Подгоняем размер картинки под размер окна def big_check(self): # Определяем размер окна, чтобы оно не растягивалось, если размер изображения больше, чем размер окна self.win_size() # Сверяем размер большого фото с размером окна if self.image.width() < self.width: self.width_my = self.image.width() self.height_my = self.image.height() else: if self.DEBUG: print('BIG_width') self.width_my = self.width - self.width * 0.1 self.height_my = self.height - self.height * 0.1 if self.height_my < self.height: if self.DEBUG: print('do nothing') else: if self.DEBUG: print('BIG_height') self.width_my = self.width - self.width * 0.1 self.height_my = self.height - self.height * 0.1 if self.DEBUG: print('Ширина:{0}; Высота:{1}'.format(self.width_my, self.height_my)) # ##############Окно настроек ###################################################### def settings_window(self): """Окно настройки""" combo = { 50: 0, 100: 1, 130: 2, 160: 3, 200: 4, 250: 5 } self.modalWindow = QWidget(window, Qt.Window) self.modalWindow.setWindowModality(Qt.WindowModal) # SettingsWindow(modalWindow) Ui_Form.setupUi(self, self.modalWindow) Ui_Form.retranslateUi(self, self.modalWindow) self.pushButtonOK.mousePressEvent = self.button_ok self.pushButtonCancel.mousePressEvent = self.button_cancel self.toolButton.mousePressEvent = self.tool_button self.pushButtonAdd.mousePressEvent = self.button_add self.pushButtonDel.mousePressEvent = self.button_del self.checkBox.stateChanged.connect(self.check_box) self.radioButtonYes.toggled.connect(self.radio_button) self.modalWindow.setAttribute(Qt.WA_DeleteOnClose, True) # modalWindow.move(window.geometry().center() - modalWindow.rect().center() - QtCore.QPoint(4, 30)) try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() # Размер preview self.photo_size = self.settings['settings']['preview'][0]['prev_size'] self.comboBox.setCurrentIndex(combo[self.photo_size]) # Количество загружаемых страниц self.num_pages = self.settings['settings']['pages_load'][0]['num_pages'] self.spinPages.setProperty("value", self.num_pages) # Количество строк self.num_line = self.settings['settings']['preview'][0]['num_line'] self.spinRow.setProperty("value", self.num_line) # Количество столбцов self.num_column = self.settings['settings']['preview'][0]['num_column'] self.spinColumns.setProperty("value", self.num_column) # Путь (каталог на диске) для сохранения изображений self.pic_save_path = self.settings['settings']['pic_save'][0]['path'] self.lineEdit.setText(self.pic_save_path) # Заполняем listWidget списком групп dict = self.settings['vk_groups'] for i in dict: self.listWidget.addItem(str(i) + ':' + dict[i]) # Заполняем прокси, если есть self.proxy_host = self.settings['settings']['proxies'][0]['host'] self.proxy_port = self.settings['settings']['proxies'][0]['port'] self.proxy_username = self.settings['settings']['proxies'][0]['username'] self.proxy_password = self.settings['settings']['proxies'][0]['password'] if self.proxy_host and self.proxy_port: self.radioButtonYes.setChecked(True) self.lineEditProxy.setText(self.proxy_host) self.spinBoxPort.setProperty("value", self.proxy_port) if self.proxy_username and self.proxy_password: self.checkBox.setChecked(True) self.lineEditLogin.setText(self.proxy_username) self.lineEditPwd.setText(self.proxy_password) else: self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) else: self.radioButtonNo.setChecked(True) self.lineEditProxy.setDisabled(True) self.spinBoxPort.setDisabled(True) self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) self.checkBox.setDisabled(True) except IOError: self.num_pages = 2 self.num_line = 2 self.num_column = 2 self.photo_size = 50 self.modalWindow.show() def radio_button(self): if self.radioButtonYes.isChecked(): self.lineEditProxy.setDisabled(False) self.spinBoxPort.setDisabled(False) self.checkBox.setDisabled(False) else: self.lineEditProxy.setDisabled(True) self.spinBoxPort.setDisabled(True) self.checkBox.setDisabled(True) self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) self.checkBox.setChecked(False) def check_box(self): if self.checkBox.isChecked(): self.lineEditLogin.setDisabled(False) self.lineEditPwd.setDisabled(False) else: self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) # Кнопка добавления группы в список listWidget def button_add(self, e): print('button add') self.modalWindowAdd = QWidget(window, Qt.Window) self.modalWindowAdd.setWindowModality(Qt.WindowModal) Ui_FormUrl.setupUi(self, self.modalWindowAdd) Ui_FormUrl.retranslateUi(self, self.modalWindowAdd) self.pushButtonUrl.mousePressEvent = self.buttonUrl self.modalWindowAdd.show() # Кнопка удаления группы из списка listWidget def button_del(self, e): print(self.settings['vk_groups']) # Берем из listWidget текущее значение (id группы) self.group_id = self.dict_count[self.listWidget.currentRow()] # print(self.group_id) # print(self.dict_count) # self.dict_count.pop(self.dict_count[self.group_id]) # print(self.dict_count) # Удаляем текущее значение из JSON self.settings['vk_groups'].pop(self.group_id) print(self.settings['vk_groups']) # Удаляем текущее значение из списка listWidget for item in self.listWidget.selectedItems(): self.listWidget.takeItem(self.listWidget.row(item)) def buttonUrl(self, e): url = self.lineEditUrl.text() try: response = requests.post(url, proxies=self.proxies, auth=self.auth) except IOError: print('Unable to fetch URL!') QMessageBox.critical(self.modalWindowAdd, 'Error','Unable to fetch URL!\nURL must be like: http://vk.com/sergeqwe') return None if response.status_code == 200: # Ищем ID группы result = response.text start = result.find('[group]') id = result[start:start+20] if id: id = int(sub("\D", "", id)) print(id) # Ищем название группы start = result.find('<title>') end = result.find('</title>') groupe_name = result[start+7:end] print(groupe_name) self.listWidget.addItem(str(id) + ':' + groupe_name) self.settings['vk_groups'][str(id)] = groupe_name print(self.settings['vk_groups']) else: QMessageBox.critical(self.modalWindowAdd, 'Error', 'Not a group!') return None else: print('Unable to fetch URL...') self.modalWindowAdd.close() def button_ok(self, e): # Размер preview self.settings['settings']['preview'][0]['prev_size'] = int(self.comboBox.currentText()) self.photo_size = int(self.comboBox.currentText()) # Количество загружаемых страниц self.settings['settings']['pages_load'][0]['num_pages'] = int(self.spinPages.text()) self.num_pages = int(self.spinPages.text()) # Количество строк self.settings['settings']['preview'][0]['num_line'] = int(self.spinRow.text()) self.num_line = int(self.spinRow.text()) # Количество столбцов self.settings['settings']['preview'][0]['num_column'] = int(self.spinColumns.text()) self.num_column = int(self.spinColumns.text()) # Путь (каталог на диске) для сохранения изображений self.settings['settings']['pic_save'][0]['path'] = self.lineEdit.text() self.pic_save_path = self.lineEdit.text() # Проверяем включен ли в настройках прокси # Если прокси выключен, то обнуляем переменную proxies if self.radioButtonNo.isChecked(): print('proxy_disable') self.proxies = {} self.auth = HTTPProxyAuth('', '') if self.radioButtonYes.isChecked(): if self.checkBox.isChecked(): username = self.lineEditLogin.text() password = self.lineEditPwd.text() self.proxies = { "http": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), "https": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), } self.auth = self.auth = HTTPProxyAuth(username, password) self.settings['settings']['proxies'][0]['username'] = self.lineEditLogin.text() self.settings['settings']['proxies'][0]['password'] = self.lineEditPwd.text() else: self.proxies = { "http": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), "https": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), } self.settings['settings']['proxies'][0]['username'] = '' self.settings['settings']['proxies'][0]['password'] = '' self.settings['settings']['proxies'][0]['host'] = self.lineEditProxy.text() self.settings['settings']['proxies'][0]['port'] = self.spinBoxPort.text() else: self.settings['settings']['proxies'][0]['host'] = '' self.settings['settings']['proxies'][0]['port'] = '' self.settings['settings']['proxies'][0]['username'] = '' self.settings['settings']['proxies'][0]['password'] = '' try: fp = open("settings.json", "w") try: json.dump(self.settings, fp, indent=4) finally: fp.close() except IOError: print('error') self.group_fill() self.modalWindow.close() self.first_run = 0 def button_cancel(self, e): print('cancel') self.modalWindow.close() ###################################################################################### # Флаги активности кнопок def check_buttons(self): """Флаги для выставления активности(затемненности) пунктов меню и кнопок""" # Если находимся в режиме росмотра большого фото, то делаем кнопку refresh активной # А кнопку Load недоступной if self.prev_mode == 1: self.actionRefresh.setEnabled(True) self.actionLoad.setEnabled(False) else: self.actionRefresh.setEnabled(False) self.actionLoad.setEnabled(True) if self.loading_error == False: # Если в режиме preview и на последней странице, то затемняем кнопку next if self.current_page == (len(self.result["response"]["items"])) / (self.num_line * self.num_column)\ and self.prev_mode == 0: self.actionPreview.setEnabled(True) self.actionNext.setEnabled(False) else: self.actionPreview.setEnabled(True) self.actionNext.setEnabled(True) # Если в режиме preview и на первой странице, то затемняем кнопку preview if self.current_page == 1 and self.prev_mode == 0: self.actionPreview.setEnabled(False) self.actionNext.setEnabled(True) # Загружаем список фото def load_pic_list(self): self.downloading('Loading...') self.wait() if self.first_run == 0: self.group_fill_ava() self.first_run = 1 current_row = self.listWidgetMain.currentRow() # Берем из listWidget текущее значение (id группы) if self.DEBUG: print('Current row (group): ' + str(current_row)) if current_row == -1: current_row = 0 if self.DEBUG: print('Current row (group): ' + str(current_row)) self.group_id = self.dict_count[current_row] if self.DEBUG: print('Groupe ID: ' + self.group_id) """Загружаем и парсим JSON""" # self.label.setPixmap(QtGui.QPixmap("pic/avto.jpg").scaled(200, 200, QtCore.Qt.KeepAspectRatio)) req = 'https://api.vk.com/method/photos.get?v=5.32' \ '&owner_id=-{0}' \ '&album_id=wall&count={1}' \ '&rev=1&photo_sizes=1'.format(self.group_id,(self.num_line * self.num_column) * self.num_pages) if self.DEBUG: print('Loading JSON list of pics: ' + req) try: response = requests.get(req, proxies=self.proxies, auth=self.auth, timeout=3) except requests.exceptions.Timeout: print('Time out') self.loading_error = True except requests.exceptions.ProxyError: print('04 Gateway Time-out') self.loading_error = True except IOError: print('Error loading JSON') self.loading_error = True # if response.status_code != 200: # print('Косяк. Статус код') # self.loading_error = True if self.loading_error == False: self.result = json.loads(response.text) # req = Request(req) # # try: # response = urlopen(req) # # except HTTPError as e: # print('The server couldn\'t fulfill the request.') # print('Error code: ', e.code) # exit(0) # # except URLError as e: # print('We failed to reach a server.') # print('Reason: ', e.reason) # exit(0) # # self.result = json.loads(response.read().decode('utf8')) # print('JSON LOADING OK') # print(self.result) # Ищем приблизительно равные размеры фото заданные в переменной photo_size # Так же помещаем в переменную photo_date дату публикации фото if self.DEBUG: print('Всего фото загружено: ' + str(len(self.result["response"]["items"]))) if len(self.result["response"]["items"]) < (self.num_line * self.num_column) * self.num_pages: print('НЕТ СТОЛЬКО ФОТО!') exit(0) return None self.photo_avg = [] self.photo_date = [] e = 0 while e < len(self.result["response"]["items"]): i = 0 v = [] while i < len(self.result["response"]["items"][e]["sizes"]): v.append(abs(self.photo_size - self.result["response"]["items"][e]["sizes"][i]["height"])) i += 1 out = 0 generator = enumerate(v) out = [i for i,x in generator if x == min(v)] self.photo_avg.append(self.result["response"]["items"][e]["sizes"][out[0]]["src"]) self.photo_date.append(self.result["response"]["items"][e]["date"]) e += 1 # Ищем картинку с самым большим разрешением self.photo_max = [] e = 0 while e < len(self.result["response"]["items"]): i = 0 v = 0 count = 0 while i < len(self.result["response"]["items"][e]["sizes"]): if v < self.result["response"]["items"][e]["sizes"][i]["height"]: v = self.result["response"]["items"][e]["sizes"][i]["height"] count = i i += 1 self.photo_max.append(self.result["response"]["items"][e]["sizes"][count]["src"]) e += 1 if self.DEBUG: print(self.photo_max) # self.modalWindowDownloading.close() self.splash.close() # Загружаем preview def load_pic_prev(self): """Загружаем фото с сайта в зависимости от страницы и момещаем их в список loading_image""" # Показываем заставку при загрузке self.downloading('Img...') self.wait() if self.loading_error == False: if self.result and len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages: self.loading_image = [] # Обнуляем список mult_num = self.num_line * self.num_column for i in range(self.current_page * mult_num - mult_num, self.current_page * mult_num): # req = Request(self.photo_avg[i]) # response = urlopen(req).read() try: response = requests.get(self.photo_avg[i], proxies=self.proxies, auth=self.auth) except IOError: print('Не смог загрузить preview на страницу') exit(0) image = QImage() image.loadFromData(response.content) self.loading_image.append(image) if self.DEBUG: print(str(i) + ')' + self.photo_avg[i]) self.splash.showMessage(os.path.basename(self.photo_avg[i]), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) else: print('NO_RESULT') # self.modalWindowDownloading.close() # print('На странице: ' + str(self.loading_image)) if self.loading_image[0].size().width() <=0: if self.DEBUG: print('Error internet connection') # QMessageBox.critical(window, 'Error','Error internet connection') self.splash.close() msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'Check internet connection', QMessageBox.NoButton) msgBox.exec_() self.first_run = 0 return None self.splash.close() # Выводим preview def draw_pic(self): if self.loading_error == False: """Выводим preview""" self.clear_screen() # Очищаем окно if len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages: t = 0 for i in range(self.num_line): for n in range(self.num_column): self.icon[t] = QtGui.QIcon() self.icon[t].addPixmap(QtGui.QPixmap(self.loading_image[t]), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.button[t] = QtWidgets.QPushButton(self.centralwidget) self.button[t].setIcon(self.icon[t]) self.button[t].setIconSize(QtCore.QSize(self.photo_size, self.photo_size)) self.button[t].setFlat(True) # self.button[t].setStyleSheet('background-color:#FFFFFF;color:#000000;') # self.button[t].setStyleSheet("font-size:40px;background-color:#333333;border: 2px solid #222222") # self.button[t].setStyleSheet("border: 1px solid #222222") self.gridLayout_2.addWidget(self.button[t], i, n, 1, 1, QtCore.Qt.AlignTop) self.button[t].setObjectName("Button: " + str(t)) self.pic_date[t] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(self.photo_date[t])) self.button[t].setToolTip(str(self.pic_date[t])) self.button[t].clicked.connect(self.full_pic_view) t += 1 else: print('Не совпало') exit(0) # Выход из просмотра большой картинки при нажатии левой кнопки и сохранение картинки при нажатии правой кнопки def close_full_pic_view(self, e): """Закрываем просмотр большой картинки левым кликом мыши""" if e.buttons() == QtCore.Qt.LeftButton: if self.DEBUG: print('left button pressed') self.prev_mode = 0 # Флаг, что выходим из просмотра в preview self.clear_screen() # Удаляем изображение self.check_buttons() self.draw_pic() self.statusbar.showMessage('Page: ' + str(self.current_page)) # Созраняем изображение при нажатии правой кнопки мыши if e.buttons() == QtCore.Qt.RightButton: path = self.pic_save_path + '/' + os.path.basename(self.photo_max[self.photo_max_id]) print(path) self.image.save(path) if os.path.exists(path): self.statusbar.showMessage('File saved to: ' + path ) else: self.statusbar.showMessage('File is not saved. Сheck the path settings!' ) msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'File is not saved. Сheck the path settings!\n<File-Settings-Path>', QMessageBox.NoButton) msgBox.exec_() # Очищаем окно def clear_screen(self): """Удаляем все кнопки с изображениями (очищаем окно)""" while self.gridLayout_2.count(): item = self.gridLayout_2.takeAt(0) item.widget().deleteLater() # Определяем какая кнопка (превиюшка) была нажата def wat_is_button(self): """Определяем какая кнопка была нажата""" sender1 = self.sender().objectName() self.sender1 = int(sub("\D", "", sender1)) print(self.sender1) # Определяем размер окна def win_size(self): """Определяем размер окна (scrollArea), чтобы оно не растягивалось, если размер изображения больше, чем размер окна""" # self.height = window.size().height() - 70 # self.width = window.size().width() - 10 self.height = self.scrollArea.size().height() self.width = self.scrollArea.size().width() # Окно загрузки def downloading(self, msg): # print('downloading...') # self.modalWindowDownloading = QWidget(window, Qt.Window) # self.modalWindowDownloading.setWindowModality(Qt.WindowModal) # Ui_FormDownload.setupUi(self, self.modalWindowDownloading) # Ui_FormDownload.retranslateUi(self, self.modalWindowDownloading) # self.modalWindowDownloading.show() image = QPixmap('./pic/loading1.jpg') self.splash = QSplashScreen(image) self.splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) font = QFont(self.splash.font()) font.setPointSize(font.pointSize() + 3) self.splash.setFont(font) self.splash.showMessage(msg, QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) self.splash.show() def wait(self): start = time.time() while time.time() - start < 1: time.sleep(0.001) app.processEvents()
class GuiApplicationBase(ApplicationBase, QApplication): _logger = logging.getLogger(__name__) has_gui = True ############################################## def __init__(self, args, **kwargs): super(GuiApplicationBase, self).__init__(args=args, **kwargs) # Fixme: Why ? self._logger.debug("QApplication " + str(sys.argv)) QApplication.__init__(self, sys.argv) self._logger.debug('GuiApplicationBase ' + str(args) + ' ' + str(kwargs)) self.setAttribute(Qt.AA_EnableHighDpiScaling) # from . import BabelRessource rcc_path = ConfigInstall.Path.join_share_directory('babel.rcc') self._logger.debug('Load ressource {}'.format(rcc_path)) if not QResource.registerResource(str(rcc_path)): self._logger.debug('Failed to load ressource {}'.format(rcc_path)) # self._display_splash_screen() self._main_window = None self._initialise_qml_engine() self._init_actions() ############################################## @property def main_window(self): return self._main_window @property def qml_engine(self): return self._qml_engine @property def qml_context(self): return self._qml_engine.rootContext() ############################################## def _exception_hook(self, exception_type, exception_value, exception_traceback): traceback.print_exception(exception_type, exception_value, exception_traceback) dialog = CriticalErrorDialog( exception_type, exception_value, exception_traceback, qml_engine=self._qml_engine ) rc = dialog.exec_() if rc == -1: self.exit() # return sys.__excepthook__(exception_type, exception_value, exception_traceback) ############################################## def _display_splash_screen(self): pixmap = QPixmap(':/splash screen/images/splash_screen.png') self._splash = QSplashScreen(pixmap) self._splash.show() self._splash.showMessage('<h2>Babel %(version)s</h2>' % {'version':str(Version.babel)}) self.processEvents() ############################################## def _initialise_qml_engine(self): self._qml_engine = QQmlEngine(self) qml_path = str(ConfigInstall.Path.qml_path) self._qml_engine.addImportPath(qml_path) context = self.qml_context self._application_style = ApplicationStyle() context.setContextProperty('application_style', self._application_style) self._icon_provider = IconProvider() self._qml_engine.addImageProvider('icon_provider', self._icon_provider) ############################################## def _init_actions(self): self.about_action = QAction( 'About Babel', self, triggered=self.about, ) self.exit_action = QAction( 'Exit', self, triggered=self.exit, ) self.help_action = QAction( 'Help', self, triggered=self.open_help, ) self.show_system_information_action = QAction( 'System Information', self, triggered=self.show_system_information, ) ############################################## def post_init(self): # self._splash.finish(self._main_window) # self.processEvents() # del self._splash QTimer.singleShot(0, self.execute_given_user_script) self.show_message('Welcome to Babel') # return to main and then enter to event loop ############################################## def show_message(self, message=None, echo=False, timeout=0): # Fixme: cf. PdfBrowserApplication if self._main_window is not None: self._main_window.show_message(message, echo, timeout) ############################################## # def critical_error(self, title='Babel Critical Error', message=''): # # # Fixme: CriticalErrorForm vs critical_error # # QMessageBox.critical(None, title, message) # # # Fixme: qt close? # sys.exit(1) ############################################## def open_help(self): url = QUrl() url.setScheme(DefaultConfig.Help.url_scheme) url.setHost(DefaultConfig.Help.host) url.setPath(DefaultConfig.Help.url_path_pattern) # % str(Version.babel)) QDesktopServices.openUrl(url) ############################################## def about(self): message = Messages.about_babel % {'version':str(Version.babel)} QMessageBox.about(self.main_window, 'About Babel', message) ############################################## def show_system_information(self): fields = dict(self._platform.__dict__) fields.update({ 'babel_version': str(Version.babel), }) message = Messages.system_information_message_pattern % fields QMessageBox.about(self.main_window, 'System Information', message)
class QtApplication(QApplication, Application, SignalEmitter): def __init__(self, **kwargs): plugin_path = "" if sys.platform == "win32": plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins") Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) elif sys.platform == "darwin": plugin_path = os.path.join(Application.getInstallPrefix(), "Resources", "plugins") if plugin_path: Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) os.environ["QSG_RENDER_LOOP"] = "basic" super().__init__(sys.argv, **kwargs) self._main_qml = "main.qml" self._engine = None self._renderer = None try: self._splash = QSplashScreen(QPixmap(Resources.getPath(Resources.ImagesLocation, self.getApplicationName() + ".png"))) except FileNotFoundError: self._splash = None else: self._splash.show() self.processEvents() signal.signal(signal.SIGINT, signal.SIG_DFL) # This is done here as a lot of plugins require a correct gl context. If you want to change the framework, # these checks need to be done in your <framework>Application.py class __init__(). i18n_catalog = i18nCatalog("uranium") self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading plugins...")) self._loadPlugins() self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading machines...")) self.loadMachines() self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading preferences...")) try: file = Resources.getPath(Resources.PreferencesLocation, self.getApplicationName() + ".cfg") Preferences.getInstance().readFromFile(file) except FileNotFoundError: pass self._translators = {} self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading translations...")) self.loadQtTranslation("uranium_qt") self.loadQtTranslation(self.getApplicationName() + "_qt") def run(self): pass def hideMessage(self, message): with self._message_lock: if message in self._visible_messages: self._visible_messages.remove(message) self.visibleMessageRemoved.emit(message) def showMessage(self, message): with self._message_lock: if message not in self._visible_messages: self._visible_messages.append(message) message.setTimer(QTimer()) self.visibleMessageAdded.emit(message) pass def setMainQml(self, path): self._main_qml = path def initializeEngine(self): # TODO: Document native/qml import trickery Bindings.register() self._engine = QQmlApplicationEngine() self.engineCreatedSignal.emit() self._engine.addImportPath(os.path.join(os.path.dirname(sys.executable), "qml")) self._engine.addImportPath(os.path.join(Application.getInstallPrefix(), "Resources", "qml")) if not hasattr(sys, "frozen"): self._engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml")) self.registerObjects(self._engine) self._engine.load(self._main_qml) engineCreatedSignal = Signal() def registerObjects(self, engine): pass def getRenderer(self): if not self._renderer: self._renderer = QtGL2Renderer() return self._renderer # Overridden from QApplication::setApplicationName to call our internal setApplicationName def setApplicationName(self, name): Application.setApplicationName(self, name) # Handle a function that should be called later. def functionEvent(self, event): e = _QtFunctionEvent(event) QCoreApplication.postEvent(self, e) # Handle Qt events def event(self, event): if event.type() == _QtFunctionEvent.QtFunctionEvent: event._function_event.call() return True return super().event(event) def windowClosed(self): self.getBackend().close() self.quit() self.saveMachines() Preferences.getInstance().writeToFile(Resources.getStoragePath(Resources.PreferencesLocation, self.getApplicationName() + ".cfg")) ## Load a Qt translation catalog. # # This method will locate, load and install a Qt message catalog that can be used # by Qt's translation system, like qsTr() in QML files. # # \param file The file name to load, without extension. It will be searched for in # the i18nLocation Resources directory. If it can not be found a warning # will be logged but no error will be thrown. # \param language The language to load translations for. This can be any valid language code # or 'default' in which case the language is looked up based on system locale. # If the specified language can not be found, this method will fall back to # loading the english translations file. # # \note When `language` is `default`, the language to load can be changed with the # environment variable "LANGUAGE". def loadQtTranslation(self, file, language = "default"): #TODO Add support for specifying a language from preferences path = None if language == "default": # If we have a language set in the environment, try and use that. lang = os.getenv("LANGUAGE") if lang: try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: path = None # If looking up the language from the enviroment fails, try and use Qt's system locale instead. if not path: locale = QLocale.system() # First, try and find a directory for any of the provided languages for lang in locale.uiLanguages(): try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: break # If that fails, see if we can extract a language "class" from the # preferred language. This will turn "en-GB" into "en" for example. if not path: lang = locale.uiLanguages()[0] lang = lang[0:lang.find("-")] try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: path = Resources.getPath(Resources.i18nLocation, language, "LC_MESSAGES", file + ".qm") # If all else fails, fall back to english. if not path: Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file)) try: path = Resources.getPath(Resources.i18nLocation, "en", "LC_MESSAGES", file + ".qm") except FileNotFoundError: Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file) return # Store a reference to the translator. # This prevents the translator from being destroyed before Qt has a chance to use it. self._translators[file] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator) ## Display text on the splash screen. def showSplashMessage(self, message): if self._splash: self._splash.showMessage(message , Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() ## Close the splash screen after the application has started. def closeSplash(self): if self._splash: self._splash.close() self._splash = None
class Splash(QObject, LogMixin, EventMixin): """Splash screen class""" def __init__(self, parent, msg = ""): """ Constructor of Splash screen :param parent: ui parent :param msg: initial message text """ super().__init__() self._parent = parent self.isHidden = True self._progress = 0 self._progressBar = None self.msg = msg pixmap = QtGui.QPixmap(380, 100) pixmap.fill(QtGui.QColor("darkgreen")) self._splash = QSplashScreen(pixmap) self._splash.setParent(self._parent) self.add_progressbar() def add_progressbar(self): """Add separate progress bar to splash screen""" self._progressBar = QProgressBar(self._splash) self._progressBar.setGeometry(self._splash.width() / 10, 8 * self._splash.height() / 10, 8 * self._splash.width() / 10, self._splash.height() / 10) self._progressBar.hide() def setProgress(self, val): """ Set progress bar to ``val`` If splash has no progressbar, it will be added dynamically. Remove progressbar with ``val`` as None. :param val: absolut percent value :return: """ if val is not None: self._progressBar.show() self._progressBar.setTextVisible(True) self.progress = val try: self._progressBar.setValue(self.progress) except: pass else: self._progressBar.setTextVisible(False) self._progressBar.hide() self._progressBar.reset() if self.isHidden is True: self.isHidden = False self.show_() def incProgress(self, val): """ Increase progressbar value by ``val`` If splash has no progressbar, it will be added dynamically. Remove progressbar with ``val`` as None. :param val: value to increase by :return: """ if val is not None: self._progressBar.show() self._progressBar.setTextVisible(True) self.progress = self.progress + val try: self._progressBar.setValue(self.progress) qApp.processEvents() except: pass else: self._progressBar.setTextVisible(False) self._progressBar.hide() self._progressBar.reset() if self.isHidden is True: self.isHidden = False self.show_() def setParent(self, parent): """Set splash's parent""" self._parent = parent self._splash.setParent(parent) @pyqtSlot() @pyqtSlot(bool) def close(self, dummy = True): self.logger.debug("Hide splash") self.isHidden = True self._progressBar.hide() self._progressBar.reset() self._splash.close() @pyqtSlot() @pyqtSlot(str) def show_(self, msg = ""): if msg != "": self._splash.showMessage(msg, QtCore.Qt.AlignCenter, QtCore.Qt.white) else: self.logger.debug("Show splash, parent: " + str(self._parent)) self._splash.showMessage(self.msg, QtCore.Qt.AlignCenter, QtCore.Qt.white) try: #if platform.system() == "Linux": parentUi = self._parent.centralwidget.geometry() # need to use centralwidget for linux preferably, don't know why except: #else: parentUi = self._parent.childrenRect() mysize = self._splash.geometry() hpos = parentUi.x() + ((parentUi.width() - mysize.width()) / 2) vpos = parentUi.y() + ((parentUi.height() - mysize.height()) / 2) self._splash.move(hpos, vpos) self._splash.show() qApp.processEvents() @property def progress(self): return self._progress @progress.setter def progress(self, value): # create new exception handling vor properties # if (value != "True") and (value != "False"): # raise ValueError("describe exception") if value > 100: value = 0 if value < 0: value = 0 self._progress = value
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking #if not settings.IS_WINDOWS: #app.setCursorFlashTime(0) #Set the codec for strings (QString) ##QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load( "qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) #Set Stylesheet style_applied = False print(settings.NINJA_SKIN) if settings.NINJA_SKIN not in ('Default'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) #Showing GUI ninjaide.show() #OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #First check if we need to load last session files if qsettings.value('preferences/general/loadFiles', True, type=bool): #Files in Main Tab files = data_qsettings.value('lastSession/openedFiles', []) tempFiles = [] if files: for file_ in files: fileData = tuple(file_) if fileData: tempFiles.append(fileData) files = tempFiles # Recent Files recent_files = data_qsettings.value('lastSession/recentFiles', []) #Current File current_file = data_qsettings.value( 'lastSession/currentFile', '', type='QString') #Projects projects = data_qsettings.value('lastSession/projects', []) else: files = [] recent_files = [] current_file = '' projects = [] #Include files received from console args file_with_nro = list([(f[0], (f[1] - 1, 0), 0) for f in zip(filenames, linenos)]) file_without_nro = list([(f, (0, 0), 0) for f in filenames[len(linenos):]]) files += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path #FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT ninjaide.load_session_files_projects(files, projects, current_file, recent_files) #Load external plugins #if extra_plugins: #ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()
def main(): print("Platform is %s (%s)" %(platform.system(), sys.platform)) if platform.system() == "Windows": print("Applying Windows-specific setup") # On Windows, redirect stderr to a file import imp import ctypes if (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")): # tools/freeze sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w") # set the App ID for Windows 7 to properly display the icon in the # taskbar. myappid = 'Friture.Friture.Friture.current' # arbitrary string try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) except: print("Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal.") app = QApplication(sys.argv) if platform.system() == "Darwin": if hasattr(sys, "frozen"): #py2app sys.stdout = open(os.path.expanduser("~/friture.out.txt"), "w") sys.stderr = open(os.path.expanduser("~/friture.err.txt"), "w") print("Applying Mac OS-specific setup") # help the py2app-packaged application find the Qt plugins (imageformats and platforms) pluginsPath = os.path.normpath(os.path.join(QApplication.applicationDirPath(), os.path.pardir, 'PlugIns')) print("Adding the following to the Library paths: " + pluginsPath) QApplication.addLibraryPath(pluginsPath) # Splash screen pixmap = QPixmap(":/images/splash.png") splash = QSplashScreen(pixmap) splash.show() splash.showMessage("Initializing the audio subsystem") app.processEvents() # Logger class logger = Logger() window = Friture(logger) window.show() splash.finish(window) profile = "no" # "python" or "kcachegrind" or anything else to disable if len(sys.argv) > 1: if sys.argv[1] == "--python": profile = "python" elif sys.argv[1] == "--kcachegrind": profile = "kcachegrind" elif sys.argv[1] == "--no": profile = "no" else: print("command-line arguments (%s) not recognized" % sys.argv[1:]) if profile == "python": import cProfile import pstats cProfile.runctx('app.exec_()', globals(), locals(), filename="friture.cprof") stats = pstats.Stats("friture.cprof") stats.strip_dirs().sort_stats('time').print_stats(20) stats.strip_dirs().sort_stats('cumulative').print_stats(20) sys.exit(0) elif profile == "kcachegrind": import cProfile import lsprofcalltree p = cProfile.Profile() p.run('app.exec_()') k = lsprofcalltree.KCacheGrind(p) with open('cachegrind.out.00000', 'wb') as data: k.output(data) sys.exit(0) else: sys.exit(app.exec_())
def main(): if platform.system() == "Windows": print("Running on Windows") # On Windows, redirect stderr to a file import imp, ctypes if (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")): # tools/freeze sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w") # set the App ID for Windows 7 to properly display the icon in the # taskbar. myappid = 'Friture.Friture.Friture.current' # arbitrary string try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) except: print("Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal.") app = QApplication(sys.argv) # Splash screen pixmap = QPixmap(":/images/splash.png") splash = QSplashScreen(pixmap) splash.show() splash.showMessage("Initializing the audio subsystem") app.processEvents() # Set the separator stylesheet here # As of Qt 4.6, separator width is not handled correctly # when the stylesheet is applied directly to the QMainWindow instance. # QtCreator workarounds it with a "minisplitter" special class app.setStyleSheet(STYLESHEET) # Logger class logger = Logger() window = Friture(logger) window.show() splash.finish(window) profile = "no" # "python" or "kcachegrind" or anything else to disable if len(sys.argv) > 1: if sys.argv[1] == "--python": profile = "python" #elif sys.argv[1] == "--kcachegrind": #profile = "kcachegrind" elif sys.argv[1] == "--no": profile = "no" else: print("command-line arguments (%s) not recognized" %sys.argv[1:]) if profile == "python": import cProfile import pstats cProfile.runctx('app.exec_()', globals(), locals(), filename="friture.cprof") stats = pstats.Stats("friture.cprof") stats.strip_dirs().sort_stats('time').print_stats(20) stats.strip_dirs().sort_stats('cumulative').print_stats(20) sys.exit(0) #elif profile == "kcachegrind": #import cProfile #import lsprofcalltree #p = cProfile.Profile() #p.run('app.exec_()') #k = lsprofcalltree.KCacheGrind(p) #data = open('cachegrind.out.00000', 'wb') #k.output(data) #data.close() ## alternative code with pyprof2calltree instead of lsprofcalltree ##import pyprof2calltree ##pyprof2calltree.convert(p.getstats(), "cachegrind.out.00000") # save #sys.exit(0) else: sys.exit(app.exec_())
def main(): try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass # ignore this as it might fail on macOS, we'll fallback to UTF-8 in that case if config.get_use_fusion_gui_style(): sys.argv += ['-style', 'fusion'] if '--error-report' in sys.argv: sys.exit(error_report_main()) # Catch all uncaught exceptions and show an error message for them. # PyQt5 does not silence exceptions in slots (as did PyQt4), so there # can be slots which try to (for example) send requests but don't wrap # them in an async call with error handling. argv = deepcopy(sys.argv) # Deep copy because QApplication (i.e. BrickViewer) constructor parses away Qt args and we want to know the style. if '--no-error-reporter' not in sys.argv: ExceptionReporter(argv) # Exceptions that happen before the event loop runs (f.e. syntax errors) kill the brickv so fast, that the error reporter thread # (which is daemonized) can not report the error before it is killed. Report them manually. try: # importing the MainWindow after creating the QApplication instance triggers this warning # # Qt WebEngine seems to be initialized from a plugin. Please set Qt::AA_ShareOpenGLContexts # using QCoreApplication::setAttribute before constructing QGuiApplication. # # do what the warnings says to avoid it QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) brick_viewer = BrickViewer(sys.argv) if sys.platform == 'darwin': # workaround macOS QTBUG-61562 from brickv.mac_pasteboard_mime_fixed import MacPasteboardMimeFixed mac_pasteboard_mime_fixed = MacPasteboardMimeFixed() splash = QSplashScreen(load_pixmap('splash.png'), Qt.WindowStaysOnTopHint) splash.show() message = 'Starting Brick Viewer ' + config.BRICKV_VERSION if config.INTERNAL != None: message += '~{}'.format(config.INTERNAL) splash.showMessage(message, Qt.AlignHCenter | Qt.AlignBottom, Qt.white) brick_viewer.processEvents() from brickv.mainwindow import MainWindow main_window = MainWindow() main_window.show() splash.finish(main_window) except: if '--no-error-reporter' in sys.argv: raise etype, value, tb = sys.exc_info() error = "".join(traceback.format_exception(etype, value, tb)) error = "The following error is fatal. Exiting now.\n\n" + error traceback.print_exception(etype, value, tb) try: splash.close() except: pass # Either sys.executable is /path/to/python, then run calls /path/to/python /path/to/main.py --error-report, # or sys.executable is brickv[.exe], then the --error-report flag ensures, that the path to main.py is ignored. subprocess.run([sys.executable, os.path.realpath(__file__), "--error-report"] + argv, input=error, universal_newlines=True) sys.exit(1) sys.exit(brick_viewer.exec_())
self.schlumbergerLayout = False self.wennerLayout = True def schlumberger(self): """Define Schlumberger layout is True""" self.schlumbergerLayout = True self.wennerLayout = False if __name__ == '__main__': app = QApplication(sys.argv) app.setWindowIcon(QIcon('hand_drill.png')) splashPix = QPixmap('splash.png') splashScreen = QSplashScreen(splashPix, Qt.WindowStaysOnTopHint) splashScreen.setMask(splashPix.mask()) splashScreen.show() app.processEvents() time.sleep(3) startup = StartupWindow(tableData, headers, colors, old_coefficients) startup.show() splashScreen.finish(startup) sys.exit(app.exec_())