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_()
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_())
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_())
class MainWindow(QObject): def __init__(self, parent=None): super().__init__(parent) self.model = MainWindowViewModel(self) self.loginModel = LoginViewModel(self) self.engine = QQmlApplicationEngine(self) self.engine.rootContext().setContextProperty('model', self.model) self.engine.rootContext().setContextProperty('loginModel', self.loginModel) self.engine.quit.connect(parent.quit) self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml')) self.window = self.engine.rootObjects()[0] # wire up logging console self.log = self.window.findChild(QQuickItem, 'log') parent.log_changed.connect(self._log) def show(self): self.window.show() def _log(self, msg): # replace with collections.deque binding(ish)? if self.log.property('lineCount') == LOG_BUFFER_SIZE: line_end = self.log.property('text').find('\n') + 1 self.log.remove(0, line_end) self.log.append(msg)
class SciHubAddSciHubURL(QObject): showWindowAddSciHubURL = pyqtSignal() def __init__(self, conf, parent): super(SciHubAddSciHubURL, self).__init__() self._conf = conf self._parent = parent self._engine = QQmlApplicationEngine() self._engine.load('qrc:/ui/SciHubEVAAddSciHubURL.qml') self._window = self._engine.rootObjects()[0] self._connect() def _connect(self): # Connect QML signals to PyQt slots self._window.addSciHubURL.connect(self.addSciHubURL) # Connect PyQt signals to QML slots self.showWindowAddSciHubURL.connect( self._window.showWindowAddSciHubURL) @pyqtSlot(str) def addSciHubURL(self, url): scihub_available_urls = json.loads( self._conf.get('network', 'scihub_available_urls')) if not url in scihub_available_urls: scihub_available_urls.append(url) self._conf.set('network', 'scihub_available_urls', json.dumps(scihub_available_urls)) self._parent.loadFromConf()
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")
def showError(message): writeSettings("", "") app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.rootContext().setContextProperty("message", message) engine.load(QUrl("qrc:/message.qml")) sys.exit(app.exec())
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_()
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()
class QmlAusgabe(object): def __init__(self, pathToQmlFile="guiTest.qml"): #QML-Engine self.__appEngine = QQmlApplicationEngine() self.__appEngine.load(pathToQmlFile) self.__appWindow = self.__appEngine.rootObjects()[0] self.__rectangle1 = self.__appWindow.findChild(QObject, "Rectangle1") self.__rectangle2 = self.__appWindow.findChild(QObject, "Rectangle2") self.__colorState = False def changeColor(self): if self.__colorState: self.__rectangle1.setProperty("color", "red") self.__rectangle2.setProperty("color", "green") else: self.__rectangle1.setProperty("color", "yellow") self.__rectangle2.setProperty("color", "blue") self.__colorState = not self.__colorState def show(self): self.__appWindow.show()
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)
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_())
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)
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
class MainWindow(QObject): def __init__(self, parent=None): super().__init__(parent) self.log = logging.getLogger(__name__) self._read_settings() self.client = Client(self) if self.remember: self._autologin() self.model = MainWindowViewModel(self) self.loginModel = LoginViewModel(self.client, self.user, self.password, self.remember, self) self.loginModel.panel_visible = not self.remember self.gamesModel = GamesViewModel(self) self.engine = QQmlApplicationEngine(self) self.engine.rootContext().setContextProperty('windowModel', self.model) self.engine.rootContext().setContextProperty('loginModel', self.loginModel) self.engine.rootContext().setContextProperty('contentModel', self.gamesModel) self.engine.quit.connect(parent.quit) self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml')) self.window = self.engine.rootObjects()[0] # wire up logging console self.console = self.window.findChild(QQuickItem, 'console') parent.log_changed.connect(self._log) def show(self): self.window.show() def _read_settings(self): stored = settings.get() stored.beginGroup('login') self.user = stored.value('user') self.password = stored.value('password') self.remember = stored.value('remember') == 'true' stored.endGroup() @async_slot def _autologin(self): try: self.log.info('logging in (auto)...') self.loginModel.logged_in = yield from self.client.login(self.user, self.password) self.log.debug('autologin result: {}'.format(self.loginModel.logged_in)) except Exception as e: self.log.error('autologin failed. {}'.format(e)) @pyqtSlot(str) def _log(self, msg): # replace with collections.deque binding(ish)? if self.console.property('lineCount') == LOG_BUFFER_SIZE: line_end = self.console.property('text').find('\n') + 1 self.console.remove(0, line_end) self.console.append(msg)
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_())
class UTools(): # Class used with UApp class. def __init__(self): # Constructor of the class self.us1 = "QML with Python." # with informative string. def u_qml(self): # Function displays QML app. self.qwid = QQmlApplicationEngine() # Create application engine. self.qwid.load(QUrl('u_qml.qml')) # Load URL of the QML file.
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")
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_()
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_())
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()
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()
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)
class App(): 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()
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_())
def run(): app = QGuiApplication([]) engine = QQmlApplicationEngine() qmlRegisterType(MainWindow, 'PyMainWindow', 1, 0, 'MainWindow') engine.load(QUrl.fromLocalFile("./gui/main/MainWindow.qml")) app.exec_()
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))
class UTools(): # Creation of the Python class. def __init__(self): # Constructor of the class. self.us1 = "QML with Python." def u_qml(self): self.qwid = QQmlApplicationEngine() self.qwid.load(QUrl('u_qml.qml'))
def main(): app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() controller = MyPersonalViewController() schema = [ QByteArray(str.encode("index")), QByteArray(str.encode("dog")), QByteArray(str.encode("thirdValue")), ] michael = Dog("Michael", 23) philipp = Dog("Philipp", 18) listOfDogs = DogList(schema) items = [ { QByteArray(str.encode("index")): "test1", QByteArray(str.encode("dog")): michael.name, QByteArray(str.encode("thirdValue")): michael.age }, { QByteArray(str.encode("index")): "test2", QByteArray(str.encode("dog")): philipp.name, QByteArray(str.encode("thirdValue")): philipp.age, } ] for item in items: listOfDogs.append(item) engine.rootContext().setContextProperty("pyModel", listOfDogs) engine.rootContext().setContextProperty("controller", controller) engine.load(QUrl('view.qml')) engine.quit.connect(app.quit) sys.exit(app.exec_())
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_())
class SciHubCaptcha(QObject): showWindowCaptcha = pyqtSignal(str) def __init__(self, parent, log=None): super(SciHubCaptcha, self).__init__() self._parent = parent self.log = log self._engine = QQmlApplicationEngine() self._engine.load('qrc:/ui/SciHubEVACaptcha.qml') self._window = self._engine.rootObjects()[0] self._connect() def _connect(self): # Connect QML signals to PyQt slots self._window.killCaptcha.connect(self.killCaptcha) # Connect PyQt signals to QML slots self.showWindowCaptcha.connect(self._window.showWindowCaptcha) @pyqtSlot(bool, str) def killCaptcha(self, kill, captcha): if kill: self._parent.rampageWithCaptchar(captcha) else: self.log(self.tr('Battle canceled, rampage again?'), 'ERROR') self._parent.afterRampage.emit()
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_())
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()
class SnowflakeUI: def __init__(self, qmlfile, gamesdb): self.engine = QQmlApplicationEngine() self.games_db = gamesdb self.root_qml = qmlfile self.platformsListModel = self._load_platforms() self.gamesListModel = self._load_games() def init_ui(self): self.engine.load(QUrl(self.root_qml)) def show(self): raise NotImplementedError def get_root(self): raise NotImplementedError def _load_games(self): gameslist = {} keys = Loadables.Instance().platforms.keys() for platform in keys: games = self.games_db.get_games_for_platform(platform) gameslist[platform] = qml_games.RunnableGamesListModel(sorted((qml_games.RunnableGameWrapper(game) for game in games), key=lambda game: game.game.gameinfo.title)) return gameslist def _load_platforms(self): return qml_platforms.PlatformsListModel(sorted((qml_platforms.PlatformsWrapper(platform_info) for platform_info in iter(Loadables.Instance().platforms.values())), key = lambda platform: platform.platform_id))
class AboutWindow: QML_FILE = "qml/AboutWindow.qml" def __init__(self): # Create window from QML via QQmlApplicationEngine self.engine = QQmlApplicationEngine() self.engine.load(self.QML_FILE) self.window = self.engine.rootObjects()[0]
def main(): print("start") app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.load(QUrl("main.qml")) engine.rootObjects()[0].show() sys.exit(app.exec_())
def startgui(): app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.load(QUrl("qrc:/asserts/gui.qml")) classifier = Classifier(engine, SRCFaceClassifier(DALMSolver())) classifier.run() return app.exec_()
def main(): app = QGuiApplication(sys.argv) qmlRegisterType(MainController, 'MainController', 1, 0, 'MainController') qmlRegisterType(ProfileViewModel, 'ProfileViewModel', 1, 0, 'ProfileViewModel') engine = QQmlApplicationEngine() main_controller = MainController() main_controller.profile_selection_changed(0) engine.rootContext().setContextProperty('mainController', main_controller) engine.load(QUrl.fromLocalFile(pkg_resources.resource_filename('yarg.resource', 'main.qml'))) sys.exit(app.exec_())
class PDFxGui: QML_FILE = "qml/MainWindow.qml" window = None threads = [] pdf_windows = [] def __init__(self): self.threads = [] # Create and setup window self.engine = QQmlApplicationEngine() self.engine.load(self.QML_FILE) self.window = self.engine.rootObjects()[0] # Connect signals self.window.signalOpenPdfs.connect(self.open_pdf) self.window.signalShowAboutWindow.connect(show_about_window) def open_pdf(self, urls): num_pdfs = urls.property("length").toInt() pdf_urls = [urls.property(index).toString() for index in range(num_pdfs)] if len(pdf_urls) == 0: return def signal_item_start(uri): print("started:", uri) self.window.setStatusText("Opening %s..." % (os.path.basename(uri))) def signal_item_finished(uri): print("finished:", uri) win = PdfDetailWindow(uri) win.window.show() self.pdf_windows.append(win) def signal_item_error(uri, error): print("error:", uri, error) def signal_item_extract_page(uri, curpage): print("page:", curpage) self.window.setStatusText("Reading page %s of %s..." % (curpage, os.path.basename(uri))) def signal_finished(): print("all finished") self.window.setState("") self.window.setStatusText("") self.window.setState("busy") open_thread = OpenPdfQThread(pdf_urls) open_thread.signal_item_start.connect(signal_item_start) open_thread.signal_item_extract_page.connect(signal_item_extract_page) open_thread.signal_item_finished.connect(signal_item_finished) open_thread.signal_item_error.connect(signal_item_error) open_thread.signal_finished.connect(signal_finished) open_thread.start() self.threads.append(open_thread)
class Application(QApplication): def __init__(self, argv): super(Application, self).__init__(argv) stderrHandler = logging.StreamHandler(stream=sys.stderr) stderrHandler.setLevel(logging.WARN) stdoutHandler = logging.StreamHandler(stream=sys.stdout) stdoutHandler.setLevel(logging.INFO) stdoutHandler.filter = lambda rec: rec.levelno <= stdoutHandler.level logging.basicConfig( format='%(name)-15s %(message)s', level=logging.INFO, handlers=[stderrHandler, stdoutHandler] ) logger.info("__init__") self._qml_engine = QQmlApplicationEngine() self._root_context = self._qml_engine.rootContext() self.char = Character(self) def setContext(self, name, value): self._root_context.setContextProperty(name, value) def start(self): logger.info("start") self.setContext('character', self.char) self.readModels() self._qml_engine.load(QUrl("qrc:/ui/main.qml")) def readModels(self): logger.info("readModels") modelTypes = [ MODEL.Perk, MODEL.Quirk, MODEL.Species ] allDelayedInits = {} for modelType in modelTypes: delayedInits = [] logger.info("parsing model %s", modelType.__name__) g = modelParsers.parse(modelType, delayedInits=delayedInits) allDelayedInits[modelType] = delayedInits model = list(g) # TODO name = "%sModel" % modelType.__name__ assert model is not None, "failed to parse {0}".format(modelType.__name__) self.setContext(name, model) for modelType, delayedInits in allDelayedInits.items(): logger.info("delayed init model %s (%s)", modelType.__name__, len(delayedInits)) for delayedInit in delayedInits: delayedInit() def exec(self): logger.info("exec") super().exec()
def main(argv=None): if not argv: argv = sys.argv app = QApplication(argv) # register own type qmlRegisterType(QmlController, 'QmlController', 1, 0, 'QmlController') engine = QQmlApplicationEngine(app) engine.load(QUrl('main.qml')) return app.exec_()
class PixelWall(QApplication): def __init__(self, *args, **kwargs): super(PixelWall, self).__init__(*args, **kwargs) self.engine = QQmlApplicationEngine(self) self.servers = ServerModel(self.engine) self.settings = QSettings('OpenServices', 'PixelWall') url = self.settings.value('server/url') self.engine.setNetworkAccessManagerFactory(NetworkAccessManagerFactory('hetzner.fladi.at', 3128)) ctxt = self.engine.rootContext() ctxt.setContextProperty('app', self) ctxt.setContextProperty('url', 'about:blank') self.engine.load(QUrl('states.qml')) discoverer = Avahi(self.engine, '_pixelwall._tcp') discoverer.initialized.connect(self.serverState) discoverer.added.connect(self.servers.addService) ctxt.setContextProperty('serverModel', self.servers) discoverer.run() if url: self.setUrl(url) self.setState('Web') def setState(self, state): for root in self.engine.rootObjects(): node = root.findChild(QObject, 'main') if node: logger.info('Setting state: {}'.format(state)) node.setProperty('state', state) def setUrl(self, url): logger.info('Connecting WebView to {}'.format(url)) ctxt = self.engine.rootContext() ctxt.setContextProperty('url', 'https://www.heise.de/') @pyqtSlot() def reset(self): self.settings.remove('server/url') self.setState('Servers') @pyqtSlot(int) def serverSelected(self, index): server = self.servers.getIndex(index) logger.info('Server selected {}'.format(server)) url = 'https://{server.host}:{server.port}/'.format(server=server) self.settings.setValue('server/url', url) self.setUrl(url) self.setState('Web') @pyqtSlot() def serverState(self): self.setState('Servers')
class SmartControlApplication(QGuiApplication): _instance = None WINDOW_ICON = "smart-control.png" DEFAULT_THEME = "default" MAIN_QML = "main.qml" def __init__(self, **kwargs): if sys.platform == "win32": if hasattr(sys, "frozen"): QCoreApplication.addLibraryPath(os.path.join(os.path.abspath(os.path.dirname(sys.executable)), "PyQt5", "plugins")) else: import site for dir in site.getsitepackages(): QCoreApplication.addLibraryPath(os.path.join(dir, "PyQt5", "plugins")) super().__init__(sys.argv, **kwargs) self.setApplicationVersion(version) self._engine = QQmlApplicationEngine() self._internationalization = Internationalization() self._theme = Theme() self._printerConnectionManager = PrinterConnectionManager() @classmethod def instance(cls): if SmartControlApplication._instance is None: SmartControlApplication._instance = cls() return SmartControlApplication._instance def run(self): self._internationalization.load(locale.getdefaultlocale()[0]) self._theme.load(SmartControlApplication.DEFAULT_THEME) self._printerConnectionManager.start() self.aboutToQuit.connect(self._onClose) self.setWindowIcon(QIcon(Resources.icon(SmartControlApplication.WINDOW_ICON))) Binder(self._internationalization, self._theme, self._printerConnectionManager).register() self._engine = QQmlApplicationEngine() if sys.platform == "win32": self._engine.addImportPath(os.path.join(os.path.abspath(os.path.dirname(sys.executable)), "qml")) self._engine.load(Resources.qml(SmartControlApplication.MAIN_QML)) sys.exit(self.exec_()) def _onClose(self): self._printerConnectionManager.stop()
class MyApp(QObject): def __init__(self, qml, set_context=None): super().__init__() self.app = QApplication(sys.argv) self.engine = QQmlApplicationEngine(self) self.root_context = self.engine.rootContext() if set_context: set_context(self.root_context) self.engine.load(QUrl(qml)) self.root_view = self.engine.rootObjects()[0] @staticmethod def run(my_app): my_app.root_view.show() return my_app.app.exec_()
class Application: organization = 'pisak' name = 'pisak' def __init__(self, gui): self._app = QApplication(sys.argv) self._app.setOrganizationName(self.organization) self._app.setApplicationName(self.name) self._context = _ApplicationContext() self._engine = QQmlApplicationEngine() self._engine.rootContext().setContextProperty('pisak', self._context) self._engine.load(gui) def run(self): sys.exit(self._app.exec_())
def main(argv): signal.signal(signal.SIGINT, signal.SIG_DFL) qapp = QGuiApplication([]) engine = QQmlApplicationEngine() data_list = [] for entry in os.scandir(argv[1]): url = "file://" + urllib.parse.quote(os.path.abspath(entry.path)) digest = hashlib.md5(os.fsencode(url)).hexdigest() result = os.path.join(xdg.BaseDirectory.xdg_cache_home, "thumbnails", "normal", digest + ".png") data_list.append(Foo(entry.name, result, "2018-01-11T19:20")) engine.load(QUrl('main.qml')) ctxt = engine.rootContext() ctxt.setContextProperty("menu2", QVariant(data_list)) win = engine.rootObjects()[0] win.show() sys.exit(qapp.exec())
class QtApplication(QApplication, Application, SignalEmitter): def __init__(self, **kwargs): plugin_path = "" if sys.platform == "win32": plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins") Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) elif sys.platform == "darwin": plugin_path = os.path.join(Application.getInstallPrefix(), "Resources", "plugins") if plugin_path: Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) os.environ["QSG_RENDER_LOOP"] = "basic" super().__init__(sys.argv, **kwargs) self._main_qml = "main.qml" self._engine = None self._renderer = None try: self._splash = QSplashScreen(QPixmap(Resources.getPath(Resources.ImagesLocation, self.getApplicationName() + ".png"))) except FileNotFoundError: self._splash = None else: self._splash.show() self.processEvents() signal.signal(signal.SIGINT, signal.SIG_DFL) # This is done here as a lot of plugins require a correct gl context. If you want to change the framework, # these checks need to be done in your <framework>Application.py class __init__(). i18n_catalog = i18nCatalog("uranium") self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading plugins...")) self._loadPlugins() self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading machines...")) self.loadMachines() self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading preferences...")) try: file = Resources.getPath(Resources.PreferencesLocation, self.getApplicationName() + ".cfg") Preferences.getInstance().readFromFile(file) except FileNotFoundError: pass self._translators = {} self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading translations...")) self.loadQtTranslation("uranium_qt") self.loadQtTranslation(self.getApplicationName() + "_qt") def run(self): pass def hideMessage(self, message): with self._message_lock: if message in self._visible_messages: self._visible_messages.remove(message) self.visibleMessageRemoved.emit(message) def showMessage(self, message): with self._message_lock: if message not in self._visible_messages: self._visible_messages.append(message) message.setTimer(QTimer()) self.visibleMessageAdded.emit(message) pass def setMainQml(self, path): self._main_qml = path def initializeEngine(self): # TODO: Document native/qml import trickery Bindings.register() self._engine = QQmlApplicationEngine() self.engineCreatedSignal.emit() self._engine.addImportPath(os.path.join(os.path.dirname(sys.executable), "qml")) self._engine.addImportPath(os.path.join(Application.getInstallPrefix(), "Resources", "qml")) if not hasattr(sys, "frozen"): self._engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml")) self.registerObjects(self._engine) self._engine.load(self._main_qml) engineCreatedSignal = Signal() def registerObjects(self, engine): pass def getRenderer(self): if not self._renderer: self._renderer = QtGL2Renderer() return self._renderer # Overridden from QApplication::setApplicationName to call our internal setApplicationName def setApplicationName(self, name): Application.setApplicationName(self, name) # Handle a function that should be called later. def functionEvent(self, event): e = _QtFunctionEvent(event) QCoreApplication.postEvent(self, e) # Handle Qt events def event(self, event): if event.type() == _QtFunctionEvent.QtFunctionEvent: event._function_event.call() return True return super().event(event) def windowClosed(self): self.getBackend().close() self.quit() self.saveMachines() Preferences.getInstance().writeToFile(Resources.getStoragePath(Resources.PreferencesLocation, self.getApplicationName() + ".cfg")) ## Load a Qt translation catalog. # # This method will locate, load and install a Qt message catalog that can be used # by Qt's translation system, like qsTr() in QML files. # # \param file The file name to load, without extension. It will be searched for in # the i18nLocation Resources directory. If it can not be found a warning # will be logged but no error will be thrown. # \param language The language to load translations for. This can be any valid language code # or 'default' in which case the language is looked up based on system locale. # If the specified language can not be found, this method will fall back to # loading the english translations file. # # \note When `language` is `default`, the language to load can be changed with the # environment variable "LANGUAGE". def loadQtTranslation(self, file, language = "default"): #TODO Add support for specifying a language from preferences path = None if language == "default": # If we have a language set in the environment, try and use that. lang = os.getenv("LANGUAGE") if lang: try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: path = None # If looking up the language from the enviroment fails, try and use Qt's system locale instead. if not path: locale = QLocale.system() # First, try and find a directory for any of the provided languages for lang in locale.uiLanguages(): try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: break # If that fails, see if we can extract a language "class" from the # preferred language. This will turn "en-GB" into "en" for example. if not path: lang = locale.uiLanguages()[0] lang = lang[0:lang.find("-")] try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: path = Resources.getPath(Resources.i18nLocation, language, "LC_MESSAGES", file + ".qm") # If all else fails, fall back to english. if not path: Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file)) try: path = Resources.getPath(Resources.i18nLocation, "en", "LC_MESSAGES", file + ".qm") except FileNotFoundError: Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file) return # Store a reference to the translator. # This prevents the translator from being destroyed before Qt has a chance to use it. self._translators[file] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator) ## Display text on the splash screen. def showSplashMessage(self, message): if self._splash: self._splash.showMessage(message , Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() ## Close the splash screen after the application has started. def closeSplash(self): if self._splash: self._splash.close() self._splash = None
class QtApplication(QApplication, Application): pluginsLoaded = Signal() applicationRunning = Signal() def __init__(self, tray_icon_name: str = None, **kwargs) -> None: plugin_path = "" if sys.platform == "win32": if hasattr(sys, "frozen"): plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins") Logger.log("i", "Adding QT5 plugin path: %s", plugin_path) QCoreApplication.addLibraryPath(plugin_path) else: import site for sitepackage_dir in site.getsitepackages(): QCoreApplication.addLibraryPath(os.path.join(sitepackage_dir, "PyQt5", "plugins")) elif sys.platform == "darwin": plugin_path = os.path.join(self.getInstallPrefix(), "Resources", "plugins") if plugin_path: Logger.log("i", "Adding QT5 plugin path: %s", plugin_path) QCoreApplication.addLibraryPath(plugin_path) # use Qt Quick Scene Graph "basic" render loop os.environ["QSG_RENDER_LOOP"] = "basic" super().__init__(sys.argv, **kwargs) # type: ignore self._qml_import_paths = [] #type: List[str] self._main_qml = "main.qml" #type: str self._qml_engine = None #type: Optional[QQmlApplicationEngine] self._main_window = None #type: Optional[MainWindow] self._tray_icon_name = tray_icon_name #type: Optional[str] self._tray_icon = None #type: Optional[str] self._tray_icon_widget = None #type: Optional[QSystemTrayIcon] self._theme = None #type: Optional[Theme] self._renderer = None #type: Optional[QtRenderer] self._job_queue = None #type: Optional[JobQueue] self._version_upgrade_manager = None #type: Optional[VersionUpgradeManager] self._is_shutting_down = False #type: bool self._recent_files = [] #type: List[QUrl] self._configuration_error_message = None #type: Optional[ConfigurationErrorMessage] def addCommandLineOptions(self) -> None: super().addCommandLineOptions() # This flag is used by QApplication. We don't process it. self._cli_parser.add_argument("-qmljsdebugger", help = "For Qt's QML debugger compatibility") def initialize(self) -> None: super().initialize() # Initialize the package manager to remove and install scheduled packages. self._package_manager = self._package_manager_class(self, parent = self) self._mesh_file_handler = MeshFileHandler(self) #type: MeshFileHandler self._workspace_file_handler = WorkspaceFileHandler(self) #type: WorkspaceFileHandler # Remove this and you will get Windows 95 style for all widgets if you are using Qt 5.10+ self.setStyle("fusion") self.setAttribute(Qt.AA_UseDesktopOpenGL) major_version, minor_version, profile = OpenGLContext.detectBestOpenGLVersion() if major_version is None and minor_version is None and profile is None and not self.getIsHeadLess(): Logger.log("e", "Startup failed because OpenGL version probing has failed: tried to create a 2.0 and 4.1 context. Exiting") QMessageBox.critical(None, "Failed to probe OpenGL", "Could not probe OpenGL. This program requires OpenGL 2.0 or higher. Please check your video card drivers.") sys.exit(1) else: opengl_version_str = OpenGLContext.versionAsText(major_version, minor_version, profile) Logger.log("d", "Detected most suitable OpenGL context version: %s", opengl_version_str) if not self.getIsHeadLess(): OpenGLContext.setDefaultFormat(major_version, minor_version, profile = profile) self._qml_import_paths.append(os.path.join(os.path.dirname(sys.executable), "qml")) self._qml_import_paths.append(os.path.join(self.getInstallPrefix(), "Resources", "qml")) Logger.log("i", "Initializing job queue ...") self._job_queue = JobQueue() self._job_queue.jobFinished.connect(self._onJobFinished) Logger.log("i", "Initializing version upgrade manager ...") self._version_upgrade_manager = VersionUpgradeManager(self) def startSplashWindowPhase(self) -> None: super().startSplashWindowPhase() self._package_manager.initialize() # Read preferences here (upgrade won't work) to get the language in use, so the splash window can be shown in # the correct language. try: preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg") self._preferences.readFromFile(preferences_filename) except FileNotFoundError: Logger.log("i", "Preferences file not found, ignore and use default language '%s'", self._default_language) signal.signal(signal.SIGINT, signal.SIG_DFL) # This is done here as a lot of plugins require a correct gl context. If you want to change the framework, # these checks need to be done in your <framework>Application.py class __init__(). i18n_catalog = i18nCatalog("uranium") self._configuration_error_message = ConfigurationErrorMessage(self, i18n_catalog.i18nc("@info:status", "Your configuration seems to be corrupt."), lifetime = 0, title = i18n_catalog.i18nc("@info:title", "Configuration errors") ) # Remove, install, and then loading plugins self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Loading plugins...")) # Remove and install the plugins that have been scheduled self._plugin_registry.initializeBeforePluginsAreLoaded() self._loadPlugins() self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) self.pluginsLoaded.emit() self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Updating configuration...")) with self._container_registry.lockFile(): VersionUpgradeManager.getInstance().upgrade() # Load preferences again because before we have loaded the plugins, we don't have the upgrade routine for # the preferences file. Now that we have, load the preferences file again so it can be upgraded and loaded. try: preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg") with open(preferences_filename, "r", encoding = "utf-8") as f: serialized = f.read() # This performs the upgrade for Preferences self._preferences.deserialize(serialized) self._preferences.setValue("general/plugins_to_remove", "") self._preferences.writeToFile(preferences_filename) except FileNotFoundError: Logger.log("i", "The preferences file cannot be found, will use default values") # Force the configuration file to be written again since the list of plugins to remove maybe changed self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Loading preferences...")) try: self._preferences_filename = Resources.getPath(Resources.Preferences, self._app_name + ".cfg") self._preferences.readFromFile(self._preferences_filename) except FileNotFoundError: Logger.log("i", "The preferences file '%s' cannot be found, will use default values", self._preferences_filename) self._preferences_filename = Resources.getStoragePath(Resources.Preferences, self._app_name + ".cfg") # FIXME: This is done here because we now use "plugins.json" to manage plugins instead of the Preferences file, # but the PluginRegistry will still import data from the Preferences files if present, such as disabled plugins, # so we need to reset those values AFTER the Preferences file is loaded. self._plugin_registry.initializeAfterPluginsAreLoaded() # Check if we have just updated from an older version self._preferences.addPreference("general/last_run_version", "") last_run_version_str = self._preferences.getValue("general/last_run_version") if not last_run_version_str: last_run_version_str = self._version last_run_version = Version(last_run_version_str) current_version = Version(self._version) if last_run_version < current_version: self._just_updated_from_old_version = True self._preferences.setValue("general/last_run_version", str(current_version)) self._preferences.writeToFile(self._preferences_filename) # Preferences: recent files self._preferences.addPreference("%s/recent_files" % self._app_name, "") file_names = self._preferences.getValue("%s/recent_files" % self._app_name).split(";") for file_name in file_names: if not os.path.isfile(file_name): continue self._recent_files.append(QUrl.fromLocalFile(file_name)) if not self.getIsHeadLess(): # Initialize System tray icon and make it invisible because it is used only to show pop up messages self._tray_icon = None if self._tray_icon_name: self._tray_icon = QIcon(Resources.getPath(Resources.Images, self._tray_icon_name)) self._tray_icon_widget = QSystemTrayIcon(self._tray_icon) self._tray_icon_widget.setVisible(False) def initializeEngine(self) -> None: # TODO: Document native/qml import trickery self._qml_engine = QQmlApplicationEngine(self) self._qml_engine.setOutputWarningsToStandardError(False) self._qml_engine.warnings.connect(self.__onQmlWarning) for path in self._qml_import_paths: self._qml_engine.addImportPath(path) if not hasattr(sys, "frozen"): self._qml_engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml")) self._qml_engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR) self._qml_engine.rootContext().setContextProperty("screenScaleFactor", self._screenScaleFactor()) self.registerObjects(self._qml_engine) Bindings.register() self._qml_engine.load(self._main_qml) self.engineCreatedSignal.emit() recentFilesChanged = pyqtSignal() @pyqtProperty("QVariantList", notify=recentFilesChanged) def recentFiles(self) -> List[QUrl]: return self._recent_files def _onJobFinished(self, job: Job) -> None: if isinstance(job, WriteFileJob): if not job.getResult() or not job.getAddToRecentFiles(): # For a write file job, if it failed or it doesn't need to be added to the recent files list, we do not # add it. return elif (not isinstance(job, ReadMeshJob) and not isinstance(job, ReadFileJob)) or not job.getResult(): return if isinstance(job, (ReadMeshJob, ReadFileJob, WriteFileJob)): self.addFileToRecentFiles(job.getFileName()) def addFileToRecentFiles(self, file_name: str) -> None: file_path = QUrl.fromLocalFile(file_name) if file_path in self._recent_files: self._recent_files.remove(file_path) self._recent_files.insert(0, file_path) if len(self._recent_files) > 10: del self._recent_files[10] pref = "" for path in self._recent_files: pref += path.toLocalFile() + ";" self.getPreferences().setValue("%s/recent_files" % self.getApplicationName(), pref) self.recentFilesChanged.emit() def run(self) -> None: super().run() def hideMessage(self, message: Message) -> None: with self._message_lock: if message in self._visible_messages: message.hide(send_signal = False) # we're in handling hideMessageSignal so we don't want to resend it self._visible_messages.remove(message) self.visibleMessageRemoved.emit(message) def showMessage(self, message: Message) -> None: with self._message_lock: if message not in self._visible_messages: self._visible_messages.append(message) message.setLifetimeTimer(QTimer()) message.setInactivityTimer(QTimer()) self.visibleMessageAdded.emit(message) # also show toast message when the main window is minimized self.showToastMessage(self._app_name, message.getText()) def _onMainWindowStateChanged(self, window_state: int) -> None: if self._tray_icon and self._tray_icon_widget: visible = window_state == Qt.WindowMinimized self._tray_icon_widget.setVisible(visible) # Show toast message using System tray widget. def showToastMessage(self, title: str, message: str) -> None: if self.checkWindowMinimizedState() and self._tray_icon_widget: # NOTE: Qt 5.8 don't support custom icon for the system tray messages, but Qt 5.9 does. # We should use the custom icon when we switch to Qt 5.9 self._tray_icon_widget.showMessage(title, message) def setMainQml(self, path: str) -> None: self._main_qml = path def exec_(self, *args: Any, **kwargs: Any) -> None: self.applicationRunning.emit() super().exec_(*args, **kwargs) @pyqtSlot() def reloadQML(self) -> None: # only reload when it is a release build if not self.getIsDebugMode(): return if self._qml_engine and self._theme: self._qml_engine.clearComponentCache() self._theme.reload() self._qml_engine.load(self._main_qml) # Hide the window. For some reason we can't close it yet. This needs to be done in the onComponentCompleted. for obj in self._qml_engine.rootObjects(): if obj != self._qml_engine.rootObjects()[-1]: obj.hide() @pyqtSlot() def purgeWindows(self) -> None: # Close all root objects except the last one. # Should only be called by onComponentCompleted of the mainWindow. if self._qml_engine: for obj in self._qml_engine.rootObjects(): if obj != self._qml_engine.rootObjects()[-1]: obj.close() @pyqtSlot("QList<QQmlError>") def __onQmlWarning(self, warnings: List[QQmlError]) -> None: for warning in warnings: Logger.log("w", warning.toString()) engineCreatedSignal = Signal() def isShuttingDown(self) -> bool: return self._is_shutting_down def registerObjects(self, engine) -> None: #type: ignore #Don't type engine, because the type depends on the platform you're running on so it always gives an error somewhere. engine.rootContext().setContextProperty("PluginRegistry", PluginRegistry.getInstance()) def getRenderer(self) -> QtRenderer: if not self._renderer: self._renderer = QtRenderer() return cast(QtRenderer, self._renderer) mainWindowChanged = Signal() def getMainWindow(self) -> Optional[MainWindow]: return self._main_window def setMainWindow(self, window: MainWindow) -> None: if window != self._main_window: if self._main_window is not None: self._main_window.windowStateChanged.disconnect(self._onMainWindowStateChanged) self._main_window = window if self._main_window is not None: self._main_window.windowStateChanged.connect(self._onMainWindowStateChanged) self.mainWindowChanged.emit() def setVisible(self, visible: bool) -> None: if self._main_window is not None: self._main_window.visible = visible @property def isVisible(self) -> bool: if self._main_window is not None: return self._main_window.visible #type: ignore #MyPy doesn't realise that self._main_window cannot be None here. return False def getTheme(self) -> Optional[Theme]: if self._theme is None: if self._qml_engine is None: Logger.log("e", "The theme cannot be accessed before the engine is initialised") return None self._theme = UM.Qt.Bindings.Theme.Theme.getInstance(self._qml_engine) return self._theme # Handle a function that should be called later. def functionEvent(self, event: QEvent) -> None: e = _QtFunctionEvent(event) QCoreApplication.postEvent(self, e) # Handle Qt events def event(self, event: QEvent) -> bool: if event.type() == _QtFunctionEvent.QtFunctionEvent: event._function_event.call() return True return super().event(event) def windowClosed(self, save_data: bool = True) -> None: Logger.log("d", "Shutting down %s", self.getApplicationName()) self._is_shutting_down = True # garbage collect tray icon so it gets properly closed before the application is closed self._tray_icon_widget = None if save_data: try: self.savePreferences() except Exception as e: Logger.log("e", "Exception while saving preferences: %s", repr(e)) try: self.applicationShuttingDown.emit() except Exception as e: Logger.log("e", "Exception while emitting shutdown signal: %s", repr(e)) try: self.getBackend().close() except Exception as e: Logger.log("e", "Exception while closing backend: %s", repr(e)) if self._tray_icon_widget: self._tray_icon_widget.deleteLater() self.quit() def checkWindowMinimizedState(self) -> bool: if self._main_window is not None and self._main_window.windowState() == Qt.WindowMinimized: return True else: return False ## Get the backend of the application (the program that does the heavy lifting). # The backend is also a QObject, which can be used from qml. @pyqtSlot(result = "QObject*") def getBackend(self) -> Backend: return self._backend ## Property used to expose the backend # It is made static as the backend is not supposed to change during runtime. # This makes the connection between backend and QML more reliable than the pyqtSlot above. # \returns Backend \type{Backend} @pyqtProperty("QVariant", constant = True) def backend(self) -> Backend: return self.getBackend() ## Create a class variable so we can manage the splash in the CrashHandler dialog when the Application instance # is not yet created, e.g. when an error occurs during the initialization splash = None # type: Optional[QSplashScreen] def createSplash(self) -> None: if not self.getIsHeadLess(): try: QtApplication.splash = self._createSplashScreen() except FileNotFoundError: QtApplication.splash = None else: if QtApplication.splash: QtApplication.splash.show() self.processEvents() ## Display text on the splash screen. def showSplashMessage(self, message: str) -> None: if not QtApplication.splash: self.createSplash() if QtApplication.splash: QtApplication.splash.showMessage(message, Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() elif self.getIsHeadLess(): Logger.log("d", message) ## Close the splash screen after the application has started. def closeSplash(self) -> None: if QtApplication.splash: QtApplication.splash.close() QtApplication.splash = None ## Create a QML component from a qml file. # \param qml_file_path: The absolute file path to the root qml file. # \param context_properties: Optional dictionary containing the properties that will be set on the context of the # qml instance before creation. # \return None in case the creation failed (qml error), else it returns the qml instance. # \note If the creation fails, this function will ensure any errors are logged to the logging service. def createQmlComponent(self, qml_file_path: str, context_properties: Dict[str, "QObject"] = None) -> Optional["QObject"]: if self._qml_engine is None: # Protect in case the engine was not initialized yet return None path = QUrl.fromLocalFile(qml_file_path) component = QQmlComponent(self._qml_engine, path) result_context = QQmlContext(self._qml_engine.rootContext()) #type: ignore #MyPy doens't realise that self._qml_engine can't be None here. if context_properties is not None: for name, value in context_properties.items(): result_context.setContextProperty(name, value) result = component.create(result_context) for err in component.errors(): Logger.log("e", str(err.toString())) if result is None: return None # We need to store the context with the qml object, else the context gets garbage collected and the qml objects # no longer function correctly/application crashes. result.attached_context = result_context return result ## Delete all nodes containing mesh data in the scene. # \param only_selectable. Set this to False to delete objects from all build plates @pyqtSlot() def deleteAll(self, only_selectable = True) -> None: Logger.log("i", "Clearing scene") if not self.getController().getToolsEnabled(): return nodes = [] for node in DepthFirstIterator(self.getController().getScene().getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax. if not isinstance(node, SceneNode): continue if (not node.getMeshData() and not node.callDecoration("getLayerData")) and not node.callDecoration("isGroup"): continue # Node that doesnt have a mesh and is not a group. if only_selectable and not node.isSelectable(): continue if not node.callDecoration("isSliceable") and not node.callDecoration("getLayerData") and not node.callDecoration("isGroup"): continue # Only remove nodes that are selectable. if node.getParent() and cast(SceneNode, node.getParent()).callDecoration("isGroup"): continue # Grouped nodes don't need resetting as their parent (the group) is resetted) nodes.append(node) if nodes: op = GroupedOperation() for node in nodes: op.addOperation(RemoveSceneNodeOperation(node)) # Reset the print information self.getController().getScene().sceneChanged.emit(node) op.push() Selection.clear() ## Get the MeshFileHandler of this application. def getMeshFileHandler(self) -> MeshFileHandler: return self._mesh_file_handler def getWorkspaceFileHandler(self) -> WorkspaceFileHandler: return self._workspace_file_handler @pyqtSlot(result = QObject) def getPackageManager(self) -> PackageManager: return self._package_manager ## Gets the instance of this application. # # This is just to further specify the type of Application.getInstance(). # \return The instance of this application. @classmethod def getInstance(cls, *args, **kwargs) -> "QtApplication": return cast(QtApplication, super().getInstance(**kwargs)) def _createSplashScreen(self) -> QSplashScreen: return QSplashScreen(QPixmap(Resources.getPath(Resources.Images, self.getApplicationName() + ".png"))) def _screenScaleFactor(self) -> float: # OSX handles sizes of dialogs behind our backs, but other platforms need # to know about the device pixel ratio if sys.platform == "darwin": return 1.0 else: # determine a device pixel ratio from font metrics, using the same logic as UM.Theme fontPixelRatio = QFontMetrics(QCoreApplication.instance().font()).ascent() / 11 # round the font pixel ratio to quarters fontPixelRatio = int(fontPixelRatio * 4) / 4 return fontPixelRatio
# # hello_world.py # basic example app for using python + pyqt5 to run a qml ui # # based of the c++ programs QtCreator creates when making a QtQuick # application. # see http://pyqt.sourceforge.net/Docs/PyQt5/qml.html # for guide on using QML with PyQt import sys from PyQt5.QtCore import QUrl # need a QGuiApplication for QtQuick to work. Could # also use a QApplication from QtWidgets from PyQt5.QtGui import QGuiApplication # QQmlApplication makes it easier to load a QML file, but the # QML file needs to put things in a Window object from PyQt5.QtQml import QQmlApplicationEngine app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.load(QUrl("main.qml")) app.exec()
Card.type == CardType.MINION.value))) cards = cards.order_by(Card.cost).order_by(Card.type.asc()). \ order_by(Card.name.asc()).limit(8).all() model.reset() model.add_cards(cards) if __name__ == "__main__": import pdb app = QApplication(sys.argv) # Register the Python type. Its URI is 'People', it's v1.0 and the type # will be called 'Person' in QML. qmlRegisterType(TrackedCard, 'TrackedCards', 1, 0, 'TrackedCard') engine = QQmlApplicationEngine() ctxt = engine.rootContext() # Initialize the data base sqlengine = create_engine('sqlite:///stats.db', echo=False) Session = sessionmaker() Session.configure(bind=sqlengine) session = Session() ctxt.setContextProperty('pythonList', model) engine.load(QUrl('vt.qml')) engine.quit.connect(app.quit) autoComplete = engine.rootObjects()[0].findChild(QObject, 'autoComplete') autoComplete.textModified.connect(onTextChanged) # data = engine.rootObjects()[0].findChild(QObject, 'myList') # QMetaObject.invokeMethod(data, "append", # Q_ARG('QVariant', {'name':'Josh', 'number': 90})) sys.exit(app.exec_())
if __name__ == '__main__': app = QApplication(sys.argv) appEngine = QQmlApplicationEngine() context = appEngine.rootContext() appEngine.addImageProvider('viewerprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation appEngine.addImageProvider('trackerprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation appEngine.addImageProvider('recorderprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation appEngine.addImageProvider('calibrationprovider', CvImageProvider()) # Hack to make qml believe provider is valid before its creation analysisImageProvider = PyplotImageProvider(fig=None) appEngine.addImageProvider("analysisprovider", analysisImageProvider) analysisImageProvider2 = PyplotImageProvider(fig=None) appEngine.addImageProvider("analysisprovider2", analysisImageProvider2) appEngine.load(QUrl('./qml/MouseTracker.qml')) win = appEngine.rootObjects()[0] if not DEBUG: logger = Logger(context, win, "log") sys.stdout = logger # REGISTER PYTHON CLASSES WITH QML params = ParamsIface(app, context, win) viewer = ViewerIface(app, context, win, params, "preview", "viewerprovider") tracker = TrackerIface(app, context, win, params, "trackerDisplay", "trackerprovider", analysisImageProvider, analysisImageProvider2) recorder = RecorderIface(app, context, win, params, "recording", "recorderprovider", analysisImageProvider, analysisImageProvider2) calibrater = CalibrationIface(app, context, win, params, "calibrationDisplay", "calibrationprovider") context.setContextProperty('py_iface', params)
app = QGuiApplication(sys.argv) # engine = QQmlApplicationEngine("ui/main.qml") engine = QQmlApplicationEngine() repositoryType = [ { "text": "GitHub" } ] # TODO: read the list of defined repositories from a conf file repository = [ { "text": "Unofficial script collection" } ] # TODO: read the list of installed scripts per repo from a conf file context = engine.rootContext() context.setContextProperty("pythonRepositoryTypeModel", repositoryType) context.setContextProperty("pythonRepositoryListModel", repository) context.setContextProperty("pythonScriptListModel", github.getScriptList()) engine.load("ui/main.qml") # import pdb; pdb.set_trace() try: window = engine.rootObjects()[0] except Exception as e: print("The QML file has not been correctly loaded"); sys.exit(); window.show() controller = Controller() controller.setWindow(window) # window.printMessage.connect(controller.printMessage) # i think it should be after window.show(); and signal must be defined in the root element # window.showMessage.connect(controller.showMessage)
loaded = pyqtSignal() error = pyqtSignal(str, arguments=["errorText"]) metaDataChanged = pyqtSignal() @pyqtProperty("QVariantMap", notify=metaDataChanged) def metaData(self): return self._metadata @pyqtProperty(str, notify=loaded) def definitionId(self): return self._definition_id signal.signal(signal.SIGINT, signal.SIG_DFL) file_name = None if len(sys.argv) > 1: file_name = sys.argv[1] del sys.argv[1] app = QApplication(sys.argv) engine = QQmlApplicationEngine() qmlRegisterType(DefinitionLoader, "Example", 1, 0, "DefinitionLoader") qmlRegisterType(DefinitionTreeModel.DefinitionTreeModel, "Example", 1, 0, "DefinitionTreeModel") if file_name: engine.rootContext().setContextProperty("open_file", QUrl.fromLocalFile(file_name)) engine.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "main.qml")) app.exec_()
class PdfDetailWindow: QML_FILE = "qml/PdfDetailsWindow.qml" window = None references = [] num_references = 0 check_links_thread = None dl_thread = None cur_download = 0 num_downloads = 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) # This works somewhat. Simply binds the list to the listModel variable # but does not support layoutChanged, etc. # refs = [QVariant({"ref": ref.ref, "type": ref.reftype, "status": ""}) for ref in self.references] # self.engine.rootContext().setContextProperty('listModel', refs) # Now we try building a real model we can use with a SortFilterProxyModel # see https://wiki.python.org/moin/PyQt/Sorting%20numbers%20in%20columns # self.model = MyTableModel(refs*2, ["ref", "type", "status"]) # self.window.setModel(self.model) # # self.model = QStandardItemModel() # for index, ref in enumerate(self.references): # row = QStandardItem() # row.setData(QVariant({ # "ref": ref.ref, # "type": ref.reftype, # "status": "" # })) # # row.setData(QVariant([ref.ref, ref.reftype, ""])) # self.model.appendRow([row]) # self.window.setModel(self.model) # self.model2 = SortFilterProxyModel() # self.model2.setSourceModel(self.model) # self.window.setModel(self.model2) def onClosing(self): print("XX Closing") # if self.check_links_thread: # self.check_links_thread.quit() def openMainWindow(self): global MAINWINDOW_INSTANCE if not MAINWINDOW_INSTANCE: MAINWINDOW_INSTANCE = PDFxGui() MAINWINDOW_INSTANCE.window.show() MAINWINDOW_INSTANCE.window.raise_() MAINWINDOW_INSTANCE.window.requestActivate() def download(self, selected_item_indexes, target_folder_uri): """ selected_item_indexes is a [QJSValue](http://doc.qt.io/qt-5/qjsvalue.html) Array """ # Parse file:/// uri to local path parsed_path = urlparse(target_folder_uri) target_folder = os.path.abspath(parsed_path.path) print("targetfolder:", target_folder) # Get selected item indexes num_items_selected = selected_item_indexes.property("length").toInt() item_indexes = [selected_item_indexes.property(index).toInt() for index in range(num_items_selected)] # Extract only PDF references refs = [] for item_index in item_indexes: if self.references[item_index].reftype in ["pdf"]: refs.append(self.references[item_index]) if not refs: self.window.setStatusText("No pdf documents selected") self.window.downloadFinished() return # Filter out only "url" and "pdf" references self.num_downloads = len(refs) self.cur_downloaded = 0 self.num_downloads_errors = 0 def signal_download_item_finished(ref, status): index = self.references.index(ref) self.cur_downloaded += 1 if status != "200": self.num_downloads_errors += 1 print("done:", self.cur_downloaded, status) self.window.setStatusText("Downloaded %s of %s..." % (self.cur_downloaded, self.num_downloads)) self.window.setStatusProgress(float(self.cur_downloaded) / float(self.num_downloads)) self.window.checkLinksStatusCodeReceived(index, status) def signal_download_finished(): self.window.setStatusText("Downloaded %s pdf documents (%s errors)" % (self.num_downloads, self.num_downloads_errors)) self.window.downloadFinished() self.window.setStatusText("Downloading %s pdf documents..." % self.num_downloads) self.window.setStatusProgress(0) self.dl_thread = DownloadQThread(refs, target_folder) self.dl_thread.download_item_finished.connect(signal_download_item_finished) self.dl_thread.download_finished.connect(signal_download_finished) self.dl_thread.start() def checkLinks(self): print("start checking links...") # Filter out only "url" and "pdf" references refs = [ref for ref in self.references if ref.reftype in ["url", "pdf"]] self.num_checks_total = len(refs) self.num_checks_current = 0 self.num_checks_errors = 0 def signal_checking_links_item_finished(ref, status_code): self.num_checks_current += 1 if status_code != "200": self.num_checks_errors += 1 print("checked %s/%s. [%s] %s" % (self.num_checks_current, self.num_checks_total, status_code, ref)) self.window.setStatusText("Checked link %s of %s..." % (self.num_checks_current, self.num_checks_total)) self.window.setStatusProgress(float(self.num_checks_current) / float(self.num_checks_total)) index = self.references.index(ref) self.window.checkLinksStatusCodeReceived(index, status_code) def signal_checking_links_finished(): text = "Checked %s links (%s errors)" % (self.num_checks_total, self.num_checks_errors) self.window.setStatusText(text) self.window.checkLinksFinished() self.window.setStatusText("Checking links...") self.window.setStatusProgress(0) self.check_links_thread = CheckLinksQThread(refs) self.check_links_thread.checking_links_item_finished.connect(signal_checking_links_item_finished) self.check_links_thread.checking_links_finished.connect(signal_checking_links_finished) self.check_links_thread.start()
window = engine.rootObjects()[0] myObject = window.findChild(QObject, "myObject") #loop.call_soon(myObject.funcRetClicked()) #myObject.funcRetClicked() loop.run_in_executor(exec, myObject.funcRetClicked) ''' with loop: try: test = Test() service = Service(loop) #loop.run_forever() print('1') # rootObjects 실행전 context를 선언/추가해줍니다. ctx = engine.rootContext() ctx.setContextProperty('Service', service) #engine.load("main.qml") engine.load("qml/tytrader.qml") window = engine.rootObjects()[0] #window.setContextProperty('Service', service) loop.run_until_complete(test.printInterval()) loop.run_forever() except: pass
def stop(self): self.cw.stop() sys.exit() if __name__ == "__main__": app = QGuiApplication(sys.argv) clipboard = app.clipboard() # add icon app_icon = QIcon() app_icon.addFile(path.join("qml", "img", "logo.jpg")) app.setWindowIcon(app_icon) engine = QQmlApplicationEngine() ctx = engine.rootContext() py = QMLNameSpace(engine, clipboard) ctx.setContextProperty("main", engine) ctx.setContextProperty("py", py) # engine.addImportPath(path.join(getcwd(), 'qml')) engine.setImportPathList([path.join(getcwd(), "qml", "lib")]) engine.load("qml/gui.qml") window = engine.rootObjects()[0] window.show() app.aboutToQuit.connect(py.stop) sys.exit(app.exec_())
class QtApplication(QApplication, Application): def __init__(self, **kwargs): plugin_path = "" if sys.platform == "win32": if hasattr(sys, "frozen"): plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins") Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) else: import site for dir in site.getsitepackages(): QCoreApplication.addLibraryPath(os.path.join(dir, "PyQt5", "plugins")) elif sys.platform == "darwin": plugin_path = os.path.join(Application.getInstallPrefix(), "Resources", "plugins") if plugin_path: Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) os.environ["QSG_RENDER_LOOP"] = "basic" super().__init__(sys.argv, **kwargs) self._plugins_loaded = False #Used to determine when it's safe to use the plug-ins. self._main_qml = "main.qml" self._engine = None self._renderer = None self._main_window = None self._shutting_down = False self._qml_import_paths = [] self._qml_import_paths.append(os.path.join(os.path.dirname(sys.executable), "qml")) self._qml_import_paths.append(os.path.join(Application.getInstallPrefix(), "Resources", "qml")) self.setAttribute(Qt.AA_UseDesktopOpenGL) try: self._splash = self._createSplashScreen() except FileNotFoundError: self._splash = None else: self._splash.show() self.processEvents() signal.signal(signal.SIGINT, signal.SIG_DFL) # This is done here as a lot of plugins require a correct gl context. If you want to change the framework, # these checks need to be done in your <framework>Application.py class __init__(). i18n_catalog = i18nCatalog("uranium") self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Loading plugins...")) self._loadPlugins() self.parseCommandLine() Logger.log("i", "Command line arguments: %s", self._parsed_command_line) self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) if self._version_upgrade_manager: self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Updating configuration...")) upgraded = self._version_upgrade_manager.upgrade() if upgraded: preferences = UM.Preferences.getInstance() #Preferences might have changed. Load them again. #Note that the language can't be updated, so that will always revert to English. try: preferences.readFromFile(Resources.getPath(Resources.Preferences, self._application_name + ".cfg")) except FileNotFoundError: pass self.showSplashMessage(i18n_catalog.i18nc("@info:progress", "Loading preferences...")) try: file = Resources.getPath(Resources.Preferences, self.getApplicationName() + ".cfg") Preferences.getInstance().readFromFile(file) except FileNotFoundError: pass def run(self): pass def hideMessage(self, message): with self._message_lock: if message in self._visible_messages: self._visible_messages.remove(message) self.visibleMessageRemoved.emit(message) def showMessage(self, message): with self._message_lock: if message not in self._visible_messages: self._visible_messages.append(message) message.setTimer(QTimer()) self.visibleMessageAdded.emit(message) def setMainQml(self, path): self._main_qml = path def initializeEngine(self): # TODO: Document native/qml import trickery Bindings.register() self._engine = QQmlApplicationEngine() for path in self._qml_import_paths: self._engine.addImportPath(path) if not hasattr(sys, "frozen"): self._engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml")) self._engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR) self.registerObjects(self._engine) self._engine.load(self._main_qml) self.engineCreatedSignal.emit() engineCreatedSignal = Signal() def isShuttingDown(self): return self._shutting_down def registerObjects(self, engine): pass def getRenderer(self): if not self._renderer: self._renderer = QtRenderer() return self._renderer def addCommandLineOptions(self, parser): parser.add_argument("--disable-textures", dest="disable-textures", action="store_true", default=False, help="Disable Qt texture loading as a workaround for certain crashes.") # Overridden from QApplication::setApplicationName to call our internal setApplicationName def setApplicationName(self, name): Application.setApplicationName(self, name) mainWindowChanged = Signal() def getMainWindow(self): return self._main_window def setMainWindow(self, window): if window != self._main_window: self._main_window = window self.mainWindowChanged.emit() # Handle a function that should be called later. def functionEvent(self, event): e = _QtFunctionEvent(event) QCoreApplication.postEvent(self, e) # Handle Qt events def event(self, event): if event.type() == _QtFunctionEvent.QtFunctionEvent: event._function_event.call() return True return super().event(event) def windowClosed(self): Logger.log("d", "Shutting down %s", self.getApplicationName()) self._shutting_down = True try: Preferences.getInstance().writeToFile(Resources.getStoragePath(Resources.Preferences, self.getApplicationName() + ".cfg")) except Exception as e: Logger.log("e", "Exception while saving preferences: %s", repr(e)) try: self.applicationShuttingDown.emit() except Exception as e: Logger.log("e", "Exception while emitting shutdown signal: %s", repr(e)) try: self.getBackend().close() except Exception as e: Logger.log("e", "Exception while closing backend: %s", repr(e)) self.quit() ## Load a Qt translation catalog. # # This method will locate, load and install a Qt message catalog that can be used # by Qt's translation system, like qsTr() in QML files. # # \param file The file name to load, without extension. It will be searched for in # the i18nLocation Resources directory. If it can not be found a warning # will be logged but no error will be thrown. # \param language The language to load translations for. This can be any valid language code # or 'default' in which case the language is looked up based on system locale. # If the specified language can not be found, this method will fall back to # loading the english translations file. # # \note When `language` is `default`, the language to load can be changed with the # environment variable "LANGUAGE". def loadQtTranslation(self, file, language = "default"): #TODO Add support for specifying a language from preferences path = None if language == "default": path = self._getDefaultLanguage(file) else: path = Resources.getPath(Resources.i18n, language, "LC_MESSAGES", file + ".qm") # If all else fails, fall back to english. if not path: Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file)) try: path = Resources.getPath(Resources.i18n, "en", "LC_MESSAGES", file + ".qm") except FileNotFoundError: Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file) return # Store a reference to the translator. # This prevents the translator from being destroyed before Qt has a chance to use it. self._translators[file] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator) ## Display text on the splash screen. def showSplashMessage(self, message): if self._splash: self._splash.showMessage(message , Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() ## Close the splash screen after the application has started. def closeSplash(self): if self._splash: self._splash.close() self._splash = None def _createSplashScreen(self): return QSplashScreen(QPixmap(Resources.getPath(Resources.Images, self.getApplicationName() + ".png"))) def _getDefaultLanguage(self, file): # If we have a language override set in the environment, try and use that. lang = os.getenv("URANIUM_LANGUAGE") if lang: try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: pass # Else, try and get the current language from preferences lang = Preferences.getInstance().getValue("general/language") if lang: try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: pass # If none of those are set, try to use the environment's LANGUAGE variable. lang = os.getenv("LANGUAGE") if lang: try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: pass # If looking up the language from the enviroment or preferences fails, try and use Qt's system locale instead. locale = QLocale.system() # First, try and find a directory for any of the provided languages for lang in locale.uiLanguages(): try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: pass # If that fails, see if we can extract a language "class" from the # preferred language. This will turn "en-GB" into "en" for example. lang = locale.uiLanguages()[0] lang = lang[0:lang.find("-")] try: return Resources.getPath(Resources.i18n, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: pass return None
with QThreadExecutor(1) as exec: window = engine.rootObjects()[0] myObject = window.findChild(QObject, "myObject") #loop.call_soon(myObject.funcRetClicked()) #myObject.funcRetClicked() loop.run_in_executor(exec, myObject.funcRetClicked) ''' with loop: try: test = Test() service = Service(loop) #loop.run_forever() print('1') # rootObjects 실행전 context를 선언/추가해줍니다. ctx = engine.rootContext() ctx.setContextProperty('Service', service) engine.load("main.qml") window = engine.rootObjects()[0] #window.setContextProperty('Service', service) loop.run_until_complete(test.printInterval()) loop.run_forever() except: pass
self.obj.orange(sec, minu) elif sec < 60 : self.obj.red(sec, minu) else : self.obj.green(sec, minu) sleeptime = 1000000 - datetime.datetime.now().microsecond yield from asyncio.sleep(round(sleeptime * 0.000001, 2)) with loop: ctx = engine.rootContext() engine.load("progressor.qml") #engine.load("progressor_multiple.qml") #window = engine.rootObjects()[0] #window = engine.rootObjects()[0].findChild("wnd1") #root = engine.rootObjects()[0].findChild(QObject, "rootObj") #root = engine.rootObjects()[0] #window = engine.rootObjects()[0].findChild(QObject, "wnd") window = engine.rootObjects()[0].findChild(QObject, "wnd_dummy") window1 = engine.rootObjects()[0].findChild(QObject, "wnd1") window2 = engine.rootObjects()[0].findChild(QObject, "wnd2") window.show() window1.show() window2.show()