Ejemplo n.º 1
0
def run():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()

    engine.load('ui.qml')
    win = engine.rootObjects()[0]

    # testButton = engine.findChild(QObject, "myButton")
    # testButton.messageSend.connect(myfunction)
    # testButton.clicked.connect(myfunction)

    # testitem = engine.findChild(QObject, "butest")
    # testitem.clicked.connect(myfunction)

    buttoning = win.findChild(QObject, "firsttabbutton")
    buttoning.clicked.connect(myfunction)

    # button_text = win.findChild(QObject, "first_tab_border")
    # button_text.opacity = 0

    # testingitem = engine.findChild(QObject, "butesting")
    # testingitem.clicked.connect(myfunction)
    # testingitem.clicked.connect(myfunction)

    if not engine.rootObjects():
        return -1

    return app.exec_()
Ejemplo n.º 2
0
def runQML():
    #view = QQuickView()
    #ui.setupUi(this)
    #container = QWidget.createWindowContainer(view, this)
    #container.setMinimumSize(200, 200)
    #container.setMaximumSize(200, 200)
    app =QApplication(sys.argv)
    engine = QQmlApplicationEngine()
#    app.setWindowIcon(QIcon("icon.png"))
    root = engine.rootContext()
    engine.load('dice/main.qml')
    #ui.verticalLayout.addWidget(container)
    child = engine.rootObjects()[0].findChild(QtCore.QObject, "foo_object")
    #print(str(child))
    child.setProperty("text", "Blödsinn")
    #root.setContextProperty("guisettings", guisettings)



    print(str(len(engine.rootObjects())))
    for w in engine.rootObjects():
        #print(str(type(w.contentItem().childItems()).__name__))
        for v in w.contentItem().childItems():
            print(str(v.setOpacity(0.9)))
            for i,x in enumerate(v.childItems()):
                print(str(x.setOpacity(0.9)))
                x.stackAfter(v.childItems()[-i])




    if not engine.rootObjects():
        return -1

    return app.exec_()
Ejemplo n.º 3
0
def main(filename=None):
    prod = get_prod()
    if not prod:
        QStandardPaths.setTestModeEnabled(True)
    setup_logging()
    logger.info(f"Application en mode {'PROD' if prod else 'DEBUG'}")

    # create de app and initial setup
    app = QApplication([])
    initial_setup_application(app)

    # create database and update configation with default values if needed
    db = main_init_database(filename=filename, prod=prod)
    update_configuration(db)
    add_database_to_types(db)

    # qml
    register_new_qml_type()
    engine = QQmlApplicationEngine()

    # late configuration
    late_setup_application(app, db)

    # run the app
    load_engine(engine)
    sys.exit(app.exec_())
Ejemplo n.º 4
0
def run():
    app = QGuiApplication([])

    engine = QQmlApplicationEngine()
    qmlRegisterType(MainWindow, 'PyMainWindow', 1, 0, 'MainWindow')
    engine.load(QUrl.fromLocalFile("./gui/main/MainWindow.qml"))
    app.exec_()
Ejemplo n.º 5
0
    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()
Ejemplo n.º 6
0
def main():
    app = QGuiApplication([])

    try:
        path = QUrl(sys.argv[1])
    except IndexError:
        print("Usage: pyqmlscene <filename>")
        sys.exit(1)

    engine = QQmlApplicationEngine()

    # Procedure similar to
    # https://github.com/qt/qtdeclarative/blob/0e9ab20b6a41bfd40aff63c9d3e686606e51e798/tools/qmlscene/main.cpp
    component = QQmlComponent(engine)
    component.loadUrl(path)
    root_object = component.create()

    if isinstance(root_object, QQuickWindow):
        # Display window object
        root_object.show()
    elif isinstance(root_object, QQuickItem):
        # Display arbitrary QQuickItems by reloading the source since
        # reparenting the existing root object to the view did not have any
        # effect. Neither does the QQuickView class have a setContent() method
        view = QQuickView(path)
        view.show()
    else:
        raise SystemExit("Error displaying {}".format(root_object))

    sys.exit(app.exec_())
Ejemplo n.º 7
0
def run():
    directory = os.path.dirname(os.path.abspath(__file__))

    appIcon = QIcon()
    appIcon.addFile(os.path.join(directory, "python.png"), QSize(64, 64))
    app.setWindowIcon(appIcon)

    from . import registerQmlTypes

    registerQmlTypes()

    engine = QQmlApplicationEngine()
    context = QQmlContext(engine)

    mainQml = QUrl.fromLocalFile(os.path.join(directory, "Main.qml"))

    component = QQmlComponent(engine)
    component.loadUrl(mainQml)

    if component.isError():
        for error in component.errors():
            print("Error: ", error.toString())

    dialog = component.create(context)

    return app.exec_()
Ejemplo n.º 8
0
    def start(self):
        """Display the GUI"""
        myApp = QApplication(sys.argv)
        sys.excepthook = lambda typ, val, tb: error_handler(typ, val, tb)

        myApp.setOrganizationDomain('mlox')
        myApp.setOrganizationName('mlox')

        icon_data: bytes = resource_manager.resource_string(
            "mlox.static", "mlox.ico")
        icon = QIcon()
        pixmap = QPixmap()
        pixmap.loadFromData(icon_data)
        icon.addPixmap(pixmap)
        myApp.setWindowIcon(icon)

        myEngine = QQmlApplicationEngine()
        # Need to set these before loading
        myEngine.rootContext().setContextProperty("python", self)
        myEngine.addImageProvider('static', PkgResourcesImageProvider())

        qml: bytes = resource_manager.resource_string("mlox.static",
                                                      "window.qml")
        myEngine.loadData(qml)

        # These two are hacks, because getting them in the __init__ and RAII working isn't
        self.debug_window = ScrollableDialog()
        self.clipboard = myApp.clipboard()

        self.analyze_loadorder()

        sys.exit(myApp.exec())
Ejemplo n.º 9
0
 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")
Ejemplo n.º 10
0
def main():
    try:
        base_path = sys._MEIPASS
    except AttributeError:
        base_path = Path(__file__).parent

    # https://github.com/kivy/kivy/issues/4182#issuecomment-471488773
    if 'twisted.internet.reactor' in sys.modules:
        del sys.modules['twisted.internet.reactor']

    qapp = QApplication(sys.argv)
    qapp.setApplicationName("HPOS Seed")
    qapp.setOrganizationDomain("holo.host")
    qapp.setOrganizationName("Holo")

    # qt5reactor needs to be imported and installed after QApplication(),
    # but before importing twisted.internet.reactor. See qt5reactor docs.
    import qt5reactor
    qt5reactor.install()

    from twisted.internet import reactor
    app = App(qapp, reactor)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("app", app)
    engine.load(Path(base_path, 'send_qt.qml').as_uri())

    reactor.run()
Ejemplo n.º 11
0
def main():
    app = QGuiApplication(argv)

    qmlRegisterType(Manager.Manager, 'BTManager', 1, 0, 'BTManager')
    qmlRegisterType(Notifier.Notifier, 'BTNotifier', 1, 0, 'BTNotifier')
    qmlRegisterType(Device.Device, 'Device', 1, 0, 'Device')

    print('Create my device')

    notifier = Notifier.Notifier()
    manager = Manager.Manager()
    manager.set_notifier(notifier)

    print('Bluetooth manager create')

    path = os.path.dirname(__file__)
    print('Detect run path')

    print('Run GUI')
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty('AppPath', path)
    engine.rootContext().setContextProperty('MyDevice', manager.my_device)
    engine.rootContext().setContextProperty('BTManager', manager)
    engine.rootContext().setContextProperty('BTNotifier', notifier)
    engine.load('ui/Main.qml')

    print('Start search for near by devices')
    manager.search(True)

    print('Execute app')
    exit(app.exec_())
Ejemplo n.º 12
0
    def __init__(self, opts, args):
        QGuiApplication.__init__(self, args)
        translator = QTranslator()
        translator.load(QLocale.system().name(), "po")
        self.installTranslator(translator)
        qmlRegisterUncreatableType(
            ReleaseDownload, 'LiveUSB', 1, 0, 'Download',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            ReleaseWriter, 'LiveUSB', 1, 0, 'Writer',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            ReleaseListModel, 'LiveUSB', 1, 0, 'ReleaseModel',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            Release, 'LiveUSB', 1, 0, 'Release',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(
            USBDrive, 'LiveUSB', 1, 0, 'Drive',
            'Not creatable directly, use the liveUSBData instance instead')
        qmlRegisterUncreatableType(LiveUSBData, 'LiveUSB', 1, 0, 'Data',
                                   'Use the liveUSBData root instance')

        engine = QQmlApplicationEngine()
        self.data = LiveUSBData(opts)
        engine.rootContext().setContextProperty('liveUSBData', self.data)
        if (opts.directqml):
            engine.load(QUrl('liveusb/liveusb.qml'))
        else:
            engine.load(QUrl('qrc:/liveusb.qml'))
        engine.rootObjects()[0].show()

        self.exec_()
Ejemplo n.º 13
0
def main():
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # QtWebEngine::initialize()

    if QT_NO_WIDGETS:
        app = QApplication(sys.argv)
    else:
        app = QGuiApplication(sys.argv)

    engine = QQmlApplicationEngine()
    server = Server(engine)

    engine.load(QUrl("qrc:/main.qml"))
    QTimer.singleShot(0, server.run)

    proxy = QNetworkProxy()
    proxy.setType(QNetworkProxy.HttpProxy)
    proxy.setHostName("localhost")
    proxy.setPort(5555)
    QNetworkProxy.setApplicationProxy(proxy)

    sys.exit(app.exec_())
Ejemplo n.º 14
0
def main(blocks=None, angle=None):
    app = QApplication(sys.argv)
    app_engine = QQmlApplicationEngine()
    context = app_engine.rootContext()

    # WARNING: ALL THE ADDIMAGEPROVIDER LINES BELOW ARE REQUIRED TO MAKE
    # WARNING: QML BELIEVE THE PROVIDER IS VALID BEFORE ITS CREATION
    analysis_image_provider = PyplotImageProvider(fig=None)
    app_engine.addImageProvider("analysisprovider", analysis_image_provider)

    win = get_main_window(app_engine)

    detector = DetectionInterface(app,
                                  context,
                                  win,
                                  display_name="detectionGraph",
                                  image_provider=analysis_image_provider,
                                  image_provider_name="analysisprovider")
    context.setContextProperty('py_detector', detector)

    if blocks is not None:
        detector.set_blocks(blocks, angle)

    win.show()
    # detector.detect()  # to display cell 0
    detector.init_ui()
    app.exec_()
Ejemplo n.º 15
0
def run():
    # First set some application settings for QSettings
    QtCore.QCoreApplication.setOrganizationName("QTodoTxt")
    QtCore.QCoreApplication.setApplicationName("QTodoTxt2")
    # Now set up our application and start
    app = QtWidgets.QApplication(sys.argv)
    # it is said, that this is lighter:
    # (without qwidgets, as we probably don't need them anymore, when transition to qml is done)
    # app = QtGui.QGuiApplication(sys.argv)

    name = QtCore.QLocale.system().name()
    translator = QtCore.QTranslator()
    if translator.load(str(name) + ".qm", "..//i18n"):
        app.installTranslator(translator)

    args = _parseArgs()

    setupSingleton(args)

    _setupLogging(args.loglevel)

    engine = QQmlApplicationEngine(parent=app)
    controller = MainController(args)
    engine.rootContext().setContextProperty("mainController", controller)
    path = os.path.join(os.path.dirname(__file__), 'qml')
    engine.addImportPath(path)
    mainqml = os.path.join(path, 'QTodoTxt.qml')
    engine.load(mainqml)

    setupAnotherInstanceEvent(controller)

    controller.start()
    app.setWindowIcon(QtGui.QIcon(":/qtodotxt"))
    app.exec_()
    sys.exit()
def main():
    print('main()')

    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    main_controller = MainController(app)
    context = engine.rootContext()
    context.setContextProperty("main", main_controller)
    script_directory = os.path.dirname(os.path.abspath(__file__))
    engine.load(os.path.join(script_directory, 'qml/main.qml'))

    # hook into SIGINT signal to shutdown the application when commanded
    def sig_int_handler(signal, frame):
        logger.info('SIGINT received')
        main_controller.shutdown()
    signal.signal(signal.SIGINT, sig_int_handler)

    # Python cannot handle signals while the Qt event loop is running
    # So we'll let the python interpreter run periodically so any
    # SIGINT signals can be processed
    timer = QTimer()
    timer.start(500)  # You may change this if you wish.
    timer.timeout.connect(lambda: None)

    main_controller.start()

    sys.exit(app.exec_())
Ejemplo n.º 17
0
    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)
Ejemplo n.º 18
0
def main():
    # Set the QtQuick Style
    # Acceptable values: Default, Fusion, Imagine, Material, Universal.
    os.environ['QT_QUICK_CONTROLS_STYLE'] = sys.argv[1] if len(sys.argv) > 1 else "Imagine"

    # Create an instance of the application
    # QApplication MUST be declared in global scope to avoid segmentation fault
    app = QApplication(sys.argv)

    # Create QML engine
    engine = QQmlApplicationEngine()

    # Load the qml file into the engine
    engine.load(QUrl('qrc:/pyqt5_qtquick2_example/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)
    # For more details and other methods to communicate between Qml and Python:
    #   http://doc.qt.io/archives/qt-4.8/qtbinding.html
    qtquick2Themes = engine.rootObjects()[0].findChild(QObject, 'qtquick2Themes')
    qtquick2Themes.setProperty('text', os.environ['QT_QUICK_CONTROLS_STYLE'])

    # engine.quit.connect(app.quit)
    # Unnecessary,
    # since QQmlEngine.quit has already connect to QCoreApplication.quit

    res = app.exec_()
    # Deleting the view before it goes out of scope is required to make sure all
    # child QML instances are destroyed in the correct order or a segmentation
    # error would occur.
    del engine
    sys.exit(res)
Ejemplo n.º 19
0
def main():
    if os.getuid() != 0:
        print('root permissions needed to launch keylogger')
        return
    no_func_keys = '--no-func-keys' in sys.argv
    if no_func_keys:
        ignored_keys = []
    else:
        ignored_keys = ['<Enter>', '<LShft>', '<#+8>', '<#+18>']

    app = QGuiApplication(sys.argv[:1])

    keypressprovider = KeyPressProvider(ignore_keys=ignored_keys,
                                        no_func_keys=no_func_keys)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("text_provider", keypressprovider)
    engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
    window = engine.rootObjects()[0]
    if not window:
        sys.exit(-1)

    k = keypressprovider.keysPressedChanged

    k.connect(window.setText)
    sys.exit(app.exec_())
Ejemplo n.º 20
0
def main():
    """Shows the GUI for event configuration
    """
    from .Controllers.LoginController import LoginController
    try:
        print('Starting GUI')
        app = QApplication(sys.argv)
        engine = QQmlApplicationEngine()

        controller = Controller(engine)
        loginController = LoginController(controller)
        controller.active_controller_exit_point = loginController._unload

        engine.rootContext().setContextProperty("controller", controller)
        engine.rootContext().setContextProperty("loginController",
                                                loginController)
        engine.load(os.path.join(base_path, 'Views', "main.qml"))

        #component.loadUrl(QUrl(os.path.join(base_path, "main.qml")))

        def hide_all():
            print('hiding all root objects')
            for r in engine.rootObjects():
                r.hide()

        engine.quit.connect(hide_all)
        #engine.quit.connect(app.quit)
        app.exec_()
        print('application ended')
        app = None

    except Exception as ex:
        print(ex)
        pass
Ejemplo n.º 21
0
    def __init__(self):
        self.app = QGuiApplication(sys.argv + ['--style', 'material'])

        fontdatabase = QFontDatabase()
        fontdatabase.addApplicationFont("fonts/Exo2-Regular.ttf")
        exo = QFont("Exo 2", 15)
        self.app.setFont(exo)

        self.engine = QQmlApplicationEngine()
        self.bridge = Bridge(self.app, self.engine)

        #responder a KeyboardInterrupt
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        self.engine.rootContext().setContextProperty("bridge", self.bridge)
        self.engine.load("assets/main.qml")

        listDicts = csvInterpreter.readCSV("components.csv")
        for d in listDicts:
            self.bridge.createComponent(d)

        # self.bridge.updateComponents(bytearray.fromhex('5553501408010401080110011F'))

        self.engine.quit.connect(self.app.quit)
        self.app.exec()
Ejemplo n.º 22
0
def main():
    import sys

    QGuiApplication.setApplicationName("Gallery")
    QGuiApplication.setOrganizationName("QtProject")
    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    app = QGuiApplication(sys.argv)

    QIcon.setThemeName("gallery")

    settings = QSettings()

    style = Fakequickcontrols2.name()
    if style:
        settings.setValue("style", style)
    else:
        Fakequickcontrols2.setStyle(settings.value("style"))

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty(
        "availableStyles", Fakequickcontrols2.availableStyles())
    engine.load(QUrl("qrc:/gallery.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
Ejemplo n.º 23
0
    def start_GUI(self):

        app = QApplication(sys.argv)
        try:

            engine = QQmlApplicationEngine()
            ctx = engine.rootContext()

            ctx.setContextProperty("roscam_main", self)
            engine.load(
                os.path.join(os.path.dirname(__file__),
                             "../../Resources/main.qml"))

            timer = QtCore.QTimer()
            timer.timeout.connect(lambda: None)
            timer.start(100)

            sys.exit(self.Close_fct(app=app, sub=self.application_node))

        except KeyboardInterrupt:
            print("keyboard interupt")
            sys.exit(self.Close_fct(app=app, sub=self.application_node))

        except Exception:
            print("exception")
            sys.exit(self.Close_fct(app=app, sub=self.application_node))
def main():
    argv = sys.argv
    
    # Trick to set the style / not found how to do it in pythonic way
    argv.extend(["-style", "universal"])
    app = QGuiApplication(argv)

    qmlRegisterType(FigureCanvasQTAggToolbar, "Backend", 1, 0, "FigureToolbar")    
    imgProvider = MatplotlibIconProvider()
    
    # !! You must specified the QApplication as parent of QQmlApplicationEngine
    # otherwise a segmentation fault is raised when exiting the app
    engine = QQmlApplicationEngine(parent=app)
    engine.addImageProvider("mplIcons", imgProvider)
    
    context = engine.rootContext()
    data_model = DataSeriesModel()
    context.setContextProperty("dataModel", data_model)
    mainApp = Form(data=data_model)
    context.setContextProperty("draw_mpl", mainApp)
    
    engine.load(QUrl('main.qml'))
    
    win = engine.rootObjects()[0]
    mainApp.figure = win.findChild(QObject, "figure").getFigure()
    
    rc = app.exec_()
    # There is some trouble arising when deleting all the objects here
    # but I have not figure out how to solve the error message.
    # It looks like 'app' is destroyed before some QObject
    sys.exit(rc)
Ejemplo n.º 25
0
def run(torrent_client):
    """
    Start the UI
    """
    app = QApplication(sys.argv)

    app.setOrganizationName("example")
    app.setOrganizationDomain("example.com")

    engine = QQmlApplicationEngine()

    context = engine.rootContext()

    ctx_manager = ContextManager(torrent_client)

    ctx_props = ctx_manager.context_props
    for prop_name in ctx_props:
        context.setContextProperty(prop_name, ctx_props[prop_name])

    qml_file = os.path.join(os.path.dirname(__file__), "views/window.qml")
    engine.load(QUrl.fromLocalFile(os.path.abspath(qml_file)))

    if not engine.rootObjects():
        sys.exit(-1)

    window = engine.rootObjects()[0]
    ctx_manager.set_window(window)

    ret = app.exec_()

    ctx_manager.clean_up()
    sys.exit(ret)
Ejemplo n.º 26
0
def main():
    global app
    # The following command line argument sets the style of the QML app. There is no alternative.
    # Available styles: https://doc.qt.io/qt-5/qtquickcontrols2-styles.html
    sys.argv += ['--style', 'fusion']
    app = QApplication(sys.argv)

    # Make the Data Preprocessor Manager accessible through QML.
    engine = QQmlApplicationEngine()
    context = engine.rootContext()
    dpmanager = DataPreprocessorManager()
    context.setContextProperty('dpManager', dpmanager)
    idsmanager = TwoStageIDSManager()
    context.setContextProperty('idsManager', idsmanager)
    reportmanager = ReportManager()
    context.setContextProperty('reportManager', reportmanager)
    simulationmanager = SimulationManager(idsmanager)
    context.setContextProperty('simManager', simulationmanager)

    baselogmodel = BaseOutputLogModel()
    outputlogmodel = OutputLogModel()
    outputlogmodel.setDynamicSortFilter(True)
    outputlogmodel.setSourceModel(baselogmodel)
    context.setContextProperty('outputLogModel', outputlogmodel)

    context.setContextProperty('excHandler', excHandler)
    # Load the QML file.
    engine.load(os.path.dirname(os.path.abspath(__file__)) + '/gui/main.qml')

    # Run the QML file.
    sys.exit(app.exec_())
Ejemplo n.º 27
0
    def initializeEngine(self) -> None:
        # TODO: Document native/qml import trickery
        self._qml_engine = QQmlApplicationEngine(self)
        self.processEvents()
        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.processEvents()
        self._qml_engine.rootContext().setContextProperty(
            "screenScaleFactor", self._screenScaleFactor())

        self.registerObjects(self._qml_engine)

        Bindings.register()

        # Preload theme. The theme will be loaded on first use, which will incur a ~0.1s freeze on the MainThread.
        # Do it here, while the splash screen is shown. Also makes this freeze explicit and traceable.
        self.getTheme()
        self.processEvents()

        self.showSplashMessage(
            self._i18n_catalog.i18nc("@info:progress", "Loading UI..."))
        self._qml_engine.load(self._main_qml)
        self.engineCreatedSignal.emit()
Ejemplo n.º 28
0
    def __init__(self, argv):
        app = QGuiApplication(argv)
        engine = QQmlApplicationEngine()
        context = engine.rootContext()
        context.setContextProperty('mainWindow',
                                   engine)  # the string can be anything

        engine.load('/Users/hebingchang/QtCreator/sniffer/sniffer.qml')
        self.root = engine.rootObjects()[0]
        self.root.setDevModel(pcap.findalldevs())
        self.dev = pcap.findalldevs()[0]
        self.sniffer_status = False

        # self.root.appendPacketModel({'source': '10.162.31.142', 'destination': '151.101.74.49', 'length': 52, 'id': 1})

        self.packetModel = self.root.findChild(QObject, "packetModel")

        btnStart = self.root.findChild(QObject, "btnStart")
        btnStart.clicked.connect(self.myFunction)  # works too

        self.comboDev = self.root.findChild(QObject, "comboDevice")
        self.comboDev.activated.connect(self.getDev)

        engine.quit.connect(app.quit)
        sys.exit(app.exec_())
Ejemplo n.º 29
0
def main() -> None:
    """Application entry point"""
    # configure logging
    logging.basicConfig(level=logging.INFO)

    # create the App ant the event loop
    app = QGuiApplication(sys.argv + ["--style", QUICK_CONTROLS2_STYLE])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    # register custom types
    register_types()

    # create the QML engine
    engine = QQmlApplicationEngine()
    # set context properties
    engine.rootContext().setContextProperty("version", VERSION)
    engine.rootContext().setContextProperty("author", AUTHOR)
    engine.rootContext().setContextProperty("authorEmail", AUTHOR_EMAIL)
    engine.rootContext().setContextProperty("projectUrl", URL)
    # load the main QML file
    engine.load(MAIN_QML_PATH)

    # start the event loop
    with loop:
        loop.run_forever()
Ejemplo n.º 30
0
def run(app):
    dir_name = os.path.dirname(__file__)
    os.environ['QML_IMPORT_PATH'] = os.path.join(dir_name, 'resources')
    os.environ['QML2_IMPORT_PATH'] = os.path.join(dir_name, 'resources')

    #QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    # Create the application instance.
    #app = QGuiApplication(sys.argv)

    # Create QML engine
    engine = QQmlApplicationEngine()
    context = engine.rootContext()

    # Testor
    manage = ManageThreads()
    context.setContextProperty("manage", manage)

    # Model
    TestorModel = Model()
    manage.runtimeSig.connect(TestorModel.addData)
    context.setContextProperty("TestorModel", TestorModel)

    engine.load(QUrl('src/resources/main.qml'))

    engine.quit.connect(app.quit)
    sys.exit(app.exec_())