class SnowflakeUI: def __init__(self, qmlfile, gamesdb): self.engine = QQmlApplicationEngine() self.games_db = gamesdb self.root_qml = qmlfile self.platformsListModel = self._load_platforms() self.gamesListModel = self._load_games() def init_ui(self): self.engine.load(QUrl(self.root_qml)) def show(self): raise NotImplementedError def get_root(self): raise NotImplementedError def _load_games(self): gameslist = {} keys = Loadables.Instance().platforms.keys() for platform in keys: games = self.games_db.get_games_for_platform(platform) gameslist[platform] = qml_games.RunnableGamesListModel(sorted((qml_games.RunnableGameWrapper(game) for game in games), key=lambda game: game.game.gameinfo.title)) return gameslist def _load_platforms(self): return qml_platforms.PlatformsListModel(sorted((qml_platforms.PlatformsWrapper(platform_info) for platform_info in iter(Loadables.Instance().platforms.values())), key = lambda platform: platform.platform_id))
def __init__(self, qml): app = QGuiApplication(sys.argv) model = QmlModel() model.register() qmlUrl = QUrl(qml) assert qmlUrl.isValid() print(qmlUrl.path()) # assert qmlUrl.isLocalFile() """ Create an engine a reference to the window? window = QuickWindowFactory().create(qmlUrl=qmlUrl) window.show() # visible """ engine = QQmlApplicationEngine() """ Need this if no stdio, i.e. Android, OSX, iOS. OW, qWarnings to stdio. engine.warnings.connect(self.errors) """ engine.load(qmlUrl) engine.quit.connect(app.quit) app.exec_() # !!! C exec => Python exec_ print("Application returned")
class AboutWindow: QML_FILE = "qml/AboutWindow.qml" def __init__(self): # Create window from QML via QQmlApplicationEngine self.engine = QQmlApplicationEngine() self.engine.load(self.QML_FILE) self.window = self.engine.rootObjects()[0]
def main(): print("start") app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.load(QUrl("main.qml")) engine.rootObjects()[0].show() sys.exit(app.exec_())
def main(): app = QGuiApplication(sys.argv) qmlRegisterType(MainController, 'MainController', 1, 0, 'MainController') qmlRegisterType(ProfileViewModel, 'ProfileViewModel', 1, 0, 'ProfileViewModel') engine = QQmlApplicationEngine() main_controller = MainController() main_controller.profile_selection_changed(0) engine.rootContext().setContextProperty('mainController', main_controller) engine.load(QUrl.fromLocalFile(pkg_resources.resource_filename('yarg.resource', 'main.qml'))) sys.exit(app.exec_())
def startgui(): app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.load(QUrl("qrc:/asserts/gui.qml")) classifier = Classifier(engine, SRCFaceClassifier(DALMSolver())) classifier.run() return app.exec_()
class PDFxGui: QML_FILE = "qml/MainWindow.qml" window = None threads = [] pdf_windows = [] def __init__(self): self.threads = [] # Create and setup window self.engine = QQmlApplicationEngine() self.engine.load(self.QML_FILE) self.window = self.engine.rootObjects()[0] # Connect signals self.window.signalOpenPdfs.connect(self.open_pdf) self.window.signalShowAboutWindow.connect(show_about_window) def open_pdf(self, urls): num_pdfs = urls.property("length").toInt() pdf_urls = [urls.property(index).toString() for index in range(num_pdfs)] if len(pdf_urls) == 0: return def signal_item_start(uri): print("started:", uri) self.window.setStatusText("Opening %s..." % (os.path.basename(uri))) def signal_item_finished(uri): print("finished:", uri) win = PdfDetailWindow(uri) win.window.show() self.pdf_windows.append(win) def signal_item_error(uri, error): print("error:", uri, error) def signal_item_extract_page(uri, curpage): print("page:", curpage) self.window.setStatusText("Reading page %s of %s..." % (curpage, os.path.basename(uri))) def signal_finished(): print("all finished") self.window.setState("") self.window.setStatusText("") self.window.setState("busy") open_thread = OpenPdfQThread(pdf_urls) open_thread.signal_item_start.connect(signal_item_start) open_thread.signal_item_extract_page.connect(signal_item_extract_page) open_thread.signal_item_finished.connect(signal_item_finished) open_thread.signal_item_error.connect(signal_item_error) open_thread.signal_finished.connect(signal_finished) open_thread.start() self.threads.append(open_thread)
class MainWindow(QObject): def __init__(self, parent=None): super().__init__(parent) self.log = logging.getLogger(__name__) self._read_settings() self.client = Client(self) if self.remember: self._autologin() self.model = MainWindowViewModel(self) self.loginModel = LoginViewModel(self.client, self.user, self.password, self.remember, self) self.loginModel.panel_visible = not self.remember self.gamesModel = GamesViewModel(self) self.engine = QQmlApplicationEngine(self) self.engine.rootContext().setContextProperty('windowModel', self.model) self.engine.rootContext().setContextProperty('loginModel', self.loginModel) self.engine.rootContext().setContextProperty('contentModel', self.gamesModel) self.engine.quit.connect(parent.quit) self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml')) self.window = self.engine.rootObjects()[0] # wire up logging console self.console = self.window.findChild(QQuickItem, 'console') parent.log_changed.connect(self._log) def show(self): self.window.show() def _read_settings(self): stored = settings.get() stored.beginGroup('login') self.user = stored.value('user') self.password = stored.value('password') self.remember = stored.value('remember') == 'true' stored.endGroup() @async_slot def _autologin(self): try: self.log.info('logging in (auto)...') self.loginModel.logged_in = yield from self.client.login(self.user, self.password) self.log.debug('autologin result: {}'.format(self.loginModel.logged_in)) except Exception as e: self.log.error('autologin failed. {}'.format(e)) @pyqtSlot(str) def _log(self, msg): # replace with collections.deque binding(ish)? if self.console.property('lineCount') == LOG_BUFFER_SIZE: line_end = self.console.property('text').find('\n') + 1 self.console.remove(0, line_end) self.console.append(msg)
class Application(QApplication): def __init__(self, argv): super(Application, self).__init__(argv) stderrHandler = logging.StreamHandler(stream=sys.stderr) stderrHandler.setLevel(logging.WARN) stdoutHandler = logging.StreamHandler(stream=sys.stdout) stdoutHandler.setLevel(logging.INFO) stdoutHandler.filter = lambda rec: rec.levelno <= stdoutHandler.level logging.basicConfig( format='%(name)-15s %(message)s', level=logging.INFO, handlers=[stderrHandler, stdoutHandler] ) logger.info("__init__") self._qml_engine = QQmlApplicationEngine() self._root_context = self._qml_engine.rootContext() self.char = Character(self) def setContext(self, name, value): self._root_context.setContextProperty(name, value) def start(self): logger.info("start") self.setContext('character', self.char) self.readModels() self._qml_engine.load(QUrl("qrc:/ui/main.qml")) def readModels(self): logger.info("readModels") modelTypes = [ MODEL.Perk, MODEL.Quirk, MODEL.Species ] allDelayedInits = {} for modelType in modelTypes: delayedInits = [] logger.info("parsing model %s", modelType.__name__) g = modelParsers.parse(modelType, delayedInits=delayedInits) allDelayedInits[modelType] = delayedInits model = list(g) # TODO name = "%sModel" % modelType.__name__ assert model is not None, "failed to parse {0}".format(modelType.__name__) self.setContext(name, model) for modelType, delayedInits in allDelayedInits.items(): logger.info("delayed init model %s (%s)", modelType.__name__, len(delayedInits)) for delayedInit in delayedInits: delayedInit() def exec(self): logger.info("exec") super().exec()
def main(argv=None): if not argv: argv = sys.argv app = QApplication(argv) # register own type qmlRegisterType(QmlController, 'QmlController', 1, 0, 'QmlController') engine = QQmlApplicationEngine(app) engine.load(QUrl('main.qml')) return app.exec_()
def create(self, qmlUrl): # assert isinstance(qmlUrl, QUrl) engine = QQmlApplicationEngine(qmlUrl) try: qmlRoot = engine.rootObjects()[0] except: qWarning("Failed to read or parse qml.") raise print(qmlRoot) #assert isinstance(qmlRoot, QQuickWindow) return qmlRoot #super().__init__(qmlRoot) '''
def __init__(self, parent=None): super().__init__(parent) self.log = logging.getLogger(__name__) self._read_settings() self.client = Client(self) if self.remember: self._autologin() self.model = MainWindowViewModel(self) self.loginModel = LoginViewModel(self.client, self.user, self.password, self.remember, self) self.loginModel.panel_visible = not self.remember self.gamesModel = GamesViewModel(self) self.engine = QQmlApplicationEngine(self) self.engine.rootContext().setContextProperty('windowModel', self.model) self.engine.rootContext().setContextProperty('loginModel', self.loginModel) self.engine.rootContext().setContextProperty('contentModel', self.gamesModel) self.engine.quit.connect(parent.quit) self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml')) self.window = self.engine.rootObjects()[0] # wire up logging console self.console = self.window.findChild(QQuickItem, 'console') parent.log_changed.connect(self._log)
def __init__(self, pdf_uri, fake=False): self.fake = fake # Create window self.engine = QQmlApplicationEngine() self.engine.load(self.QML_FILE) self.window = self.engine.rootObjects()[0] self.window.setTitle(os.path.basename(pdf_uri)) # Connect signals self.window.download.connect(self.download) self.window.signalCheckLinks.connect(self.checkLinks) self.window.shutdown.connect(self.onClosing) self.window.signalOpenMainWindow.connect(self.openMainWindow) self.window.signalShowAboutWindow.connect(show_about_window) if self.fake: # self.references = REFS_TEST self.references = [] else: # Sort references by type ref_set = PDFX_INSTANCES[pdf_uri].get_references() self.references = sorted(ref_set, key=lambda ref: ref.reftype) self.num_references = len(self.references) self.window.setStatusText("%s references" % self.num_references) for ref in self.references: self.window.addReference(ref.ref, ref.reftype)
class SmartControlApplication(QGuiApplication): _instance = None WINDOW_ICON = "smart-control.png" DEFAULT_THEME = "default" MAIN_QML = "main.qml" def __init__(self, **kwargs): if sys.platform == "win32": if hasattr(sys, "frozen"): QCoreApplication.addLibraryPath(os.path.join(os.path.abspath(os.path.dirname(sys.executable)), "PyQt5", "plugins")) else: import site for dir in site.getsitepackages(): QCoreApplication.addLibraryPath(os.path.join(dir, "PyQt5", "plugins")) super().__init__(sys.argv, **kwargs) self.setApplicationVersion(version) self._engine = QQmlApplicationEngine() self._internationalization = Internationalization() self._theme = Theme() self._printerConnectionManager = PrinterConnectionManager() @classmethod def instance(cls): if SmartControlApplication._instance is None: SmartControlApplication._instance = cls() return SmartControlApplication._instance def run(self): self._internationalization.load(locale.getdefaultlocale()[0]) self._theme.load(SmartControlApplication.DEFAULT_THEME) self._printerConnectionManager.start() self.aboutToQuit.connect(self._onClose) self.setWindowIcon(QIcon(Resources.icon(SmartControlApplication.WINDOW_ICON))) Binder(self._internationalization, self._theme, self._printerConnectionManager).register() self._engine = QQmlApplicationEngine() if sys.platform == "win32": self._engine.addImportPath(os.path.join(os.path.abspath(os.path.dirname(sys.executable)), "qml")) self._engine.load(Resources.qml(SmartControlApplication.MAIN_QML)) sys.exit(self.exec_()) def _onClose(self): self._printerConnectionManager.stop()
class MainWindow(QObject): def __init__(self, parent=None): super().__init__(parent) self.model = MainWindowViewModel(self) self.loginModel = LoginViewModel(self) self.engine = QQmlApplicationEngine(self) self.engine.rootContext().setContextProperty('model', self.model) self.engine.rootContext().setContextProperty('loginModel', self.loginModel) self.engine.quit.connect(parent.quit) self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml')) self.window = self.engine.rootObjects()[0] # wire up logging console self.log = self.window.findChild(QQuickItem, 'log') parent.log_changed.connect(self._log) def show(self): self.window.show() def _log(self, msg): # replace with collections.deque binding(ish)? if self.log.property('lineCount') == LOG_BUFFER_SIZE: line_end = self.log.property('text').find('\n') + 1 self.log.remove(0, line_end) self.log.append(msg)
class MyApp(QObject): def __init__(self, qml, set_context=None): super().__init__() self.app = QApplication(sys.argv) self.engine = QQmlApplicationEngine(self) self.root_context = self.engine.rootContext() if set_context: set_context(self.root_context) self.engine.load(QUrl(qml)) self.root_view = self.engine.rootObjects()[0] @staticmethod def run(my_app): my_app.root_view.show() return my_app.app.exec_()
def __init__(self, gui): self._app = QApplication(sys.argv) self._app.setOrganizationName(self.organization) self._app.setApplicationName(self.name) self._context = _ApplicationContext() self._engine = QQmlApplicationEngine() self._engine.rootContext().setContextProperty('pisak', self._context) self._engine.load(gui)
def __init__(self): self.threads = [] # Create and setup window self.engine = QQmlApplicationEngine() self.engine.load(self.QML_FILE) self.window = self.engine.rootObjects()[0] # Connect signals self.window.signalOpenPdfs.connect(self.open_pdf) self.window.signalShowAboutWindow.connect(show_about_window)
def __init__(self, qml, set_context=None): super().__init__() self.app = QApplication(sys.argv) self.engine = QQmlApplicationEngine(self) self.root_context = self.engine.rootContext() if set_context: set_context(self.root_context) self.engine.load(QUrl(qml)) self.root_view = self.engine.rootObjects()[0]
def _contextNeedOSD(self, area): def _osdClosed(): self._osdVisible = False self._osdVisible = True self._qmlEngine = QQmlApplicationEngine() self._qmlEngine.load(QUrl(OSD_QML)) osd = self._qmlEngine.rootObjects()[0] osd.setX(area.x() + (area.width() - osd.width()) / 2) osd.setY(area.y() + (area.height() - osd.height()) / 2) osd.showTips() osd.closed.connect(_osdClosed)
def __init__(self, **kwargs): if sys.platform == "win32": if hasattr(sys, "frozen"): QCoreApplication.addLibraryPath(os.path.join(os.path.abspath(os.path.dirname(sys.executable)), "PyQt5", "plugins")) else: import site for dir in site.getsitepackages(): QCoreApplication.addLibraryPath(os.path.join(dir, "PyQt5", "plugins")) super().__init__(sys.argv, **kwargs) self.setApplicationVersion(version) self._engine = QQmlApplicationEngine() self._internationalization = Internationalization() self._theme = Theme() self._printerConnectionManager = PrinterConnectionManager()
def main(argv): signal.signal(signal.SIGINT, signal.SIG_DFL) qapp = QGuiApplication([]) engine = QQmlApplicationEngine() data_list = [] for entry in os.scandir(argv[1]): url = "file://" + urllib.parse.quote(os.path.abspath(entry.path)) digest = hashlib.md5(os.fsencode(url)).hexdigest() result = os.path.join(xdg.BaseDirectory.xdg_cache_home, "thumbnails", "normal", digest + ".png") data_list.append(Foo(entry.name, result, "2018-01-11T19:20")) engine.load(QUrl('main.qml')) ctxt = engine.rootContext() ctxt.setContextProperty("menu2", QVariant(data_list)) win = engine.rootObjects()[0] win.show() sys.exit(qapp.exec())
def __init__(self, qml): super().__init__(sys.argv) ''' Register our Python models (classes/types to be registered with QML.) ''' model = QmlModel() model.register() self.qmlMaster = QmlMaster() engine = QQmlApplicationEngine() ''' Need this if no stdio, i.e. Android, OSX, iOS. OW, qWarnings to stdio. engine.warnings.connect(self.errors) ''' engine.load(resourceMgr.urlToQMLResource(resourceSubpath=qml)) engine.quit.connect(self.quit) " Keep reference to engine, used by root() " self.engine = engine ''' Window is shown by default. window = self.getWindow() window.show() ''' ''' Suggested architecture is for model layer (Python) not to know of UI layer, and thus not make connections. The model layer can emit signals to UI layer and vice versa, but only the UI layer knows what connections to make ''' self.makeConnections()
class PixelWall(QApplication): def __init__(self, *args, **kwargs): super(PixelWall, self).__init__(*args, **kwargs) self.engine = QQmlApplicationEngine(self) self.servers = ServerModel(self.engine) self.settings = QSettings('OpenServices', 'PixelWall') url = self.settings.value('server/url') self.engine.setNetworkAccessManagerFactory(NetworkAccessManagerFactory('hetzner.fladi.at', 3128)) ctxt = self.engine.rootContext() ctxt.setContextProperty('app', self) ctxt.setContextProperty('url', 'about:blank') self.engine.load(QUrl('states.qml')) discoverer = Avahi(self.engine, '_pixelwall._tcp') discoverer.initialized.connect(self.serverState) discoverer.added.connect(self.servers.addService) ctxt.setContextProperty('serverModel', self.servers) discoverer.run() if url: self.setUrl(url) self.setState('Web') def setState(self, state): for root in self.engine.rootObjects(): node = root.findChild(QObject, 'main') if node: logger.info('Setting state: {}'.format(state)) node.setProperty('state', state) def setUrl(self, url): logger.info('Connecting WebView to {}'.format(url)) ctxt = self.engine.rootContext() ctxt.setContextProperty('url', 'https://www.heise.de/') @pyqtSlot() def reset(self): self.settings.remove('server/url') self.setState('Servers') @pyqtSlot(int) def serverSelected(self, index): server = self.servers.getIndex(index) logger.info('Server selected {}'.format(server)) url = 'https://{server.host}:{server.port}/'.format(server=server) self.settings.setValue('server/url', url) self.setUrl(url) self.setState('Web') @pyqtSlot() def serverState(self): self.setState('Servers')
def __init__(self): super().__init__() self.fsm = QStateMachine() self.qmlEngine = QQmlApplicationEngine() self.qmlEngine.addImportPath("qml") self.qmlEngine.addImportPath("lib") self.qmlEngine.load(QUrl('qrc:/qml/main.qml')) self.rootObject = self.qmlEngine.rootObjects()[0] self.rootObject.comPortOpened.connect(self.sigComPortOpened) self.rootObject.comPortClosed.connect(self.sigComPortClosed) self.rootObject.powerOn.connect(self.sigPowerOn) self.rootObject.powerOff.connect(self.sigPowerOff) self.createState() pass
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)
def run(self): self._internationalization.load(locale.getdefaultlocale()[0]) self._theme.load(SmartControlApplication.DEFAULT_THEME) self._printerConnectionManager.start() self.aboutToQuit.connect(self._onClose) self.setWindowIcon(QIcon(Resources.icon(SmartControlApplication.WINDOW_ICON))) Binder(self._internationalization, self._theme, self._printerConnectionManager).register() self._engine = QQmlApplicationEngine() if sys.platform == "win32": self._engine.addImportPath(os.path.join(os.path.abspath(os.path.dirname(sys.executable)), "qml")) self._engine.load(Resources.qml(SmartControlApplication.MAIN_QML)) sys.exit(self.exec_())
def __init__(self, argv): super(Application, self).__init__(argv) stderrHandler = logging.StreamHandler(stream=sys.stderr) stderrHandler.setLevel(logging.WARN) stdoutHandler = logging.StreamHandler(stream=sys.stdout) stdoutHandler.setLevel(logging.INFO) stdoutHandler.filter = lambda rec: rec.levelno <= stdoutHandler.level logging.basicConfig( format='%(name)-15s %(message)s', level=logging.INFO, handlers=[stderrHandler, stdoutHandler] ) logger.info("__init__") self._qml_engine = QQmlApplicationEngine() self._root_context = self._qml_engine.rootContext() self.char = Character(self)
def __init__(self, parent=None): super().__init__(parent) self.model = MainWindowViewModel(self) self.loginModel = LoginViewModel(self) self.engine = QQmlApplicationEngine(self) self.engine.rootContext().setContextProperty('model', self.model) self.engine.rootContext().setContextProperty('loginModel', self.loginModel) self.engine.quit.connect(parent.quit) self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml')) self.window = self.engine.rootObjects()[0] # wire up logging console self.log = self.window.findChild(QQuickItem, 'log') parent.log_changed.connect(self._log)
def initializeEngine(self): # TODO: Document native/qml import trickery Bindings.register() self._engine = QQmlApplicationEngine() for path in self._qml_import_paths: self._engine.addImportPath(path) if not hasattr(sys, "frozen"): self._engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml")) self._engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR) self.registerObjects(self._engine) self._engine.load(self._main_qml) self.engineCreatedSignal.emit()
class QtApplication(QApplication, Application): pluginsLoaded = Signal() applicationRunning = Signal() def __init__(self, tray_icon_name=None, **kwargs): plugin_path = "" if sys.platform == "win32": if hasattr(sys, "frozen"): 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) else: import site for sitepackage_dir in site.getsitepackages(): QCoreApplication.addLibraryPath( os.path.join(sitepackage_dir, "PyQt5", "plugins")) 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.setStyle("fusion") self.setAttribute(Qt.AA_UseDesktopOpenGL) major_version, minor_version, profile = OpenGLContext.detectBestOpenGLVersion( ) if major_version is None and minor_version is None and profile is None: Logger.log( "e", "Startup failed because OpenGL version probing has failed: tried to create a 2.0 and 4.1 context. Exiting" ) QMessageBox.critical( None, "Failed to probe OpenGL", "Could not probe OpenGL. This program requires OpenGL 2.0 or higher. Please check your video card drivers." ) sys.exit(1) else: Logger.log( "d", "Detected most suitable OpenGL context version: %s" % (OpenGLContext.versionAsText(major_version, minor_version, profile))) OpenGLContext.setDefaultFormat(major_version, minor_version, profile=profile) self._plugins_loaded = False # Used to determine when it's safe to use the plug-ins. self._main_qml = "main.qml" self._engine = None self._renderer = None self._main_window = None self._theme = None self._shutting_down = False self._qml_import_paths = [] self._qml_import_paths.append( os.path.join(os.path.dirname(sys.executable), "qml")) self._qml_import_paths.append( os.path.join(Application.getInstallPrefix(), "Resources", "qml")) self.parseCommandLine() Logger.log("i", "Command line arguments: %s", self._parsed_command_line) self._splash = None 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("@info:progress", "Loading plugins...")) self._loadPlugins() self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) self.pluginsLoaded.emit() self.showSplashMessage( i18n_catalog.i18nc("@info:progress", "Updating configuration...")) upgraded = UM.VersionUpgradeManager.VersionUpgradeManager.getInstance( ).upgrade() if upgraded: # Preferences might have changed. Load them again. # Note that the language can't be updated, so that will always revert to English. preferences = Preferences.getInstance() try: preferences.readFromFile( Resources.getPath(Resources.Preferences, self._application_name + ".cfg")) except FileNotFoundError: pass self.showSplashMessage( i18n_catalog.i18nc("@info:progress", "Loading preferences...")) try: file_name = Resources.getPath(Resources.Preferences, self.getApplicationName() + ".cfg") Preferences.getInstance().readFromFile(file_name) except FileNotFoundError: pass self.getApplicationName() Preferences.getInstance().addPreference( "%s/recent_files" % self.getApplicationName(), "") self._recent_files = [] file_names = Preferences.getInstance().getValue( "%s/recent_files" % self.getApplicationName()).split(";") for file_name in file_names: if not os.path.isfile(file_name): continue self._recent_files.append(QUrl.fromLocalFile(file_name)) JobQueue.getInstance().jobFinished.connect(self._onJobFinished) # Initialize System tray icon and make it invisible because it is used only to show pop up messages self._tray_icon = None self._tray_icon_widget = None if tray_icon_name: self._tray_icon = QIcon( Resources.getPath(Resources.Images, tray_icon_name)) self._tray_icon_widget = QSystemTrayIcon(self._tray_icon) self._tray_icon_widget.setVisible(False) recentFilesChanged = pyqtSignal() @pyqtProperty("QVariantList", notify=recentFilesChanged) def recentFiles(self): return self._recent_files def _onJobFinished(self, job): if (not isinstance(job, ReadMeshJob) and not isinstance(job, ReadFileJob)) or not job.getResult(): return f = QUrl.fromLocalFile(job.getFileName()) if f in self._recent_files: self._recent_files.remove(f) self._recent_files.insert(0, f) if len(self._recent_files) > 10: del self._recent_files[10] pref = "" for path in self._recent_files: pref += path.toLocalFile() + ";" Preferences.getInstance().setValue( "%s/recent_files" % self.getApplicationName(), pref) self.recentFilesChanged.emit() 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.setLifetimeTimer(QTimer()) message.setInactivityTimer(QTimer()) self.visibleMessageAdded.emit(message) # also show toast message when the main window is minimized self.showToastMessage(self._application_name, message.getText()) def _onMainWindowStateChanged(self, window_state): if self._tray_icon: visible = window_state == Qt.WindowMinimized self._tray_icon_widget.setVisible(visible) # Show toast message using System tray widget. def showToastMessage(self, title: str, message: str): if self.checkWindowMinimizedState() and self._tray_icon_widget: # NOTE: Qt 5.8 don't support custom icon for the system tray messages, but Qt 5.9 does. # We should use the custom icon when we switch to Qt 5.9 self._tray_icon_widget.showMessage(title, message) def setMainQml(self, path): self._main_qml = path def initializeEngine(self): # TODO: Document native/qml import trickery Bindings.register() self._engine = QQmlApplicationEngine() self._engine.setOutputWarningsToStandardError(False) self._engine.warnings.connect(self.__onQmlWarning) for path in self._qml_import_paths: self._engine.addImportPath(path) if not hasattr(sys, "frozen"): self._engine.addImportPath( os.path.join(os.path.dirname(__file__), "qml")) self._engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR) self._engine.rootContext().setContextProperty( "screenScaleFactor", self._screenScaleFactor()) self.registerObjects(self._engine) self._engine.load(self._main_qml) self.engineCreatedSignal.emit() def exec_(self, *args, **kwargs): self.applicationRunning.emit() super().exec_(*args, **kwargs) @pyqtSlot() def reloadQML(self): # only reload when it is a release build if not self.getIsDebugMode(): return self._engine.clearComponentCache() self._theme.reload() self._engine.load(self._main_qml) # Hide the window. For some reason we can't close it yet. This needs to be done in the onComponentCompleted. for obj in self._engine.rootObjects(): if obj != self._engine.rootObjects()[-1]: obj.hide() @pyqtSlot() def purgeWindows(self): # Close all root objects except the last one. # Should only be called by onComponentCompleted of the mainWindow. for obj in self._engine.rootObjects(): if obj != self._engine.rootObjects()[-1]: obj.close() @pyqtSlot("QList<QQmlError>") def __onQmlWarning(self, warnings): for warning in warnings: Logger.log("w", warning.toString()) engineCreatedSignal = Signal() def isShuttingDown(self): return self._shutting_down def registerObjects(self, engine): engine.rootContext().setContextProperty("PluginRegistry", PluginRegistry.getInstance()) def getRenderer(self): if not self._renderer: self._renderer = QtRenderer() return self._renderer @classmethod def addCommandLineOptions(self, parser, parsed_command_line={}): super().addCommandLineOptions(parser, parsed_command_line=parsed_command_line) parser.add_argument( "--disable-textures", dest="disable-textures", action="store_true", default=False, help= "Disable Qt texture loading as a workaround for certain crashes.") parser.add_argument("-qmljsdebugger", help="For Qt's QML debugger compatibility") mainWindowChanged = Signal() def getMainWindow(self): return self._main_window def getSplashScreen(self): if not self._splash: self.createSplash() return self._splash def setMainWindow(self, window): if window != self._main_window: if self._main_window is not None: self._main_window.windowStateChanged.disconnect( self._onMainWindowStateChanged) self._main_window = window if self._main_window is not None: self._main_window.windowStateChanged.connect( self._onMainWindowStateChanged) self.mainWindowChanged.emit() def setVisible(self, visible): if self._engine is None: self.initializeEngine() if self._main_window is not None: self._main_window.visible = visible @property def isVisible(self): if self._main_window is not None: return self._main_window.visible def getTheme(self): if self._theme is None: if self._engine is None: Logger.log( "e", "The theme cannot be accessed before the engine is initialised" ) return None self._theme = UM.Qt.Bindings.Theme.Theme.getInstance(self._engine) return self._theme # 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): Logger.log("d", "Shutting down %s", self.getApplicationName()) self._shutting_down = True try: Preferences.getInstance().writeToFile( Resources.getStoragePath(Resources.Preferences, self.getApplicationName() + ".cfg")) except Exception as e: Logger.log("e", "Exception while saving preferences: %s", repr(e)) try: self.applicationShuttingDown.emit() except Exception as e: Logger.log("e", "Exception while emitting shutdown signal: %s", repr(e)) try: self.getBackend().close() except Exception as e: Logger.log("e", "Exception while closing backend: %s", repr(e)) self.quit() def checkWindowMinimizedState(self): if self._main_window is not None and self._main_window.windowState( ) == Qt.WindowMinimized: return True else: return False ## Get the backend of the application (the program that does the heavy lifting). # The backend is also a QObject, which can be used from qml. # \returns Backend \type{Backend} @pyqtSlot(result="QObject*") def getBackend(self): return self._backend ## Property used to expose the backend # It is made static as the backend is not supposed to change during runtime. # This makes the connection between backend and QML more reliable than the pyqtSlot above. # \returns Backend \type{Backend} @pyqtProperty("QVariant", constant=True) def backend(self): return self.getBackend() ## 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_name 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_name, language="default"): # TODO Add support for specifying a language from preferences path = None if language == "default": path = self._getDefaultLanguage(file_name) else: path = Resources.getPath(Resources.i18n, language, "LC_MESSAGES", file_name + ".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_name)) try: path = Resources.getPath(Resources.i18n, "en_US", "LC_MESSAGES", file_name + ".qm") except FileNotFoundError: Logger.log( "w", "Could not find English translations for file {0}. Switching to developer english." .format(file_name)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file_name) 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_name] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator) def createSplash(self): if not self.getCommandLineOption("headless"): try: self._splash = self._createSplashScreen() except FileNotFoundError: self._splash = None else: if self._splash: self._splash.show() self.processEvents() ## Display text on the splash screen. def showSplashMessage(self, message): if not self._splash: self.createSplash() if self._splash: self._splash.showMessage(message, Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() elif self.getCommandLineOption("headless"): Logger.log("d", message) ## Close the splash screen after the application has started. def closeSplash(self): if self._splash: self._splash.close() self._splash = None ## Create a QML component from a qml file. # \param qml_file_path: The absolute file path to the root qml file. # \param context_properties: Optional dictionary containing the properties that will be set on the context of the # qml instance before creation. # \return None in case the creation failed (qml error), else it returns the qml instance. # \note If the creation fails, this function will ensure any errors are logged to the logging service. def createQmlComponent( self, qml_file_path: str, context_properties: Dict[str, "QObject"] = None) -> Optional["QObject"]: path = QUrl.fromLocalFile(qml_file_path) component = QQmlComponent(self._engine, path) result_context = QQmlContext(self._engine.rootContext()) if context_properties is not None: for name, value in context_properties.items(): result_context.setContextProperty(name, value) result = component.create(result_context) for err in component.errors(): Logger.log("e", str(err.toString())) if result is None: return None # We need to store the context with the qml object, else the context gets garbage collected and the qml objects # no longer function correctly/application crashes. result.attached_context = result_context return result def _createSplashScreen(self): return QSplashScreen( QPixmap( Resources.getPath(Resources.Images, self.getApplicationName() + ".png"))) def _screenScaleFactor(self): # OSX handles sizes of dialogs behind our backs, but other platforms need # to know about the device pixel ratio if sys.platform == "darwin": return 1.0 else: # determine a device pixel ratio from font metrics, using the same logic as UM.Theme fontPixelRatio = QFontMetrics( QCoreApplication.instance().font()).ascent() / 11 # round the font pixel ratio to quarters fontPixelRatio = int(fontPixelRatio * 4) / 4 return fontPixelRatio def _getDefaultLanguage(self, file_name): # If we have a language override set in the environment, try and use that. lang = os.getenv("URANIUM_LANGUAGE") if lang: try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file_name + ".qm") except FileNotFoundError: pass # Else, try and get the current language from preferences lang = Preferences.getInstance().getValue("general/language") if lang: try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file_name + ".qm") except FileNotFoundError: pass # If none of those are set, try to use the environment's LANGUAGE variable. lang = os.getenv("LANGUAGE") if lang: try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file_name + ".qm") except FileNotFoundError: pass # If looking up the language from the enviroment or preferences fails, try and use Qt's system locale instead. locale = QLocale.system() # First, try and find a directory for any of the provided languages for lang in locale.uiLanguages(): try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file_name + ".qm") except FileNotFoundError: pass # If that fails, see if we can extract a language code from the # preferred language, regardless of the country code. This will turn # "en-GB" into "en" for example. lang = locale.uiLanguages()[0] lang = lang[0:lang.find("-")] for subdirectory in os.path.listdir(Resources.getPath(Resources.i18n)): if subdirectory == "en_7S": #Never automatically go to Pirate. continue if not os.path.isdir( Resources.getPath(Resources.i18n, subdirectory)): continue if subdirectory.startswith( lang + "_"): #Only match the language code, not the country code. return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file_name + ".qm") return None def preventComputerFromSleeping(self, prevent): """ Function used to prevent the computer from going into sleep mode. :param prevent: True = Prevent the system from going to sleep from this point on. :param prevent: False = No longer prevent the system from going to sleep. """ Logger.log("d", "Prevent computer from sleeping? " + str(prevent)) if sys.platform.startswith('win'): # Windows try: ES_CONTINUOUS = 0x80000000 ES_SYSTEM_REQUIRED = 0x00000001 ES_AWAYMODE_REQUIRED = 0x00000040 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up. if prevent: # For Vista and up we use ES_AWAYMODE_REQUIRED to prevent a print from failing if the PC does go to sleep # As it's not supported on XP, we catch the error and fallback to using ES_SYSTEM_REQUIRED only if ctypes.windll.kernel32.SetThreadExecutionState( ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == 0: ctypes.windll.kernel32.SetThreadExecutionState( ES_CONTINUOUS | ES_SYSTEM_REQUIRED) else: ctypes.windll.kernel32.SetThreadExecutionState( ES_CONTINUOUS) except: Logger.log("w", "Failed to prevent from sleeping") pass elif sys.platform.startswith('darwin'): # Mac OS import os import subprocess try: if prevent: subprocess.Popen( ['caffeinate', '-i', '-w', str(os.getpid())]) except: Logger.log("w", "Failed to prevent from sleeping") pass else: # Linux import os import subprocess try: id = self.getMainWindow().winId() if os.path.isfile("/usr/bin/xdg-screensaver"): try: cmd = [ 'xdg-screensaver', 'suspend' if prevent else 'resume', str(int(id)) ] subprocess.call(cmd) except: Logger.log( "w", "Call to /usr/bin/xdg-screensaver failed, unable to prevent sleep" ) pass else: Logger.log( "w", "No /usr/bin/xdg-screensaver found, unable to prevent sleep" ) except: Logger.log("w", "Failed to prevent from sleeping") pass
def __init__(self): QObject.__init__(self) updCanv = pyqtSignal(list, arguments=['upd']) @pyqtSlot(float, float, str) def upd(self, left_bound, right_bound, func): if func in ('cos', 'sin', 'tan'): points = generate_points(left_bound, right_bound, eval(f"math.{func}")) if func == 'sqrt': if left_bound >= 0: points = generate_points(left_bound, right_bound, math.sqrt) else: points = [] if func == 'x^2': points = generate_points(left_bound, right_bound, lambda x: x * x) self.updCanv.emit(points) if __name__ == "__main__": sys.argv += ['--style', 'material'] app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() plot = Plot() engine.rootContext().setContextProperty("plot", plot) engine.load("main.qml") engine.quit.connect(app.quit) sys.exit(app.exec_())
self.updated.emit(curr_time) def bootUp(self): t_thread = threading.Thread(target=self._bootUp) t_thread.daemon = True t_thread.start() def _bootUp(self): while True: curr_time = strftime("%H:%M:%S", localtime()) self.updater(curr_time) sleep(0.1) # print(curr_time) # sleep(1) curr_time = strftime("%H:%M:%S", gmtime()) app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.quit.connect(app.quit) engine.load('main.qml') engine.rootObjects()[0].setProperty('currTime', curr_time) back_end = Backend() engine.rootObjects()[0].setProperty('backend', back_end) back_end.bootUp() sys.exit(app.exec())
client.subscribe("WindSpeed") #subscribe client.subscribe("WindBox") #subscribe print("Box Wind subscribed ") client.publish("MainControl", "active") #publish ## QT5 GUI print("Graphical User Interface ") app = QGuiApplication(sys.argv) view = QQuickView() view.setSource(QUrl('main.qml')) mqttvalue = MQTTValue() timer = QTimer() timer.start(10) ##Update screen every 10 miliseconds context = view.rootContext() context.setContextProperty("mqttvalue", mqttvalue) root = view.rootObject() timer.timeout.connect(root.updateValue) ##Call function update in GUI QML engine = QQmlApplicationEngine(app) engine.quit.connect(app.quit) ## Quit Button Respon view.showFullScreen() sys.exit(app.exec_())
def start_gui(): parser = argparse.ArgumentParser( description= 'SmallSOCC v{!s} - Frontend for interfacing with SOC hardware'.format( VERSION_FULL), formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-L', '--loglevel', type=str, choices=[*logging._nameToLevel.keys()], default='WARNING', help='set the loglevel') parser.add_argument('--logconf', type=str, default=os.path.join(LIB_DIR, 'logging.conf.json'), help='path to log configuration') args = parser.parse_args() # initialize logger soclog.init_logging(level=logging._nameToLevel.get(args.loglevel, None), config_path=args.logconf) listmodel = sequence.SequenceListModel() if args.loglevel is not 'NOTSET' and logging._nameToLevel[ args.loglevel] <= logging.DEBUG: # load example sequence, for rapid debugging try: listmodel = sequence.SequenceListModel.fromJson( os.path.join(TEST_FILES, 'test_output.json')) except Exception as e: logger.warning('FAILED TO READ DEBUG JSON FILE : {!s}'.format(e)) # SAMPLE ITEMS FOR DEBUG from sequence import SequenceItem, SequenceItemType sample_sequenceitems = [ SequenceItem(rot_couch_deg=5, rot_gantry_deg=0, timecode_ms=0, datecreatedstr="2016 Oct 31 12:00:00", type='Manual'), SequenceItem(rot_couch_deg=12, rot_gantry_deg=120, timecode_ms=1500, description="descriptive text2", type=SequenceItemType.Auto), SequenceItem(rot_couch_deg=24, rot_gantry_deg=25, timecode_ms=3000, description="descriptive text3"), SequenceItem(rot_couch_deg=0, rot_gantry_deg=45, timecode_ms=4500, description="descriptive text4"), ] listmodel = sequence.SequenceListModel( elements=sample_sequenceitems) HWSOC(8, HID=None) # init singleton instance for controlling hardware # integrate qml logging with python logging QtCore.qInstallMessageHandler(qt_message_handler) # prevent qml caching os.environ['QML_DISABLE_DISK_CACHE'] = '1' # set QML visual style app = QGuiApplication(sys.argv + ['-style', 'default']) # app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) # register pre-exit hook app.aboutToQuit.connect(preExit) # perform cleanup ### the order here matters greatly - must init context properties before loading main.qml engine = QQmlApplicationEngine() rootContext = engine.rootContext() ## compute scaling ratios to make views dpi-independent if logger.getEffectiveLevel() <= logging.DEBUG: screens = app.screens() for sidx, screen in enumerate(screens): geometry = screen.geometry() dpi = screen.logicalDotsPerInch() logger.debug( 'Screen #{} ({}) - size: (w:{}, h:{}); DPI: {}'.format( sidx, screen.name(), geometry.width(), geometry.height(), dpi)) screen = app.primaryScreen() geometry = screen.geometry() dpi = screen.logicalDotsPerInch() refDpi = 96 refHeight = 1440 refWidth = 2560 _h = min(geometry.width(), geometry.height()) _w = max(geometry.width(), geometry.height()) sratio = min(_h / refHeight, _w / refWidth) # element size scaling fratio = min(_h * refDpi / (dpi * refHeight), _w * refDpi / (dpi * refWidth)) # font pointSize scaling logger.debug('Setting scaling ratios - general: {}; font: {}'.format( sratio, fratio)) ## Set accessible properties/objects in QML Root Context rootContext.setContextProperty( "mainwindow_title", 'SOC Controller - {!s}'.format(VERSION_FULL)) # make seq. list model accessible to qml-listview rootContext.setContextProperty("SequenceListModel", listmodel) pathhandler_instance = pathhandler.PathHandler() rootContext.setContextProperty("PathHandler", pathhandler_instance) rootContext.setContextProperty("sratio", sratio) rootContext.setContextProperty("fratio", fratio) # load layout engine.load(QtCore.QUrl(os.path.join(dirname(__file__), 'main.qml'))) ## connect signals to slots - unnecessary, example of grabbing qml objects from py-code # listview buttons # rootObject = engine.rootObjects()[0] # btns = rootObject.findChildren(QQuickItem, "list_buttons", QtCore.Qt.FindChildrenRecursively)[0] # btns.findChild(QQuickItem, 'btn_moveup').clicked.connect(lambda: print('moveup clicked')) return app.exec_()
context = engine.rootContext() context.setContextProperty("con", bridge) # Get the path of the current directory, and then add the name # of the QML file, to load it. qmlFile = join(dirname(__file__), 'dash_v9.qml') #qmlFile = join(dirname(__file__), 'stck.qml') engine.load(abspath(qmlFile)) sys.exit(app.exec_()) if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() # Instance of the Python object bridge = Bridge() # Expose the Python object to QML context = engine.rootContext() context.setContextProperty("con", bridge) # Get the path of the current directory, and then add the name # of the QML file, to load it. qmlFile = join(dirname(__file__), 'dash_v9.qml') # qmlFile = join(dirname(__file__), 'stck.qml') engine.load(abspath(qmlFile)) sys.exit(app.exec_())
@pyqtProperty("QVariantMap", notify=metaDataChanged) def metaData(self): return self._metadata @pyqtProperty(str, notify=loaded) def definitionId(self): return self._definition_id signal.signal(signal.SIGINT, signal.SIG_DFL) file_name = None if len(sys.argv) > 1: file_name = sys.argv[1] del sys.argv[1] app = QApplication(sys.argv) engine = QQmlApplicationEngine() qmlRegisterType(DefinitionLoader, "Example", 1, 0, "DefinitionLoader") qmlRegisterType(DefinitionTreeModel.DefinitionTreeModel, "Example", 1, 0, "DefinitionTreeModel") if file_name: engine.rootContext().setContextProperty("open_file", QUrl.fromLocalFile(file_name)) engine.load( os.path.join(os.path.dirname(os.path.abspath(__file__)), "main.qml")) app.exec_()
from time import sleep import os from PyQt5.QtCore import QUrl, QObject from PyQt5.QtGui import QGuiApplication from PyQt5.QtQuick import QQuickItem from PyQt5.QtQml import qmlRegisterType, QQmlComponent, QQmlApplicationEngine, QQmlEngine, QQmlPropertyMap import soloman app = QGuiApplication(sys.argv) # Create a QML engine. #register() engine = QQmlApplicationEngine() engine.quit.connect(app.quit) engine.load(QUrl('tests/exampl.qml')) sol = soloman.Video(engine) sol.get_SVideo('lover') vid = soloman.Video(engine) vid.get_SVideo('love') # Capture source = "ex/countdown640.mp4" capture = cv2.VideoCapture(source) cap = cv2.VideoCapture(0) fgbg = cv2.createBackgroundSubtractorMOG2(50, 200, True)
import sys from PyQt5.QtCore import QObject, QUrl, pyqtSlot from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine, QQmlComponent, QQmlContext from SignalHandler import SignalHandler if __name__ == "__main__": app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() configurator = SignalHandler() engine.load("qml/SimpleMainWindow.qml") engine.quit.connect(app.quit) rootWindow = engine.rootObjects()[0] content_item = rootWindow.property("contentItem") context = QQmlContext(engine) component = QQmlComponent(engine) component.loadUrl(QUrl("qml/TestViewButton.qml")) itm = component.create(context) context.setContextProperty("configurator", configurator) itm.setProperty("parent", content_item) sys.exit(app.exec_())
from PyQt5.QtCore import QUrl import numpy as np import cv2 import utils.fp as fp import utils.futils as fu import gui import state import consts consts.load_config() import core import imgio as io app = QApplication(sys.argv) main_window = gui.MainWindow( QQmlApplicationEngine() ) @pytest.fixture def clear_state(): state.clear_all() def fpath(*ps): return str(PurePosixPath(*ps)) def posix_abspath(path): abspath = os.path.abspath(path) return(abspath.replace('\\','/') if '\\' in abspath else abspath) def open_project(prjdir): abspath = os.path.abspath(prjdir)
class QtApplication(QApplication, Application): pluginsLoaded = Signal() applicationRunning = Signal() def __init__(self, tray_icon_name: str = None, **kwargs) -> None: plugin_path = "" if sys.platform == "win32": if hasattr(sys, "frozen"): 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) else: import site for sitepackage_dir in site.getsitepackages(): QCoreApplication.addLibraryPath( os.path.join(sitepackage_dir, "PyQt5", "plugins")) elif sys.platform == "darwin": plugin_path = os.path.join(self.getInstallPrefix(), "Resources", "plugins") if plugin_path: Logger.log("i", "Adding QT5 plugin path: %s", plugin_path) QCoreApplication.addLibraryPath(plugin_path) # use Qt Quick Scene Graph "basic" render loop os.environ["QSG_RENDER_LOOP"] = "basic" super().__init__(sys.argv, **kwargs) # type: ignore self._qml_import_paths = [] #type: List[str] self._main_qml = "main.qml" #type: str self._qml_engine = None #type: Optional[QQmlApplicationEngine] self._main_window = None #type: Optional[MainWindow] self._tray_icon_name = tray_icon_name #type: Optional[str] self._tray_icon = None #type: Optional[str] self._tray_icon_widget = None #type: Optional[QSystemTrayIcon] self._theme = None #type: Optional[Theme] self._renderer = None #type: Optional[QtRenderer] self._job_queue = None #type: Optional[JobQueue] self._version_upgrade_manager = None #type: Optional[VersionUpgradeManager] self._is_shutting_down = False #type: bool self._recent_files = [] #type: List[QUrl] self._configuration_error_message = None #type: Optional[ConfigurationErrorMessage] def addCommandLineOptions(self) -> None: super().addCommandLineOptions() # This flag is used by QApplication. We don't process it. self._cli_parser.add_argument( "-qmljsdebugger", help="For Qt's QML debugger compatibility") def initialize(self) -> None: super().initialize() self._mesh_file_handler = MeshFileHandler(self) #type: MeshFileHandler self._workspace_file_handler = WorkspaceFileHandler( self) #type: WorkspaceFileHandler # Remove this and you will get Windows 95 style for all widgets if you are using Qt 5.10+ self.setStyle("fusion") self.setAttribute(Qt.AA_UseDesktopOpenGL) major_version, minor_version, profile = OpenGLContext.detectBestOpenGLVersion( ) if major_version is None and minor_version is None and profile is None and not self.getIsHeadLess( ): Logger.log( "e", "Startup failed because OpenGL version probing has failed: tried to create a 2.0 and 4.1 context. Exiting" ) QMessageBox.critical( None, "Failed to probe OpenGL", "Could not probe OpenGL. This program requires OpenGL 2.0 or higher. Please check your video card drivers." ) sys.exit(1) else: opengl_version_str = OpenGLContext.versionAsText( major_version, minor_version, profile) Logger.log("d", "Detected most suitable OpenGL context version: %s", opengl_version_str) if not self.getIsHeadLess(): OpenGLContext.setDefaultFormat(major_version, minor_version, profile=profile) self._qml_import_paths.append( os.path.join(os.path.dirname(sys.executable), "qml")) self._qml_import_paths.append( os.path.join(self.getInstallPrefix(), "Resources", "qml")) Logger.log("i", "Initializing job queue ...") self._job_queue = JobQueue() self._job_queue.jobFinished.connect(self._onJobFinished) Logger.log("i", "Initializing version upgrade manager ...") self._version_upgrade_manager = VersionUpgradeManager(self) def startSplashWindowPhase(self) -> None: super().startSplashWindowPhase() self._package_manager.initialize() # Read preferences here (upgrade won't work) to get the language in use, so the splash window can be shown in # the correct language. try: preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg") self._preferences.readFromFile(preferences_filename) except FileNotFoundError: Logger.log( "i", "Preferences file not found, ignore and use default language '%s'", self._default_language) 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._configuration_error_message = ConfigurationErrorMessage( self, i18n_catalog.i18nc("@info:status", "Your configuration seems to be corrupt."), lifetime=0, title=i18n_catalog.i18nc("@info:title", "Configuration errors")) # Remove, install, and then loading plugins self.showSplashMessage( i18n_catalog.i18nc("@info:progress", "Loading plugins...")) # Remove and install the plugins that have been scheduled self._plugin_registry.initializeBeforePluginsAreLoaded() self._loadPlugins() self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) self.pluginsLoaded.emit() self.showSplashMessage( i18n_catalog.i18nc("@info:progress", "Updating configuration...")) with self._container_registry.lockFile(): VersionUpgradeManager.getInstance().upgrade() # Load preferences again because before we have loaded the plugins, we don't have the upgrade routine for # the preferences file. Now that we have, load the preferences file again so it can be upgraded and loaded. try: preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg") with open(preferences_filename, "r", encoding="utf-8") as f: serialized = f.read() # This performs the upgrade for Preferences self._preferences.deserialize(serialized) self._preferences.setValue("general/plugins_to_remove", "") self._preferences.writeToFile(preferences_filename) except FileNotFoundError: Logger.log( "i", "The preferences file cannot be found, will use default values" ) # Force the configuration file to be written again since the list of plugins to remove maybe changed self.showSplashMessage( i18n_catalog.i18nc("@info:progress", "Loading preferences...")) try: self._preferences_filename = Resources.getPath( Resources.Preferences, self._app_name + ".cfg") self._preferences.readFromFile(self._preferences_filename) except FileNotFoundError: Logger.log( "i", "The preferences file '%s' cannot be found, will use default values", self._preferences_filename) self._preferences_filename = Resources.getStoragePath( Resources.Preferences, self._app_name + ".cfg") # FIXME: This is done here because we now use "plugins.json" to manage plugins instead of the Preferences file, # but the PluginRegistry will still import data from the Preferences files if present, such as disabled plugins, # so we need to reset those values AFTER the Preferences file is loaded. self._plugin_registry.initializeAfterPluginsAreLoaded() # Preferences: recent files self._preferences.addPreference("%s/recent_files" % self._app_name, "") file_names = self._preferences.getValue("%s/recent_files" % self._app_name).split(";") for file_name in file_names: if not os.path.isfile(file_name): continue self._recent_files.append(QUrl.fromLocalFile(file_name)) if not self.getIsHeadLess(): # Initialize System tray icon and make it invisible because it is used only to show pop up messages self._tray_icon = None if self._tray_icon_name: self._tray_icon = QIcon( Resources.getPath(Resources.Images, self._tray_icon_name)) self._tray_icon_widget = QSystemTrayIcon(self._tray_icon) self._tray_icon_widget.setVisible(False) def initializeEngine(self) -> None: # TODO: Document native/qml import trickery self._qml_engine = QQmlApplicationEngine(self) self._qml_engine.setOutputWarningsToStandardError(False) self._qml_engine.warnings.connect(self.__onQmlWarning) for path in self._qml_import_paths: self._qml_engine.addImportPath(path) if not hasattr(sys, "frozen"): self._qml_engine.addImportPath( os.path.join(os.path.dirname(__file__), "qml")) self._qml_engine.rootContext().setContextProperty( "QT_VERSION_STR", QT_VERSION_STR) self._qml_engine.rootContext().setContextProperty( "screenScaleFactor", self._screenScaleFactor()) self.registerObjects(self._qml_engine) Bindings.register() self._qml_engine.load(self._main_qml) self.engineCreatedSignal.emit() recentFilesChanged = pyqtSignal() @pyqtProperty("QVariantList", notify=recentFilesChanged) def recentFiles(self) -> List[QUrl]: return self._recent_files def _onJobFinished(self, job: Job) -> None: if isinstance(job, WriteFileJob): if not job.getResult() or not job.getAddToRecentFiles(): # For a write file job, if it failed or it doesn't need to be added to the recent files list, we do not # add it. return elif (not isinstance(job, ReadMeshJob) and not isinstance(job, ReadFileJob)) or not job.getResult(): return if isinstance(job, (ReadMeshJob, ReadFileJob, WriteFileJob)): self.addFileToRecentFiles(job.getFileName()) def addFileToRecentFiles(self, file_name: str) -> None: file_path = QUrl.fromLocalFile(file_name) if file_path in self._recent_files: self._recent_files.remove(file_path) self._recent_files.insert(0, file_path) if len(self._recent_files) > 10: del self._recent_files[10] pref = "" for path in self._recent_files: pref += path.toLocalFile() + ";" self.getPreferences().setValue( "%s/recent_files" % self.getApplicationName(), pref) self.recentFilesChanged.emit() def run(self) -> None: super().run() def hideMessage(self, message: Message) -> None: with self._message_lock: if message in self._visible_messages: message.hide( send_signal=False ) # we're in handling hideMessageSignal so we don't want to resend it self._visible_messages.remove(message) self.visibleMessageRemoved.emit(message) def showMessage(self, message: Message) -> None: with self._message_lock: if message not in self._visible_messages: self._visible_messages.append(message) message.setLifetimeTimer(QTimer()) message.setInactivityTimer(QTimer()) self.visibleMessageAdded.emit(message) # also show toast message when the main window is minimized self.showToastMessage(self._app_name, message.getText()) def _onMainWindowStateChanged(self, window_state: int) -> None: if self._tray_icon and self._tray_icon_widget: visible = window_state == Qt.WindowMinimized self._tray_icon_widget.setVisible(visible) # Show toast message using System tray widget. def showToastMessage(self, title: str, message: str) -> None: if self.checkWindowMinimizedState() and self._tray_icon_widget: # NOTE: Qt 5.8 don't support custom icon for the system tray messages, but Qt 5.9 does. # We should use the custom icon when we switch to Qt 5.9 self._tray_icon_widget.showMessage(title, message) def setMainQml(self, path: str) -> None: self._main_qml = path def exec_(self, *args: Any, **kwargs: Any) -> None: self.applicationRunning.emit() super().exec_(*args, **kwargs) @pyqtSlot() def reloadQML(self) -> None: # only reload when it is a release build if not self.getIsDebugMode(): return if self._qml_engine and self._theme: self._qml_engine.clearComponentCache() self._theme.reload() self._qml_engine.load(self._main_qml) # Hide the window. For some reason we can't close it yet. This needs to be done in the onComponentCompleted. for obj in self._qml_engine.rootObjects(): if obj != self._qml_engine.rootObjects()[-1]: obj.hide() @pyqtSlot() def purgeWindows(self) -> None: # Close all root objects except the last one. # Should only be called by onComponentCompleted of the mainWindow. if self._qml_engine: for obj in self._qml_engine.rootObjects(): if obj != self._qml_engine.rootObjects()[-1]: obj.close() @pyqtSlot("QList<QQmlError>") def __onQmlWarning(self, warnings: List[QQmlError]) -> None: for warning in warnings: Logger.log("w", warning.toString()) engineCreatedSignal = Signal() def isShuttingDown(self) -> bool: return self._is_shutting_down def registerObjects( self, engine ) -> None: #type: ignore #Don't type engine, because the type depends on the platform you're running on so it always gives an error somewhere. engine.rootContext().setContextProperty("PluginRegistry", PluginRegistry.getInstance()) def getRenderer(self) -> QtRenderer: if not self._renderer: self._renderer = QtRenderer() return cast(QtRenderer, self._renderer) mainWindowChanged = Signal() def getMainWindow(self) -> Optional[MainWindow]: return self._main_window def setMainWindow(self, window: MainWindow) -> None: if window != self._main_window: if self._main_window is not None: self._main_window.windowStateChanged.disconnect( self._onMainWindowStateChanged) self._main_window = window if self._main_window is not None: self._main_window.windowStateChanged.connect( self._onMainWindowStateChanged) self.mainWindowChanged.emit() def setVisible(self, visible: bool) -> None: if self._main_window is not None: self._main_window.visible = visible @property def isVisible(self) -> bool: if self._main_window is not None: return self._main_window.visible #type: ignore #MyPy doesn't realise that self._main_window cannot be None here. return False def getTheme(self) -> Optional[Theme]: if self._theme is None: if self._qml_engine is None: Logger.log( "e", "The theme cannot be accessed before the engine is initialised" ) return None self._theme = UM.Qt.Bindings.Theme.Theme.getInstance( self._qml_engine) return self._theme # Handle a function that should be called later. def functionEvent(self, event: QEvent) -> None: e = _QtFunctionEvent(event) QCoreApplication.postEvent(self, e) # Handle Qt events def event(self, event: QEvent) -> bool: if event.type() == _QtFunctionEvent.QtFunctionEvent: event._function_event.call() return True return super().event(event) def windowClosed(self, save_data: bool = True) -> None: Logger.log("d", "Shutting down %s", self.getApplicationName()) self._is_shutting_down = True # garbage collect tray icon so it gets properly closed before the application is closed self._tray_icon_widget = None if save_data: try: self.savePreferences() except Exception as e: Logger.log("e", "Exception while saving preferences: %s", repr(e)) try: self.applicationShuttingDown.emit() except Exception as e: Logger.log("e", "Exception while emitting shutdown signal: %s", repr(e)) try: self.getBackend().close() except Exception as e: Logger.log("e", "Exception while closing backend: %s", repr(e)) if self._tray_icon_widget: self._tray_icon_widget.deleteLater() self.quit() def checkWindowMinimizedState(self) -> bool: if self._main_window is not None and self._main_window.windowState( ) == Qt.WindowMinimized: return True else: return False ## Get the backend of the application (the program that does the heavy lifting). # The backend is also a QObject, which can be used from qml. @pyqtSlot(result="QObject*") def getBackend(self) -> Backend: return self._backend ## Property used to expose the backend # It is made static as the backend is not supposed to change during runtime. # This makes the connection between backend and QML more reliable than the pyqtSlot above. # \returns Backend \type{Backend} @pyqtProperty("QVariant", constant=True) def backend(self) -> Backend: return self.getBackend() ## Create a class variable so we can manage the splash in the CrashHandler dialog when the Application instance # is not yet created, e.g. when an error occurs during the initialization splash = None # type: Optional[QSplashScreen] def createSplash(self) -> None: if not self.getIsHeadLess(): try: QtApplication.splash = self._createSplashScreen() except FileNotFoundError: QtApplication.splash = None else: if QtApplication.splash: QtApplication.splash.show() self.processEvents() ## Display text on the splash screen. def showSplashMessage(self, message: str) -> None: if not QtApplication.splash: self.createSplash() if QtApplication.splash: QtApplication.splash.showMessage(message, Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() elif self.getIsHeadLess(): Logger.log("d", message) ## Close the splash screen after the application has started. def closeSplash(self) -> None: if QtApplication.splash: QtApplication.splash.close() QtApplication.splash = None ## Create a QML component from a qml file. # \param qml_file_path: The absolute file path to the root qml file. # \param context_properties: Optional dictionary containing the properties that will be set on the context of the # qml instance before creation. # \return None in case the creation failed (qml error), else it returns the qml instance. # \note If the creation fails, this function will ensure any errors are logged to the logging service. def createQmlComponent( self, qml_file_path: str, context_properties: Dict[str, "QObject"] = None) -> Optional["QObject"]: if self._qml_engine is None: # Protect in case the engine was not initialized yet return None path = QUrl.fromLocalFile(qml_file_path) component = QQmlComponent(self._qml_engine, path) result_context = QQmlContext( self._qml_engine.rootContext() ) #type: ignore #MyPy doens't realise that self._qml_engine can't be None here. if context_properties is not None: for name, value in context_properties.items(): result_context.setContextProperty(name, value) result = component.create(result_context) for err in component.errors(): Logger.log("e", str(err.toString())) if result is None: return None # We need to store the context with the qml object, else the context gets garbage collected and the qml objects # no longer function correctly/application crashes. result.attached_context = result_context return result ## Delete all nodes containing mesh data in the scene. # \param only_selectable. Set this to False to delete objects from all build plates @pyqtSlot() def deleteAll(self, only_selectable=True) -> None: Logger.log("i", "Clearing scene") if not self.getController().getToolsEnabled(): return nodes = [] for node in DepthFirstIterator( self.getController().getScene().getRoot() ): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax. if not isinstance(node, SceneNode): continue if (not node.getMeshData() and not node.callDecoration("getLayerData") ) and not node.callDecoration("isGroup"): continue # Node that doesnt have a mesh and is not a group. if only_selectable and not node.isSelectable(): continue if not node.callDecoration( "isSliceable") and not node.callDecoration( "getLayerData") and not node.callDecoration("isGroup"): continue # Only remove nodes that are selectable. if node.getParent() and cast( SceneNode, node.getParent()).callDecoration("isGroup"): continue # Grouped nodes don't need resetting as their parent (the group) is resetted) nodes.append(node) if nodes: op = GroupedOperation() for node in nodes: op.addOperation(RemoveSceneNodeOperation(node)) # Reset the print information self.getController().getScene().sceneChanged.emit(node) op.push() Selection.clear() ## Get the MeshFileHandler of this application. def getMeshFileHandler(self) -> MeshFileHandler: return self._mesh_file_handler def getWorkspaceFileHandler(self) -> WorkspaceFileHandler: return self._workspace_file_handler @pyqtSlot(result=QObject) def getPackageManager(self) -> PackageManager: return self._package_manager ## Gets the instance of this application. # # This is just to further specify the type of Application.getInstance(). # \return The instance of this application. @classmethod def getInstance(cls, *args, **kwargs) -> "QtApplication": return cast(QtApplication, super().getInstance(**kwargs)) def _createSplashScreen(self) -> QSplashScreen: return QSplashScreen( QPixmap( Resources.getPath(Resources.Images, self.getApplicationName() + ".png"))) def _screenScaleFactor(self) -> float: # OSX handles sizes of dialogs behind our backs, but other platforms need # to know about the device pixel ratio if sys.platform == "darwin": return 1.0 else: # determine a device pixel ratio from font metrics, using the same logic as UM.Theme fontPixelRatio = QFontMetrics( QCoreApplication.instance().font()).ascent() / 11 # round the font pixel ratio to quarters fontPixelRatio = int(fontPixelRatio * 4) / 4 return fontPixelRatio
self.sumResult.emit(a) self.first_operand = a elif self.sign == "*": a = self.first_operand * c self.sumResult.emit(a) self.first_operand = a elif self.sign == "/": a = self.first_operand / c self.sumResult.emit(a) self.first_operand = a if __name__ == "__main__": import sys app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() calculator = Calculator() engine.rootContext().setContextProperty("calculator", calculator) engine.load("main.qml") engine.quit.connect(app.quit) sys.exit(app.exec_())
del globals()["engine"] if __name__ == "__main__": projectHandler = ProjectHandler() logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) qmlRegisterType(Cardinalities, "ProjectSettingTypes", 1, 0, "Cardinalities") QGuiApplication.setAttribute(PyQt5.QtCore.Qt.AA_EnableHighDpiScaling, True) QGuiApplication.setAttribute(PyQt5.QtCore.Qt.AA_UseHighDpiPixmaps, True) app = QGuiApplication([]) engine = QQmlApplicationEngine() app.aboutToQuit.connect(shutdown) app.setApplicationName("MOCOS") app.setOrganizationDomain("mocos.pl") engine.rootContext().setContextProperty("projectHandler", projectHandler) engine.rootContext().setContextProperty( "initialConditions", projectHandler._settings.initialConditions) engine.rootContext().setContextProperty( "transmissionProbabilities", projectHandler._settings.transmissionProbabilities) engine.rootContext().setContextProperty( "generalSettings", projectHandler._settings.generalSettings) engine.rootContext().setContextProperty( "phoneTracking", projectHandler._settings.phoneTracking)
myseries.checkbaseline() timer.start(300) def stopreading(): readingthread.stopping() timer.stop() #Create the main app app = QApplication(sys.argv) app.setWindowIcon(QIcon("icons/logoonlyspheretransparent.png")) app.setOrganizationName('BluePhysics') #create the qml engine engine = QQmlApplicationEngine() #create objects in Python and pushthem to qml #QXYSeries context = engine.rootContext() context.setContextProperty("myseries", myseries) context.setContextProperty("mydarkcurrentthread", mydarkcurrentthread) context.setContextProperty("mysettingsw", mysettingsw) context.setContextProperty("regulatethread", regulatethread) #Load the qmlfile engine.load('main.qml') #get objects from qml engine startb = engine.rootObjects()[0].findChild(QObject, 'startbutton') stopb = engine.rootObjects()[0].findChild(QObject, 'stopbutton')
class start: def __init__(self): self.app = QGuiApplication(sys.argv) self.engine = QQmlApplicationEngine() self.app_icon = QIcon() self.set_icons() def load_ui(self): self.engine.load(os.path.join(os.getcwd(), r"qml/main.qml")) self.engine.load(os.path.join(os.getcwd(), r"qml/ui/login/login.qml")) self.engine.load(os.path.join(os.getcwd(), r"qml/ui/admin/admin.qml")) self.engine.load( os.path.join(os.getcwd(), r"qml/ui/student/student.qml")) self.engine.load( os.path.join(os.getcwd(), r"qml/ui/instructor/instructor.qml")) if not self.engine.rootObjects(): sys.exit(-1) sys.exit(self.app.exec_()) def instructor_context(self): InstructorMain = instructormain.main() self.engine.rootContext().setContextProperty("InstructorMain", InstructorMain) InstructorHome = instructorhome.home() self.engine.rootContext().setContextProperty("InstructorHome", InstructorHome) InstructorRequest = instructorrequest.appointment() self.engine.rootContext().setContextProperty("InstructorRequest", InstructorRequest) InstructorOfferService = instructoroffer.service() self.engine.rootContext().setContextProperty("InstructorOfferService", InstructorOfferService) InstructorRoomReservation = instructorroom.reserve() self.engine.rootContext().setContextProperty( "InstructorRoomReservation", InstructorRoomReservation) InstructorAccountDetails = instructoraccount.details() self.engine.rootContext().setContextProperty( "InstructorAccountDetails", InstructorAccountDetails) self.load_ui() def student_context(self): StudentMain = studentmain.main() self.engine.rootContext().setContextProperty("StudentMain", StudentMain) StudentHome = studenthome.home() self.engine.rootContext().setContextProperty("StudentHome", StudentHome) StudentReserve = studentreserve.roomreserve() self.engine.rootContext().setContextProperty("StudentReserve", StudentReserve) StudentAppointment = studentsetappointment.setAppointment() self.engine.rootContext().setContextProperty("StudentAppointment", StudentAppointment) StudentDetails = studentaccount.details() self.engine.rootContext().setContextProperty("StudentDetails", StudentDetails) StudentApplyService = studentapply.service() self.engine.rootContext().setContextProperty("StudentApplyService", StudentApplyService) self.instructor_context() def admin_context(self): AdminMain = admin.main() self.engine.rootContext().setContextProperty("AdminMain", AdminMain) AdminHome = home.home() self.engine.rootContext().setContextProperty("AdminHome", AdminHome) AdminReservation = roomreserve.roomreserve() self.engine.rootContext().setContextProperty("AdminReservation", AdminReservation) AdminStudent = student.student() self.engine.rootContext().setContextProperty("AdminStudent", AdminStudent) AdminInstructor = instructor.instructor() self.engine.rootContext().setContextProperty("AdminInstructor", AdminInstructor) AdminSetAppointment = setAppointment.setAppointment() self.engine.rootContext().setContextProperty("AdminSetAppointment", AdminSetAppointment) AdminOfferService = offer.service() self.engine.rootContext().setContextProperty("AdminOfferService", AdminOfferService) AdminApplyService = apply.service() self.engine.rootContext().setContextProperty("AdminApplyService", AdminApplyService) AdminAccountDetails = account.details() self.engine.rootContext().setContextProperty("AdminAccountDetails", AdminAccountDetails) AdminRequestAppointment = request.appointment() self.engine.rootContext().setContextProperty("AdminRequestAppointment", AdminRequestAppointment) self.student_context() def createaccount_context(self): CreateAccount = create.account() self.engine.rootContext().setContextProperty("CreateAccount", CreateAccount) self.admin_context() def queue_context(self): QueueNumber = queue.number() self.engine.rootContext().setContextProperty("QueueNumber", QueueNumber) self.createaccount_context() def login_context(self): Login = login.login() self.engine.rootContext().setContextProperty("Login", Login) self.queue_context() def splashscreen_context(self): SplashScreen = splashScreen.splashScreen() self.engine.rootContext().setContextProperty("SplashScreen", SplashScreen) self.login_context() def set_icons(self): app_icon_dir = os.path.join(os.getcwd(), r"app_icon/16x16.png") self.app_icon.addFile(app_icon_dir, QSize(16, 16)) self.app_icon.addFile(app_icon_dir, QSize(24, 24)) self.app_icon.addFile(app_icon_dir, QSize(32, 32)) self.app_icon.addFile(app_icon_dir, QSize(48, 48)) self.app_icon.addFile(app_icon_dir, QSize(256, 256)) self.app.setWindowIcon(self.app_icon) self.splashscreen_context()
class SciHubPreferences(QObject): showWindowPreferences = pyqtSignal() setFilenamePrefixFormat = pyqtSignal(str) setNetworkSciHubURLModel = pyqtSignal(list) setNetworkSciHubURLCurrentIndex = pyqtSignal(int) setNetworkTimeout = pyqtSignal(int) setNetworkRetryTimes = pyqtSignal(int) setProxyEnabled = pyqtSignal(bool) setProxyType = pyqtSignal(str) setProxyHost = pyqtSignal(str) setProxyPort = pyqtSignal(int) setProxyUsername = pyqtSignal(str) setProxyPassword = pyqtSignal(str) def __init__(self, conf): super(SciHubPreferences, self).__init__() self._conf = conf self._engine = QQmlApplicationEngine() self._engine.load('qrc:/ui/SciHubEVAPreferences.qml') self._window = self._engine.rootObjects()[0] self._connect() self.loadFromConf() self._scihub_add_scihub_url = SciHubAddSciHubURL(self._conf, self) def _connect(self): # Connect QML signals to PyQt slots self._window.showWindowAddSciHubURL.connect( self.showWindowAddSciHubURL) self._window.removeSciHubURL.connect(self.removeSciHubURL) self._window.saveFilenamePrefixFormat.connect( self.saveFilenamePrefixFormat) self._window.saveNetworkSciHubURLCurrentIndex.connect( self.saveNetworkSciHubURLCurrentIndex) self._window.saveNetworkTimeout.connect(self.saveNetworkTimeout) self._window.saveNetworkRetryTimes.connect(self.saveNetworkRetryTimes) self._window.saveProxyEnabled.connect(self.saveProxyEnabled) self._window.saveProxyType.connect(self.saveProxyType) self._window.saveProxyHost.connect(self.saveProxyHost) self._window.saveProxyPort.connect(self.saveProxyPort) self._window.saveProxyUsername.connect(self.saveProxyUsername) self._window.saveProxyPassword.connect(self.saveProxyPassword) # Connect PyQt signals to QML slots self.showWindowPreferences.connect(self._window.showWindowPreferences) self.setFilenamePrefixFormat.connect( self._window.setFilenamePrefixFormat) self.setNetworkSciHubURLModel.connect( self._window.setNetworkSciHubURLModel) self.setNetworkSciHubURLCurrentIndex.connect( self._window.setNetworkSciHubURLCurrentIndex) self.setNetworkTimeout.connect(self._window.setNetworkTimeout) self.setNetworkRetryTimes.connect(self._window.setNetworkRetryTimes) self.setProxyEnabled.connect(self._window.setProxyEnabled) self.setProxyType.connect(self._window.setProxyType) self.setProxyHost.connect(self._window.setProxyHost) self.setProxyPort.connect(self._window.setProxyPort) self.setProxyUsername.connect(self._window.setProxyUsername) self.setProxyPassword.connect(self._window.setProxyPassword) def loadFromConf(self): self.setFilenamePrefixFormat.emit( self._conf.get('common', 'filename_prefix_format')) scihub_available_urls = json.loads( self._conf.get('network', 'scihub_available_urls')) self.setNetworkSciHubURLModel.emit(scihub_available_urls) scihub_url = self._conf.get('network', 'scihub_url') self.setNetworkSciHubURLCurrentIndex.emit( scihub_available_urls.index(scihub_url)) self.setNetworkTimeout.emit(self._conf.getint('network', 'timeout')) self.setNetworkRetryTimes.emit( self._conf.getint('network', 'retry_times')) self.setProxyEnabled.emit(self._conf.getboolean('proxy', 'enabled')) self.setProxyType.emit(self._conf.get('proxy', 'type')) self.setProxyHost.emit(self._conf.get('proxy', 'host')) self.setProxyPort.emit(self._conf.getint('proxy', 'port')) self.setProxyUsername.emit(self._conf.get('proxy', 'username')) self.setProxyPassword.emit(self._conf.get('proxy', 'password')) @pyqtSlot() def showWindowAddSciHubURL(self): self._scihub_add_scihub_url.showWindowAddSciHubURL.emit() @pyqtSlot(int) def removeSciHubURL(self, network__scihub_url_current_index): scihub_available_urls = json.loads( self._conf.get('network', 'scihub_available_urls')) del scihub_available_urls[network__scihub_url_current_index] self._conf.set('network', 'scihub_available_urls', json.dumps(scihub_available_urls)) self._conf.set('network', 'scihub_url', scihub_available_urls[0]) self.setNetworkSciHubURLCurrentIndex.emit(0) @pyqtSlot(str) def saveFilenamePrefixFormat(self, filename_prefix_format): self._conf.set('common', 'filename_prefix_format', filename_prefix_format) @pyqtSlot(int) def saveNetworkSciHubURLCurrentIndex(self, _scihub_url_current_index): scihub_available_urls = json.loads( self._conf.get('network', 'scihub_available_urls')) self._conf.set('network', 'scihub_url', scihub_available_urls[_scihub_url_current_index]) @pyqtSlot(int) def saveNetworkTimeout(self, timeout): self._conf.set('network', 'timeout', str(timeout)) def saveNetworkRetryTimes(self, retry_times): self._conf.set('network', 'retry_times', str(retry_times)) @pyqtSlot(bool) def saveProxyEnabled(self, enabled): self._conf.set('proxy', 'enabled', str(enabled).lower()) @pyqtSlot(str) def saveProxyType(self, type): self._conf.set('proxy', 'type', type) @pyqtSlot(str) def saveProxyHost(self, host): self._conf.set('proxy', 'host', host) @pyqtSlot(int) def saveProxyPort(self, port): self._conf.set('proxy', 'port', str(port)) @pyqtSlot(str) def saveProxyUsername(self, username): self._conf.set('proxy', 'username', username) @pyqtSlot(str) def saveProxyPassword(self, password): self._conf.set('proxy', 'password', password)
""" This will works if qml file main item is ApplicationWindow, not Item or Rectangle """ import sys import os from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine if __name__ == '__main__': full_directory = os.path.dirname(os.path.abspath(__file__)) app = QApplication(sys.argv) engine = QQmlApplicationEngine() qml_file = os.path.join(full_directory, "main2.qml") engine.load(str(qml_file)) window = engine.rootObjects()[0] window.show() sys.exit(app.exec_())
class Backend(QObject): def __init__(self): QObject.__init__(self) updated = pyqtSignal(str, arguments=['updater']) def updater(self, curr_time): self.updated.emit(curr_time) def bootUp(self): t_thread = threading.Thread(target=self._bootUp) t_thread.daemon = True t_thread.start() def _bootUp(self): while True: curr_time = strftime("%H:%M:%S", gmtime()) self.updater(curr_time) sleep(0.1) app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.quit.connect(app.quit) engine.load('./UI/main.qml') back_end = Backend() engine.rootObjects()[0].setProperty('backend', back_end) back_end.bootUp() sys.exit(app.exec())
import sys from PyQt5.QtCore import QUrl, QObject, pyqtSlot, pyqtSignal from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine class mainWindow(QObject): def __init__(self): QObject.__init__(self) # @pyqtSlot() # def sendBtn_Click(self): # print("Send Button Clicked") if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() currentWindow = mainWindow() engine.rootContext().setContextProperty("mainWindow", currentWindow) # engine.load(QUrl("main1.qml")) engine.load(QUrl("main2.qml")) # engine.load(QUrl("main3.qml")) senderW = engine.rootObjects()[0] if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
initialGenres = [ "(None)", "Biography", "Crime", "Science-fiction", "Fantastic", "Historic", "Nonfiction", "Theatre" ] initialBooks = [{ 'title': "Commentarii de Bello Gallico", 'author': "Caius Iulius Caesar", 'genre': "Historic", 'publisher': "Les Belles Lettres", 'year': "1926", 'summary': "Julius Caesar\'s firsthand account of the Gallic Wars", 'price': "9.00" }, { 'title': "Προμηθεὺς δεσμώτης", 'author': "Αἰσχύλος", 'genre': "Nonfiction", 'publisher': "Les Solitaires Intempestifs", 'year': "2010", 'summary': "Prometheus defied the gods and gave fire to mankind", 'price': "24.34" }] if __name__ == "__main__": app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.quit.connect(app.quit) engine.rootContext().setContextProperty("initialGenres", initialGenres) engine.rootContext().setContextProperty("initialBooks", initialBooks) engine.load("main.qml") sys.exit(app.exec_())
def capture_screen_stop(self): self.hide() self.timer.stop() class MyClass(QObject): def __init__(self): super(MyClass, self).__init__() self.scw = ScreenCaptureWindow() @pyqtSlot(str) def screen_capture_start(self): self.scw.capture_screen_start() @pyqtSlot(str) def screen_capture_stop(self): self.scw.capture_screen_stop() if __name__ == "__main__": app = QApplication(sys.argv) engine = QQmlApplicationEngine() # engine.load("resources/qmls/app_main_window.qml") # engine.load(QUrl("qrc:/resources/qmls/app_main_window.qml")) engine.load(":/resources/qmls/app_main_window.qml") con = MyClass() context = engine.rootContext() context.setContextProperty("con", con) # myApp = MyAppMainWindow() sys.exit(app.exec_())
def __init__(self): qInstallMessageHandler(FramUtil.qt_msg_handler) self.rpc = RpcClient() # self.app = QApplication(sys.argv) appGuid = 'F3FF80BA-BA05-4277-8063-82A6DB9245A5' self.app = QtSingleApplication(appGuid, sys.argv) if self.app.isRunning(): sys.exit(0) self.app.unhandledExceptionCaught.connect(self.exception_caught) qmlRegisterType(SortFilterProxyModel, "SortFilterProxyModel", 0, 1, "SortFilterProxyModel") self.engine = QQmlApplicationEngine() self.context = self.engine.rootContext() # qmlRegisterType(FramTreeItem, 'FramTreeItem', 1, 0, 'FramTreeItem') # Set Contexts # wfs = WindowFrameSize() # self.context.setContextProperty('wfs', wfs) fl = FramLog() self.context.setContextProperty('framLog', fl) db = HookAndLineHookCutterDB() self.context.setContextProperty('db', db) self.state_machine = StateMachine(app=self, db=db) self.sound_player = SoundPlayer(app=self, db=db) self.serial_port_manager = SerialPortManager(app=self, db=db) self.sites = Sites(app=self, db=db) self.fish_sampling = FishSampling(app=self, db=db) self.label_printer = LabelPrinter(app=self, db=db) self.notes = Notes(app=self, db=db) # self.qaqc = QAQC(app=self, db=db) self.context.setContextProperty("soundPlayer", self.sound_player) self.context.setContextProperty("stateMachine", self.state_machine) self.context.setContextProperty("sites", self.sites) self.context.setContextProperty("fishSampling", self.fish_sampling) self.context.setContextProperty("serialPortManager", self.serial_port_manager) self.context.setContextProperty("labelPrinter", self.label_printer) self.context.setContextProperty("notes", self.notes) # self.context.setContextProperty("qaqc", self.qaqc) # self.setAttribute(QtCore.Qt.WA_DeleteOnClose) try: self.engine.load( QUrl('qrc:/qml/survey_backdeck/main_backdeck.qml')) self.win = self.engine.rootObjects()[0] self.msg_box = self.win.findChild(QObject, "dlgUnhandledException") self.engine.quit.connect(self.app.quit) sys.exit(self.app.exec_()) except Exception as ex: logging.error(f"bad stuff happening: {ex}")
:return: bool """ try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if __name__ == '__main__': if is_admin(): QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) path = 'qrc:/Main.qml' # 加载的QML文件 app = QGuiApplication(sys.argv) app.setWindowIcon(QIcon(':/img/icon.ico')) engine = QQmlApplicationEngine() context = engine.rootContext() setting = Setting() mysqlServiceManager = MysqlServiceManager(setting) mysqlConfiguration = MysqlConfiguration() system = System() context.setContextProperty("mysqlServiceManager", mysqlServiceManager) context.setContextProperty("mysqlConfiguration", mysqlConfiguration) context.setContextProperty("system", system) context.setContextProperty("setting", setting) # Mysql状态检测线程 _thread.start_new_thread(mysqlServiceManager.status_update_thread, ())
class Backdeck: def __init__(self): qInstallMessageHandler(FramUtil.qt_msg_handler) self.rpc = RpcClient() # self.app = QApplication(sys.argv) appGuid = 'F3FF80BA-BA05-4277-8063-82A6DB9245A5' self.app = QtSingleApplication(appGuid, sys.argv) if self.app.isRunning(): sys.exit(0) self.app.unhandledExceptionCaught.connect(self.exception_caught) qmlRegisterType(SortFilterProxyModel, "SortFilterProxyModel", 0, 1, "SortFilterProxyModel") self.engine = QQmlApplicationEngine() self.context = self.engine.rootContext() # qmlRegisterType(FramTreeItem, 'FramTreeItem', 1, 0, 'FramTreeItem') # Set Contexts # wfs = WindowFrameSize() # self.context.setContextProperty('wfs', wfs) fl = FramLog() self.context.setContextProperty('framLog', fl) db = HookAndLineHookCutterDB() self.context.setContextProperty('db', db) self.state_machine = StateMachine(app=self, db=db) self.sound_player = SoundPlayer(app=self, db=db) self.serial_port_manager = SerialPortManager(app=self, db=db) self.sites = Sites(app=self, db=db) self.fish_sampling = FishSampling(app=self, db=db) self.label_printer = LabelPrinter(app=self, db=db) self.notes = Notes(app=self, db=db) # self.qaqc = QAQC(app=self, db=db) self.context.setContextProperty("soundPlayer", self.sound_player) self.context.setContextProperty("stateMachine", self.state_machine) self.context.setContextProperty("sites", self.sites) self.context.setContextProperty("fishSampling", self.fish_sampling) self.context.setContextProperty("serialPortManager", self.serial_port_manager) self.context.setContextProperty("labelPrinter", self.label_printer) self.context.setContextProperty("notes", self.notes) # self.context.setContextProperty("qaqc", self.qaqc) # self.setAttribute(QtCore.Qt.WA_DeleteOnClose) try: self.engine.load( QUrl('qrc:/qml/survey_backdeck/main_backdeck.qml')) self.win = self.engine.rootObjects()[0] self.msg_box = self.win.findChild(QObject, "dlgUnhandledException") self.engine.quit.connect(self.app.quit) sys.exit(self.app.exec_()) except Exception as ex: logging.error(f"bad stuff happening: {ex}") def exception_caught(self, except_type, except_value, traceback_obj): tbinfofile = io.StringIO() traceback.print_tb(traceback_obj, None, tbinfofile) tbinfofile.seek(0) tbinfo = tbinfofile.read() log_filename = "survey_backdeck_debug.log" log_filepath = os.path.join(os.getcwd(), log_filename) msg = f"Exception occurred at {arrow.now().format('MM/DD/YYYY HH:mm:ss')}\n\n Please check log file at:\n{log_filepath}\n\n{except_type}: {except_value}\n\n{tbinfo}" logging.info(f"{msg}") self.msg_box.show(msg) logging.info( f"Survey Backdeck is quitting at {arrow.now().format('MM/DD/YYYY HH:mm:ss')}" )
import sys from PyQt5.QtGui import QGuiApplication, QIcon from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtCore import QResource from chatbot import ChatBot, ChatBot2 app = QGuiApplication(sys.argv) QResource.registerResource('main.rcc') app.setWindowIcon(QIcon(":/resources/disc_logo.png")) engine = QQmlApplicationEngine() chatbb = ChatBot() chatboo = ChatBot2() engine.rootContext().setContextProperty('chatty', chatbb) engine.rootContext().setContextProperty('chatt', chatboo) engine.load(':/main.qml') engine.quit.connect(app.quit) sys.exit(app.exec_())
import os import sys from PyQt5.QtCore import QUrl, QObject from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine from UI import classres os.environ['QT_QUICK_CONTROLS_STYLE'] = "Universal" app = QApplication(sys.argv) # Create QML engine engine = QQmlApplicationEngine() # Load the qml file into the engine engine.load(QUrl('qrc:/UI/qml/main.qml')) # Qml file error handling if not engine.rootObjects(): sys.exit(-1) # Send QT_QUICK_CONTROLS_STYLE to main qml (only for demonstration) qtquick2Themes = engine.rootObjects()[0].findChild( QObject, 'qtquick2Themes' ) qtquick2Themes.setProperty('text', os.environ['QT_QUICK_CONTROLS_STYLE']) sys.exit(app.exec_())
import sys from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QGuiApplication from PyQt5.QtQuick import QQuickView from PyQt5.QtQml import QQmlApplicationEngine from DoubanFM import DoubanFM import Logger # Main Function if __name__ == '__main__': # Create main app main_app = QGuiApplication(sys.argv) # Create a label and set its properties douban = DoubanFM() logger = Logger.Logger() engine = QQmlApplicationEngine(parent=main_app) root_context = engine.rootContext() root_context.setContextProperty("douban", douban) root_context.setContextProperty("logger", logger) mainurl = "qml/main.qml" engine.load(QUrl(mainurl)) # Execute the Application and Exit rc = main_app.exec_() sys.exit(rc)
def __init__(self): self.app = QGuiApplication(sys.argv) self.engine = QQmlApplicationEngine() self.app_icon = QIcon() self.set_icons()
import sys from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.quit.connect(app.quit) engine.load("main.qml") sys.exit(app.exec_())
Adds a whitelisted password to FTP router """ self.ftp_router.add_whitelist_password(password) @pyqtSlot(str) def remove_whitelist_password(self, password: str): """ Removes a whitelisted password from the FTP router """ self.ftp_router.remove_whitelist_password(password) if __name__ == "__main__": app = QGuiApplication(sys.argv) app.setOrganizationName(" ") app.setOrganizationDomain(" ") main_window = MainWindow() GUI.main_window = main_window engine = QQmlApplicationEngine() root = engine.rootContext() root.setContextProperty("backend", main_window) engine.load(r"Honeypot/qml/main.qml") if not engine.rootObjects(): sys.exit(-1) ret = app.exec_() main_window.stop_routers() # stop routers before exit sys.exit(ret)