コード例 #1
0
    def __init__(self,
                 container_id: str,
                 i18n_catalog: i18nCatalog = None,
                 parent: QObject = None,
                 *args,
                 **kwargs) -> None:
        """Constructor
        
        :param container_id: A unique, machine readable/writable ID for this container.
        """

        super().__init__()
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {
            "id": container_id,
            "name": container_id,
            "container_type": DefinitionContainer,
            "version": self.Version
        }  # type: Dict[str, Any]
        self._definitions = []  # type: List[SettingDefinition]
        self._inherited_files = []  # type: List[str]
        self._i18n_catalog = i18n_catalog  # type: Optional[i18nCatalog]

        self._definition_cache = {}  # type: Dict[str, SettingDefinition]
        self._path = ""
コード例 #2
0
ファイル: ContainerStack.py プロジェクト: vfrisach/Uranium
    def __init__(self, stack_id: str) -> None:
        """Constructor

        :param stack_id: A unique, machine readable/writable ID.
        """

        super().__init__()
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {
            "id": stack_id,
            "name": stack_id,
            "version": self.Version,
            "container_type": ContainerStack
        }  #type: Dict[str, Any]
        self._containers = []  # type: List[ContainerInterface]
        self._next_stack = None  # type: Optional[ContainerStack]
        self._read_only = False  # type: bool
        self._dirty = False  # type: bool
        self._path = ""  # type: str
        self._postponed_emits = [
        ]  # type: List[Tuple[Signal, ContainerInterface]] # gets filled with 2-tuples: signal, signal_argument(s)

        self._property_changes = {}  # type: Dict[str, Set[str]]
        self._emit_property_changed_queued = False  # type: bool
コード例 #3
0
ファイル: InstanceContainer.py プロジェクト: situchen/Uranium
    def __init__(self,
                 container_id: str,
                 parent: QObject = None,
                 *args: Any,
                 **kwargs: Any) -> None:
        """Constructor
        
        :param container_id: A unique, machine readable/writable ID for this container.
        """

        super().__init__()
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {
            "id": container_id,
            "name": container_id,
            "version": self.Version,
            "container_type": InstanceContainer
        }  # type: Dict[str, Any]
        self._instances = {}  # type: Dict[str, SettingInstance]
        self._read_only = False  # type: bool
        self._dirty = False  # type: bool
        self._path = ""  # type: str
        self._postponed_emits = [
        ]  # type: List[Tuple[Signal, Tuple[str, str]]]
        self._definition = None  # type: Optional[DefinitionContainerInterface]

        self._cached_values = None  # type: Optional[Dict[str, Any]]
コード例 #4
0
ファイル: qmlapp.py プロジェクト: pinnaculum/galacteek
    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)
コード例 #5
0
    def __init__(self, parent = None):
        super().__init__(parent)
        # Ensure that this model doesn't get garbage collected (Now the bound object is destroyed when the wrapper is)
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)
        self._device_manager = Application.getInstance().getOutputDeviceManager()  # type: OutputDeviceManager

        self.addRoleName(self.IdRole, "id")
        self.addRoleName(self.NameRole, "name")
        self.addRoleName(self.PriorityRole, "priority")
        self.addRoleName(self.ShortcutRole, "shortcut")

        self._device_manager.projectOutputDevicesChanged.connect(self._update)
        self._update()
コード例 #6
0
    def __init__(self, container_id: str, i18n_catalog: i18nCatalog = None, parent: QObject = None, *args, **kwargs) -> None:
        super().__init__()
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {"id": container_id,
                          "name": container_id,
                          "container_type": DefinitionContainer,
                          "version": self.Version} # type: Dict[str, Any]
        self._definitions = []                     # type: List[SettingDefinition]
        self._inherited_files = []                 # type: List[str]
        self._i18n_catalog = i18n_catalog

        self._definition_cache = {}                # type: Dict[str, SettingDefinition]
        self._path = ""
コード例 #7
0
    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)
コード例 #8
0
    def __init__(self, container_id: str, i18n_catalog: i18nCatalog = None, parent: QObject = None, *args, **kwargs) -> None:
        super().__init__()
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {"id": container_id,
                          "name": container_id,
                          "container_type": DefinitionContainer,
                          "version": self.Version} # type: Dict[str, Any]
        self._definitions = []                     # type: List[SettingDefinition]
        self._inherited_files = []                 # type: List[str]
        self._i18n_catalog = i18n_catalog          # type: Optional[i18nCatalog]

        self._definition_cache = {}                # type: Dict[str, SettingDefinition]
        self._path = ""
コード例 #9
0
    def prepareAlgorithm(self, parameters, context, feedback):
        """
        Prepares the algorithm
        """
        self.engine = QJSEngine()
        js_feedback = self.engine.newQObject(feedback)
        QQmlEngine.setObjectOwnership(feedback, QQmlEngine.CppOwnership)
        self.engine.globalObject().setProperty("feedback", js_feedback)
        js = """
        function process(feature)
        {
          res = func(JSON.parse(feature))
          if ( res && res.stack && res.message )
            return res;
         return JSON.stringify(res);
        }
        """

        for param in self.parameterDefinitions():
            if param.isDestination():
                continue

            if param.name() not in parameters or parameters[param.name()] is None:
                js += '{}=None;\n'.format(param.name())
                continue

            if isinstance(param,
                            (QgsProcessingParameterField, QgsProcessingParameterString, QgsProcessingParameterFile)):
                value = self.parameterAsString(parameters, param.name(), context)
                js += '{}="{}";'.format(param.name(), value)
            elif isinstance(param, QgsProcessingParameterNumber):
                value = self.parameterAsDouble(parameters, param.name(), context)
                js += '{}={};'.format(param.name(), value)

        js += self.js_script
        result = self.engine.evaluate(js)

        user_func = self.engine.globalObject().property("func")
        if not user_func:
            raise QgsProcessingException('No \'func\' function detected in script')
        if not user_func.isCallable():
            raise QgsProcessingException('Object \'func\' is not a callable function')

        self.process_js_function = self.engine.globalObject().property("process")
        self.json_exporter = QgsJsonExporter()

        self.codec = QTextCodec.codecForName("System")

        return True
コード例 #10
0
ファイル: app.py プロジェクト: nihalvaria/digital-waterfall
    def __init__(self) :
        QObject.__init__( self )
        self.app = QApplication( sys.argv )
        self.app.setApplicationName( 'Waterfall' )
        engine = QQmlEngine()

        appDirPath = os.path.dirname( os.path.abspath( __file__ ) )
        rootContext = engine.rootContext()
        rootContext.setContextProperty( 'controller', self )
        rootContext.setContextProperty( 'appPath', appDirPath.replace( "\\", "/" ) + "/" )
        windowComp = QQmlComponent( engine, QUrl( 'qml/Main.qml' ) )
        
        self.window = windowComp.create()
        self.window.show()
        self.app.exec()
コード例 #11
0
    def __init__(self, parent = None):
        super().__init__(parent)
        # Ensure that this model doesn't get garbage collected (Now the bound object is destroyed when the wrapper is)
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)
        self._device_manager = Application.getInstance().getOutputDeviceManager()

        self.addRoleName(self.IdRole, "id")
        self.addRoleName(self.NameRole, "name")
        self.addRoleName(self.ShortDescriptionRole, "short_description")
        self.addRoleName(self.DescriptionRole, "description")
        self.addRoleName(self.IconNameRole, "icon_name")
        self.addRoleName(self.PriorityRole, "priority")

        self._device_manager.outputDevicesChanged.connect(self._update)
        self._update()
コード例 #12
0
    def reloadProject(self, filename):
        engine = QQmlEngine()
        component = QQmlComponent(engine)
        component.loadUrl(QUrl(filename))
        self.site = component.create()
        if self.site is not None:
            self.site.setFilename(filename)
            self.site.setWindow(self)
        else:
            for error in component.errors():
                print(error.toString())
            return False

        self.site.loadMenus()
        self.site.loadPages()
        self.site.loadPosts()

        self.theme_settings_button.setVisible(False)
        Plugins.setActualThemeEditorPlugin("")
        for key in Plugins.themePluginNames():
            tei = Plugins.getThemePlugin(key)
            if tei:
                if tei.theme_name == self.site.theme:
                    Plugins.setActualThemeEditorPlugin(tei.class_name)
                    self.theme_settings_button.setVisible(True)
                    break

        #if not self.site.publisher:
        #    if len(Plugins.publishPluginNames()) > 0:
        #        self.site.publisher = Plugins.publishPluginNames[0]

        Plugins.setActualPublishPlugin(self.site.publisher)
        self.siteLoaded.emit(self.site)
        return True
コード例 #13
0
ファイル: animation.py プロジェクト: dbeckwith/cs4732-proj2
    def __init__(self, title, frame_rate, run_time):
        """
        Create a new Animation.

        Arguments:
            title: str, the window title
            frame_rate: float, the number of frames to display per second
            run_time: float, the number of seconds to run the animation
        """
        self.title = title
        assert 0 < frame_rate < 1000
        self.frame_rate = frame_rate
        assert run_time > 0
        self.run_time = run_time

        self.frame = 0
        self.prev_update_time = None

        # import OpenGL so Qt can use it for rendering
        from OpenGL import GL
        # create the 3D window
        self.view = Qt3DWindow()
        self.view.setX(100)
        self.view.setY(100)

        self.view.setTitle(self.title)

        self.qml_engine = QQmlEngine(self.view)
コード例 #14
0
def init_country_names_from_code(locale):
    '''Init the country description as found in GCompris geography/resource/board/board*.qml'''
    '''in the global descriptions hash'''

    po = None
    try:
        po = polib.pofile(gcompris_qt + '/po/gcompris_' + locale + '.po')
    except:
        print("**ERROR: Failed to load po file %s**" %
              ('/po/gcompris_' + locale + '.po'))
        print('')

    app = QCoreApplication(sys.argv)
    engine = QQmlEngine()
    component = QQmlComponent(engine)

    for qml in glob.glob(gcompris_qt +
                         '/src/activities/geography/resource/board/*.qml'):
        component.loadUrl(QUrl(qml))
        board = component.create()
        levels = board.property('levels')
        for level in levels.toVariant():
            if 'soundFile' in level and 'toolTipText' in level:
                sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg')
                tooltip = level['toolTipText']
                if po:
                    tooltip = po.find(tooltip).msgstr if po.find(
                        tooltip) else tooltip
                descriptions[sound] = tooltip
コード例 #15
0
def main(argv, app):

    engine = QQmlEngine(app)
    engine.quit.connect(app.quit)
    component = QQmlComponent(engine)
    component.loadUrl(QUrl('Wizard/Wizard.qml'))
    if component.isReady():
        mainWindow = component.create()
        file = FileInfo()
        context = engine.rootContext()
        context.setContextProperty('FileInfo', file)

    else:
        print(component.errorString())

    sys.exit(app.exec_())
コード例 #16
0
 def loadBook(self, filename):
     self.last_book = filename
     self.filename = ""
     engine = QQmlEngine()
     self.component = QQmlComponent(engine)
     self.component.statusChanged.connect(self.loadStatusChanged)
     self.component.loadUrl(QUrl.fromLocalFile(filename))
コード例 #17
0
ファイル: __main__.py プロジェクト: pianohacker/nube
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_()
コード例 #18
0
ファイル: ContainerStack.py プロジェクト: Ultimaker/Uranium
    def __init__(self, stack_id: str) -> None:
        super().__init__()
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {
            "id": stack_id,
            "name": stack_id,
            "version": self.Version,
            "container_type": ContainerStack
        } #type: Dict[str, Any]
        self._containers = []  # type: List[ContainerInterface]
        self._next_stack = None  # type: Optional[ContainerStack]
        self._read_only = False  # type: bool
        self._dirty = True  # type: bool
        self._path = ""  # type: str
        self._postponed_emits = [] #type: List[Tuple[Signal, ContainerInterface]] # gets filled with 2-tuples: signal, signal_argument(s)

        self._property_changes = {} #type: Dict[str, Set[str]]
        self._emit_property_changed_queued = False  # type: bool
コード例 #19
0
 def loadMenus(self):
     engine = QQmlEngine()
     component = QQmlComponent(engine)
     component.loadUrl(QUrl(os.path.join(self.source_path, "Menus.qml")))
     self.menus = component.create()
     if self.menus is not None:
         self.win.statusBar().showMessage("Menus have been loaded")
     else:
         for error in component.errors():
             print(error.toString())
     del engine
コード例 #20
0
ファイル: conftest.py プロジェクト: jgirardet/MyCartable
def pytest_qml_qmlEngineAvailable(engine: QQmlEngine):
    global db
    global fk
    global th
    from mycartable.main import (
        add_database_to_types,
    )

    add_database_to_types(db)
    ctx = engine.rootContext()
    ctx.setContextProperty("fk", fk)
    ctx.setContextProperty("th", th)
コード例 #21
0
    def __init__(self, stack_id: str, *args, **kwargs):
        # Note that we explicitly pass None as QObject parent here. This is to be able
        # to support pickling.
        super().__init__(parent=None, *args, **kwargs)
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)

        self._metadata = {
            "id": stack_id,
            "name": stack_id,
            "version": self.Version,
            "container_type": ContainerStack
        }
        self._containers = []  # type: List[ContainerInterface]
        self._next_stack = None  # type: Optional[ContainerStack]
        self._read_only = False  # type: bool
        self._dirty = True  # type: bool
        self._path = ""  # type: str
        self._postponed_emits = [
        ]  # gets filled with 2-tuples: signal, signal_argument(s)

        self._property_changes = {}
        self._emit_property_changed_queued = False  # type: bool
コード例 #22
0
    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)
コード例 #23
0
 def loadProject(self, filename):
     self.last_project = filename
     self.filename = ""
     engine = QQmlEngine()
     component = QQmlComponent(engine)
     component.loadUrl(QUrl(filename))
     self.project = component.create()
     if self.project is not None:
         self.project.setFilename(filename)
         self.project.setWindow(self)
     else:
         for error in component.errors():
             print(error.toString())
             return
コード例 #24
0
 def loadContent(self, source, type):
     if type == ContentType.PAGE:
         sub = "pages"
     else:
         sub = "posts"
     engine = QQmlEngine()
     component = QQmlComponent(engine)
     component.loadUrl(QUrl(os.path.join(self.source_path, sub, source)))
     content = component.create()
     if content is not None:
         content.source = source
         content.content_type = type
     else:
         for error in component.errors():
             print(error.toString())
     return content
コード例 #25
0
def get_geography_on_letter_from_code():
    '''Return all the countries in geography/resource/board/board-x.json'''
    words = set()

    app = QCoreApplication(sys.argv)
    engine = QQmlEngine()
    component = QQmlComponent(engine)
    for qml in glob.glob(gcompris_qt +
                         '/src/activities/geography/resource/board/*.qml'):
        component.loadUrl(QUrl(qml))
        board = component.create()
        levels = board.property('levels')
        for level in levels.toVariant():
            if 'soundFile' in level and (not 'type' in level or
                                         level['type'] != "SHAPE_BACKGROUND"):
                sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg')
                words.add(sound)
    return words
コード例 #26
0
    def loadMenus(self):
        engine = QQmlEngine()
        component = QQmlComponent(engine)
        component.loadUrl(QUrl.fromLocalFile(os.path.join(self.source_path, "Menus.qml")))
        self.menus = component.create()
        if self.menus is not None:
            self.win.statusBar().showMessage(QCoreApplication.translate("Site", "Menus have been loaded"))
        else:
            for error in component.errors():
                print(error.toString())
        del engine

        # we have to loop through the menu items to set the parent for subitems
        for i in range(0, len(self.menus._menus)):
            menu = self.menus._menus[i]
            for j in range(0, len(menu._items)):
                item = menu._items[j]
                for k in range(len(item._items)):
                    subItem = item._items[k]
                    subItem.setParentItem(item)
コード例 #27
0
ファイル: main.py プロジェクト: vinutah/sandbox
def main(arguments):
    'Main logic'
    app = QCoreApplication([__file__] + arguments)

    # Register the Python type.  Its URI is 'People', it's v1.0, and the type
    # will be called 'Person' in QML.
    qmlRegisterType(Person, 'People', 1, 0, 'Person')

    # Now we can load Person.qml, since it uses our registered python class
    engine = QQmlEngine()
    component = QQmlComponent(engine)
    component.loadUrl(QUrl('Person.qml'))
    person = component.create()

    if person is not None:
        print("The person's name is {0}.".format(person.name))
        print('They wear a size {0} shoe.'.format(person.shoe_size))
    else:
        for error in component.errors():
            print(error.toString())
コード例 #28
0
app = QCoreApplication(sys.argv)

qmlRegisterType(BirthdayPartyAttached)
qmlRegisterType(BirthdayParty,
                "People",
                1,
                0,
                "BirthdayParty",
                attachedProperties=BirthdayPartyAttached)
qmlRegisterType(ShoeDescription)
qmlRegisterType(Person)
qmlRegisterType(Boy, "People", 1, 0, "Boy")
qmlRegisterType(Girl, "People", 1, 0, "Girl")

engine = QQmlEngine()

component = QQmlComponent(engine)
component.setData(QML, QUrl())

party = component.create()

if party is not None and party.host is not None:
    print("\"%s\" is having a birthday!" % party.host.name)

    if isinstance(party.host, Boy):
        print("He is inviting:")
    else:
        print("She is inviting:")

    for guest in party.guests:
コード例 #29
0
ファイル: __init__.py プロジェクト: bgromov/ros_qml
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
コード例 #30
0
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)
コード例 #31
0
ファイル: qmlapp.py プロジェクト: pinnaculum/galacteek
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
コード例 #32
0
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)
コード例 #33
0
    def __init__(self,
                 package_data: Dict[str, Any],
                 section_title: Optional[str] = None,
                 parent: Optional[QObject] = None) -> None:
        """
        Constructs a new model for a single package.
        :param package_data: The data received from the Marketplace API about the package to create.
        :param section_title: If the packages are to be categorized per section provide the section_title
        :param parent: The parent QML object that controls the lifetime of this model (normally a PackageList).
        """
        super().__init__(parent)
        QQmlEngine.setObjectOwnership(self, QQmlEngine.CppOwnership)
        self._package_manager: CuraPackageManager = cast(
            CuraPackageManager,
            CuraApplication.getInstance().getPackageManager())
        self._plugin_registry: PluginRegistry = CuraApplication.getInstance(
        ).getPluginRegistry()

        self._package_id = package_data.get("package_id", "UnknownPackageId")
        self._package_type = package_data.get("package_type", "")
        self._is_bundled = package_data.get("is_bundled", False)
        self._icon_url = package_data.get("icon_url", "")
        self._marketplace_url = package_data.get("marketplace_url", "")
        self._display_name = package_data.get(
            "display_name", catalog.i18nc("@label:property",
                                          "Unknown Package"))
        tags = package_data.get("tags", [])
        self._is_checked_by_ultimaker = (self._package_type == "plugin"
                                         and "verified" in tags) or (
                                             self._package_type == "material"
                                             and "certified" in tags)
        self._package_version = package_data.get(
            "package_version",
            "")  # Display purpose, no need for 'UM.Version'.
        self._package_info_url = package_data.get(
            "website", "")  # Not to be confused with 'download_url'.
        self._download_count = package_data.get("download_count", 0)
        self._description = package_data.get("description", "")
        self._formatted_description = self._format(self._description)

        self._download_url = package_data.get("download_url", "")
        self._release_notes = package_data.get(
            "release_notes",
            "")  # Not used yet, propose to add to description?

        subdata = package_data.get("data", {})
        self._technical_data_sheet = self._findLink(subdata,
                                                    "technical_data_sheet")
        self._safety_data_sheet = self._findLink(subdata, "safety_data_sheet")
        self._where_to_buy = self._findLink(subdata, "where_to_buy")
        self._compatible_printers = self._getCompatiblePrinters(subdata)
        self._compatible_support_materials = self._getCompatibleSupportMaterials(
            subdata)
        self._is_compatible_material_station = self._isCompatibleMaterialStation(
            subdata)
        self._is_compatible_air_manager = self._isCompatibleAirManager(subdata)

        author_data = package_data.get("author", {})
        self._author_name = author_data.get(
            "display_name", catalog.i18nc("@label:property", "Unknown Author"))
        self._author_info_url = author_data.get("website", "")
        if not self._icon_url or self._icon_url == "":
            self._icon_url = author_data.get("icon_url", "")

        self._can_update = False
        self._section_title = section_title
        self.sdk_version = package_data.get("sdk_version_semver", "")
        # Note that there's a lot more info in the package_data than just these specified here.

        self.enablePackageTriggered.connect(self._plugin_registry.enablePlugin)
        self.disablePackageTriggered.connect(
            self._plugin_registry.disablePlugin)

        self._plugin_registry.pluginsEnabledOrDisabledChanged.connect(
            self.stateManageButtonChanged)
        self._package_manager.packageInstalled.connect(
            lambda pkg_id: self._packageInstalled(pkg_id))
        self._package_manager.packageUninstalled.connect(
            lambda pkg_id: self._packageInstalled(pkg_id))
        self._package_manager.packageInstallingFailed.connect(
            lambda pkg_id: self._packageInstalled(pkg_id))
        self._package_manager.packagesWithUpdateChanged.connect(
            self._processUpdatedPackages)

        self._is_busy = False
コード例 #34
0
ファイル: QuickView.py プロジェクト: zkw1995/XwareDesktop
 def __init__(self):
     self.engine = QQmlEngine()
コード例 #35
0
ファイル: __init__.py プロジェクト: tiberium24/ros_qml
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
コード例 #36
0
        # fileMenu.addAction(exitAction)

        toolbar = self.addToolBar('Exit')
        # toolbar.setObjectName('ToolBar')
        # toolbar.addAction(exitAction)
        # toolbar.addAction(processUrlAction)

        self.restoreState()
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    qmlRegisterType(JiraMain, 'JiraTree', 1, 0, 'MainWindow')

    engine = QQmlEngine()
    # Create a component factory and load the QML script.
    component = QQmlComponent(engine)
    component.loadUrl(QUrl.fromLocalFile('main.qml'))
    jm = component.create()
    [print(e.toString()) for e in component.errors()]
    engine.rootContext().setContextProperty("mainWindow", jm)
    if jm is None:
        print("JM is none")
        print({e.toString() for e in component.errors()})

#	ex = JiraMain(None)
    print("Run")
    app.exec()
    print("Exit")
    sys.exit()