def main(): # Set up correct Ctrl-C behavior. signal.signal(signal.SIGINT, signal.SIG_DFL) app = QGuiApplication( sys.argv ) engine = QQmlEngine() engine.addImportPath( path.join( path.dirname( __file__ ), 'ui', 'qml' ) ) core.register_types() component = QQmlComponent( engine ) component.loadUrl( QUrl( '/home/feoh3/.config/nube/hud.qml' ) ) if component.isError(): print( "\n".join( error.toString() for error in component.errors() ) ) else: window = component.create() app.exec_()
def ros_qml_main(): try: rospy.init_node('ros_qml', sys.argv) my_argv = rospy.myargv(sys.argv) signal.signal(signal.SIGINT, sigint_handler) app = QApplication(my_argv) engine = QQmlEngine() engine.quit.connect(app.quit) plugins_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath) # ## Add QML extension modules and plugins to the path, including ourselves plugins_paths = rospack.get_manifest(THIS_PACKAGE).get_export( THIS_PACKAGE, 'plugins') for idx, p in enumerate(plugins_paths): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): plugins_paths[idx] = plugins_dir + '/' + p qml_paths = rospack.get_manifest(THIS_PACKAGE).get_export( THIS_PACKAGE, 'imports') deps = rospack.get_depends_on(THIS_PACKAGE) for d in deps: pp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'plugins') for idx, p in enumerate(pp): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): pp[idx] = plugins_dir + '/' + p plugins_paths += pp qp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'imports') qml_paths += qp for p in plugins_paths: engine.addPluginPath(p) for p in qml_paths: engine.addImportPath(p) qml_sys_path = QLibraryInfo.location(QLibraryInfo.ImportsPath) engine.addImportPath(qml_sys_path) # Somehow we need to set the path both with QQmlEngine and with environment, # commenting any of the two will lead to 'module not installed' error os.environ['QML2_IMPORT_PATH'] = ':'.join( qml_paths) + ':' + qml_sys_path comp = QQmlComponent(engine) if len(my_argv) > 1 and my_argv[1]: qml_url = my_argv[1] comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_url'): qml_url = rospy.get_param('qml_url') comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_description'): # experimental qml_description = rospy.get_param('qml_description') # FIXME that hangs for unknown reason comp.setData(QByteArray(qml_description), QUrl()) else: rospy.logfatal( 'Neither /qml_url nor /qml_description (experimental) parameter is present' ) sys.exit(1) if not comp.isReady(): sys.stderr.write(comp.errorString()) sys.exit(1) win = comp.create() if not win: rospy.logfatal('Your root item has to be a Window') sys.exit(1) engine.setIncubationController(win.incubationController()) if win: win.show() # Poll Python interpreter every 500ms timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) sys.exit(app.exec_()) except KeyboardInterrupt: pass except rospy.ROSInterruptException: pass
class GuiApplicationBase(ApplicationBase, QApplication): _logger = logging.getLogger(__name__) has_gui = True ############################################## def __init__(self, args, **kwargs): super(GuiApplicationBase, self).__init__(args=args, **kwargs) # Fixme: Why ? self._logger.debug("QApplication " + str(sys.argv)) QApplication.__init__(self, sys.argv) self._logger.debug('GuiApplicationBase ' + str(args) + ' ' + str(kwargs)) self.setAttribute(Qt.AA_EnableHighDpiScaling) # from . import BabelRessource rcc_path = ConfigInstall.Path.join_share_directory('babel.rcc') self._logger.debug('Load ressource {}'.format(rcc_path)) if not QResource.registerResource(str(rcc_path)): self._logger.debug('Failed to load ressource {}'.format(rcc_path)) # self._display_splash_screen() self._main_window = None self._initialise_qml_engine() self._init_actions() ############################################## @property def main_window(self): return self._main_window @property def qml_engine(self): return self._qml_engine @property def qml_context(self): return self._qml_engine.rootContext() ############################################## def _exception_hook(self, exception_type, exception_value, exception_traceback): traceback.print_exception(exception_type, exception_value, exception_traceback) dialog = CriticalErrorDialog( exception_type, exception_value, exception_traceback, qml_engine=self._qml_engine ) rc = dialog.exec_() if rc == -1: self.exit() # return sys.__excepthook__(exception_type, exception_value, exception_traceback) ############################################## def _display_splash_screen(self): pixmap = QPixmap(':/splash screen/images/splash_screen.png') self._splash = QSplashScreen(pixmap) self._splash.show() self._splash.showMessage('<h2>Babel %(version)s</h2>' % {'version':str(Version.babel)}) self.processEvents() ############################################## def _initialise_qml_engine(self): self._qml_engine = QQmlEngine(self) qml_path = str(ConfigInstall.Path.qml_path) self._qml_engine.addImportPath(qml_path) context = self.qml_context self._application_style = ApplicationStyle() context.setContextProperty('application_style', self._application_style) self._icon_provider = IconProvider() self._qml_engine.addImageProvider('icon_provider', self._icon_provider) ############################################## def _init_actions(self): self.about_action = QAction( 'About Babel', self, triggered=self.about, ) self.exit_action = QAction( 'Exit', self, triggered=self.exit, ) self.help_action = QAction( 'Help', self, triggered=self.open_help, ) self.show_system_information_action = QAction( 'System Information', self, triggered=self.show_system_information, ) ############################################## def post_init(self): # self._splash.finish(self._main_window) # self.processEvents() # del self._splash QTimer.singleShot(0, self.execute_given_user_script) self.show_message('Welcome to Babel') # return to main and then enter to event loop ############################################## def show_message(self, message=None, echo=False, timeout=0): # Fixme: cf. PdfBrowserApplication if self._main_window is not None: self._main_window.show_message(message, echo, timeout) ############################################## # def critical_error(self, title='Babel Critical Error', message=''): # # # Fixme: CriticalErrorForm vs critical_error # # QMessageBox.critical(None, title, message) # # # Fixme: qt close? # sys.exit(1) ############################################## def open_help(self): url = QUrl() url.setScheme(DefaultConfig.Help.url_scheme) url.setHost(DefaultConfig.Help.host) url.setPath(DefaultConfig.Help.url_path_pattern) # % str(Version.babel)) QDesktopServices.openUrl(url) ############################################## def about(self): message = Messages.about_babel % {'version':str(Version.babel)} QMessageBox.about(self.main_window, 'About Babel', message) ############################################## def show_system_information(self): fields = dict(self._platform.__dict__) fields.update({ 'babel_version': str(Version.babel), }) message = Messages.system_information_message_pattern % fields QMessageBox.about(self.main_window, 'System Information', message)
class QMLApplicationWidget(QWidget): def __init__(self, fileUrl, parent=None): super(QMLApplicationWidget, self).__init__(parent=parent) self.setLayout(QVBoxLayout()) self.app = runningApp() self.epFileUrl = fileUrl self.fsw = FileWatcher(parent=self) self.fsw.pathChanged.connect(self.onReloadApp) self.fsw.watch(self.epFileUrl) self.stack = QStackedWidget() self.layout().addWidget(self.stack) self.gInterface = GHandler(self) self.iInterface = IHandler(self) self.ldInterface = LDHandler(self) self.sparqlInterface = SparQLHandler(self) self.ipidInterface = IPIDHandler(self) self.currentComponent = None # Clone the IPFS profile self.webProfile = self.app.webProfiles['ipfs'].quickClone() # TODO: move this in global place self.models = { 'Articles': ArticlesModel(), 'Channels': MultimediaChannelsModel(), 'Shouts': ShoutsModel() } self.setupEngine() @property def comp(self): return self.currentComponent def onReloadApp(self, chPath): print(chPath, 'changed') self.engine.clearComponentCache() self.load() def setupEngine(self): ipfsCtx = self.app.ipfsCtx filesModel = ipfsCtx.currentProfile.filesModel # stores = services.getByDotName('ld.rdf.graphs') self.engine = QQmlEngine(self) ctx = self.engine.rootContext() # XML graph exports paths # ctx.setContextProperty('graphGXmlPath', # stores.graphG.xmlExportUrl) ctx.setContextProperty('g', self.gInterface) ctx.setContextProperty('ld', self.ldInterface) ctx.setContextProperty('sparql', self.sparqlInterface) ctx.setContextProperty('iContainer', self.iInterface) ctx.setContextProperty('ipid', self.ipidInterface) # Pass the web profile ctx.setContextProperty('ipfsWebProfile', self.webProfile) ctx.setContextProperty('modelArticles', self.models['Articles']) ctx.setContextProperty('modelMultiChannels', self.models['Channels']) ctx.setContextProperty('modelShouts', self.models['Shouts']) ctx.setContextProperty('modelMfs', filesModel) def resizeEvent(self, event): super().resizeEvent(event) if self.comp: self.iInterface.size = event.size() self.iInterface.sizeChanged.emit(event.size().width(), event.size().height()) def importComponent(self, path): self.engine.addImportPath(path) self.fsw.watchWalk(Path(path)) def load(self): # stores = services.getByDotName('ld.rdf.graphs') qcomp = quickEnginedWidget(self.engine, QUrl.fromLocalFile(self.epFileUrl), parent=self.stack) if not qcomp: return self.stack.addWidget(qcomp) self.stack.setCurrentWidget(qcomp) self.stack.setFocus(Qt.OtherFocusReason) qcomp.setFocus(Qt.OtherFocusReason) self.currentComponent = qcomp
class GuiApplicationBase(ApplicationBase, QApplication): _logger = logging.getLogger(__name__) has_gui = True ############################################## def __init__(self, args, **kwargs): super(GuiApplicationBase, self).__init__(args=args, **kwargs) # Fixme: Why ? self._logger.debug("QApplication " + str(sys.argv)) QApplication.__init__(self, sys.argv) self._logger.debug('GuiApplicationBase ' + str(args) + ' ' + str(kwargs)) self.setAttribute(Qt.AA_EnableHighDpiScaling) # from . import BabelRessource rcc_path = ConfigInstall.Path.join_share_directory('babel.rcc') self._logger.debug('Load ressource {}'.format(rcc_path)) if not QResource.registerResource(str(rcc_path)): self._logger.debug('Failed to load ressource {}'.format(rcc_path)) # self._display_splash_screen() self._main_window = None self._initialise_qml_engine() self._init_actions() ############################################## @property def main_window(self): return self._main_window @property def qml_engine(self): return self._qml_engine @property def qml_context(self): return self._qml_engine.rootContext() ############################################## def _exception_hook(self, exception_type, exception_value, exception_traceback): traceback.print_exception(exception_type, exception_value, exception_traceback) dialog = CriticalErrorDialog(exception_type, exception_value, exception_traceback, qml_engine=self._qml_engine) rc = dialog.exec_() if rc == -1: self.exit() # return sys.__excepthook__(exception_type, exception_value, exception_traceback) ############################################## def _display_splash_screen(self): pixmap = QPixmap(':/splash screen/images/splash_screen.png') self._splash = QSplashScreen(pixmap) self._splash.show() self._splash.showMessage('<h2>Babel %(version)s</h2>' % {'version': str(Version.babel)}) self.processEvents() ############################################## def _initialise_qml_engine(self): self._qml_engine = QQmlEngine(self) qml_path = str(ConfigInstall.Path.qml_path) self._qml_engine.addImportPath(qml_path) context = self.qml_context self._application_style = ApplicationStyle() context.setContextProperty('application_style', self._application_style) self._icon_provider = IconProvider() self._qml_engine.addImageProvider('icon_provider', self._icon_provider) ############################################## def _init_actions(self): self.about_action = QAction( 'About Babel', self, triggered=self.about, ) self.exit_action = QAction( 'Exit', self, triggered=self.exit, ) self.help_action = QAction( 'Help', self, triggered=self.open_help, ) self.show_system_information_action = QAction( 'System Information', self, triggered=self.show_system_information, ) ############################################## def post_init(self): # self._splash.finish(self._main_window) # self.processEvents() # del self._splash QTimer.singleShot(0, self.execute_given_user_script) self.show_message('Welcome to Babel') # return to main and then enter to event loop ############################################## def show_message(self, message=None, echo=False, timeout=0): # Fixme: cf. PdfBrowserApplication if self._main_window is not None: self._main_window.show_message(message, echo, timeout) ############################################## # def critical_error(self, title='Babel Critical Error', message=''): # # # Fixme: CriticalErrorForm vs critical_error # # QMessageBox.critical(None, title, message) # # # Fixme: qt close? # sys.exit(1) ############################################## def open_help(self): url = QUrl() url.setScheme(DefaultConfig.Help.url_scheme) url.setHost(DefaultConfig.Help.host) url.setPath( DefaultConfig.Help.url_path_pattern) # % str(Version.babel)) QDesktopServices.openUrl(url) ############################################## def about(self): message = Messages.about_babel % {'version': str(Version.babel)} QMessageBox.about(self.main_window, 'About Babel', message) ############################################## def show_system_information(self): fields = dict(self._platform.__dict__) fields.update({ 'babel_version': str(Version.babel), }) message = Messages.system_information_message_pattern % fields QMessageBox.about(self.main_window, 'System Information', message)
def ros_qml_main(): try: rospy.init_node('ros_qml', sys.argv) my_argv = rospy.myargv(sys.argv) signal.signal(signal.SIGINT, sigint_handler) app = QApplication(my_argv) engine = QQmlEngine() engine.quit.connect(app.quit) plugins_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath) # ## Add QML extension modules and plugins to the path, including ourselves plugins_paths = rospack.get_manifest(THIS_PACKAGE).get_export(THIS_PACKAGE, 'plugins') for idx, p in enumerate(plugins_paths): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): plugins_paths[idx] = plugins_dir + '/' + p qml_paths = rospack.get_manifest(THIS_PACKAGE).get_export(THIS_PACKAGE, 'imports') deps = rospack.get_depends_on(THIS_PACKAGE) for d in deps: pp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'plugins') for idx, p in enumerate(pp): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): pp[idx] = plugins_dir + '/' + p plugins_paths += pp qp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'imports') qml_paths += qp for p in plugins_paths: engine.addPluginPath(p) for p in qml_paths: engine.addImportPath(p) qml_sys_path = QLibraryInfo.location(QLibraryInfo.ImportsPath) engine.addImportPath(qml_sys_path) # Somehow we need to set the path both with QQmlEngine and with environment, # commenting any of the two will lead to 'module not installed' error os.environ['QML2_IMPORT_PATH'] = ':'.join(qml_paths) + ':' + qml_sys_path comp = QQmlComponent(engine) if len(my_argv) > 1 and my_argv[1]: qml_url = my_argv[1] comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_url'): qml_url = rospy.get_param('qml_url') comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_description'): # experimental qml_description = rospy.get_param('qml_description') # FIXME that hangs for unknown reason comp.setData(QByteArray(qml_description), QUrl()) else: rospy.logfatal('Neither /qml_url nor /qml_description (experimental) parameter is present') sys.exit(1) if not comp.isReady(): sys.stderr.write(comp.errorString()) sys.exit(1) win = comp.create() if not win: rospy.logfatal('Your root item has to be a Window') sys.exit(1) engine.setIncubationController(win.incubationController()) if win: win.show() # Poll Python interpreter every 500ms timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) sys.exit(app.exec_()) except KeyboardInterrupt: pass except rospy.ROSInterruptException: pass