def start(): app = QApplication(sys.argv) # 将Qt事件循环写到asyncio事件循环里。 # QEventLoop不是Qt原生事件循环, # 是被asyncio重写的事件循环。 eventLoop = QEventLoop(app) asyncio.set_event_loop(eventLoop) try: main = Window() main.show() # 当前音乐的显示信息。 # 因为需要布局之后重新绘制的宽高。 # 这个宽高会在show之后才会改变。 # 需要获取宽,高并嵌入到父窗口里。 main.playWidgets.currentMusic.resize(main.navigation.width(), 64) with eventLoop: eventLoop.run_forever() sys.exit(0) except: logger.error("got some error", exc_info=True)
def main(): app = QApplication(sys.argv) #shared= QSharedMemory("wepush") #if shared.attach(): #return 0 #shared.create(1) #sys.stdout=common.Mystd() loop = QEventLoop(app) asyncio.set_event_loop(loop) win = QWebEngineView() # QWebEngineView() director['root_win'] = win #thread.start_new_thread (server.start_server,(28289,)) #win =QWebView() #win.setWindowIcon(QIcon( './html/wechat.ico')) win.setMinimumSize(1200, 900) win.setWindowTitle('微信群发工具V1.0') url = 'file:///%s/test.html' % base_dir.replace('\\', '/') win.load(QUrl(url)) win.show() with loop: from server import start_server #loop.set_debug(True) loop.run_until_complete(start_server) #loop.create_task(send()) #loop.create_task(start_server) loop.run_forever()
def main(self): connections = dict() users = dict() # Each client will create a new protocol instance self.ins = ChatServerProtocol(self.db_path, connections, users) # GUI app = Qt.QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # NEW must set the event loop wnd = ServerMonitorWindow(server_instance=self.ins, parsed_args=self.args) wnd.show() with loop: coro = loop.create_server(lambda: self.ins, self.args["addr"], self.args["port"]) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C print('Serving on {}:{}'.format(*server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass server.close() loop.run_until_complete(server.wait_closed()) loop.close()
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 main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() # plugins to include different websites (and listeners?) plugin_manager = PluginManager() plugin_manager.register_main_window(main_window) # User Settings settings_manager = SettingsManager() settings_manager.register_main_window(main_window) settings_manager.register_plugin_manager(plugin_manager) main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass app.deleteLater() plugin_manager.terminate_plugins() event_loop.close() sys.exit()
def main_gui(args: argparse.Namespace): QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # Check environment first from PyQt5.QtWidgets import QMessageBox, QSystemTrayIcon def dialog(message: str) -> None: QMessageBox.critical(None, "VirtScreen", message) if not QSystemTrayIcon.isSystemTrayAvailable(): dialog("Cannot detect system tray on this system.") sys.exit(1) check_env(args, dialog) app.setApplicationName("VirtScreen") app.setWindowIcon(QIcon(ICON_PATH)) os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material" # Register the Python type. Its URI is 'People', it's v1.0 and the type # will be called 'Person' in QML. qmlRegisterType(DisplayProperty, 'VirtScreen.DisplayProperty', 1, 0, 'DisplayProperty') qmlRegisterType(Backend, 'VirtScreen.Backend', 1, 0, 'Backend') qmlRegisterType(Cursor, 'VirtScreen.Cursor', 1, 0, 'Cursor') qmlRegisterType(Network, 'VirtScreen.Network', 1, 0, 'Network') # Create a component factory and load the QML script. engine = QQmlApplicationEngine() engine.load(QUrl(MAIN_QML_PATH)) if not engine.rootObjects(): dialog("Failed to load QML") sys.exit(1) sys.exit(app.exec_()) with loop: loop.run_forever()
class KnechtQT: def __init__(self, args): self.port = args.port self.address = args.listen self.app = None self.window = None self.loop = None def _close_window(self): if self.window: self.window.showNormal() self.window.hide() self.window.close() self.window = None def show_text(self, text, duration=None): if duration is None or duration <= 0: duration = 10 if self.window: self._close_window() try: subprocess.call(['xset', 'dpms', 'force', 'on']) except FileNotFoundError as e: pass label = QLabel() label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) label.setTextFormat(Qt.RichText) label.setWordWrap(True) label.setText('<span style="font-size:100px">%s</span>' % text) self.window = QMainWindow() self.window.setWindowTitle("KnechtQT") self.window.setCentralWidget(label) self.window.showFullScreen() self.loop.call_later(duration, self._close_window) def launch(self): self.app = QApplication([]) self.app.setQuitOnLastWindowClosed(False) self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) signal.signal(signal.SIGINT, signal.SIG_DFL) with self.loop: coro = self.loop.create_server(lambda: CommandReceiver(self), self.address, self.port) server = self.loop.run_until_complete(coro) self.loop.run_forever() server.close() loop.run_until_complete(server.wait_closed())
def main(): app = QtWidgets.QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) aw = ApplicationWindow() aw.show() loop.run_until_complete(amain(app, loop, aw)) loop.run_forever()
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop and set it in asyncio event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() settings_data = main_window.settings_model.root # Create the recving messaging interface messager = ZmqMessaging() messager.message_signal.connect(main_window.chat_slot) messager.connected_signal.connect(main_window.status_bar.set_widget_status) main_window.command_line_signal.connect(messager.publish_message) # gather the plugins module_manager = pluginmanager.PluginInterface() module_manager.set_entry_points('chatimusmaximus.communication_protocols') modules, names = module_manager.collect_entry_point_plugins() # need to have the modules in a dict, so get the name and put in dict module_dict = {module.__name__.split('.')[-1]: module for module in modules} services, addresses = create_services_from_settings(settings_data, module_dict) atexit.register(_destroy_services, services) try: messager.subscribe_to_publishers(settings_data['sockets_to_connect_to']) cmd_line_address = settings_data['display']['address'] if cmd_line_address: messager.publish_to_address(cmd_line_address) except ZMQError: pass # show me the money! main_window.show() # let everything asyncorous run try: event_loop.run_forever() # catch ctrl-C event to allow for graceful closing except KeyboardInterrupt: pass # tell Qt we're going out app.deleteLater() # close the event loop event_loop.close() # close the subprocesses for service in services: service.deactivate() # exit sys.exit()
def gui_loop(room_uri): app = QApplication([]) loop = QEventLoop(app) asyncio.set_event_loop(loop) w = App(Room(room_uri)) w.show() with loop: loop.run_forever()
class SimpleApplet: def __init__(self, main_widget_class, cmd_description=None): self.main_widget_class = main_widget_class self.argparser = argparse.ArgumentParser(description=cmd_description) group = self.argparser.add_argument_group("data server") group.add_argument( "--server", default="::1", help="hostname or IP to connect to") group.add_argument( "--port", default=3250, type=int, help="TCP port to connect to") self._arggroup_datasets = self.argparser.add_argument_group("datasets") def add_dataset(self, name, help=None): if help is None: self._arggroup_datasets.add_argument(name) else: self._arggroup_datasets.add_argument(name, help=help) def args_init(self): self.args = self.argparser.parse_args() def quamash_init(self): app = QtWidgets.QApplication([]) self.loop = QEventLoop(app) asyncio.set_event_loop(self.loop) def create_main_widget(self): self.main_widget = self.main_widget_class(self.args) self.main_widget.show() def sub_init(self, data): self.data = data return data def sub_mod(self, mod): self.main_widget.data_changed(self.data, mod) def create_subscriber(self): self.subscriber = Subscriber("datasets", self.sub_init, self.sub_mod) self.loop.run_until_complete(self.subscriber.connect( self.args.server, self.args.port)) def run(self): self.args_init() self.quamash_init() try: self.create_main_widget() self.create_subscriber() try: self.loop.run_forever() finally: self.loop.run_until_complete(self.subscriber.close()) finally: self.loop.close()
def main(): # Build default paths for files. dirs = appdirs.AppDirs('QHangups', 'QHangups') default_log_path = os.path.join(dirs.user_data_dir, 'hangups.log') default_cookies_path = os.path.join(dirs.user_data_dir, 'cookies.json') # Setup command line argument parser parser = argparse.ArgumentParser( prog='qhangups', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-d', '--debug', action='store_true', help='log detailed debugging messages') parser.add_argument('--log', default=default_log_path, help='log file path') parser.add_argument('--cookies', default=default_cookies_path, help='cookie storage path') args = parser.parse_args() # Create all necessary directories. for path in [args.log, args.cookies]: directory = os.path.dirname(path) if directory and not os.path.isdir(directory): try: os.makedirs(directory) except OSError as e: sys.exit('Failed to create directory: {}'.format(e)) # Setup logging log_level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(filename=args.log, level=log_level, format=LOG_FORMAT) # asyncio's debugging logs are VERY noisy, so adjust the log level logging.getLogger('asyncio').setLevel(logging.WARNING) # ...and if we don't need Hangups debug logs, then uncomment this: # logging.getLogger('hangups').setLevel(logging.WARNING) # Setup QApplication app = QtGui.QApplication(sys.argv) app.setOrganizationName("QHangups") app.setOrganizationDomain("qhangups.eutopia.cz") app.setApplicationName("QHangups") app.setQuitOnLastWindowClosed(False) app.installTranslator(translator) app.installTranslator(qt_translator) # Start Quamash event loop loop = QEventLoop(app) asyncio.set_event_loop(loop) with loop: widget = QHangupsMainWidget(args.cookies) loop.run_forever()
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop and set it in asyncio event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() settings_data = main_window.settings_model.root # Need 3 bits of information from settings. ip addresses, display missing, # and general settings # Create the recving messaging interface messager = ZmqMessaging() messager.message_signal.connect(main_window.chat_slot) messager.connected_signal.connect(main_window.status_bar.set_widget_status) # gather the plugins module_manager = pluginmanager.PluginInterface() module_manager.set_entry_points('chatimusmaximus.communication_protocols') modules = module_manager.collect_entry_point_plugins() # need to have the modules in a dict, so get the name and put in dict module_dict = { module.__name__.split('.')[-1]: module for module in modules } services, addresses = create_services_from_settings( settings_data, module_dict) atexit.register(_destroy_services, services) messager.subscribe_to_publishers(settings_data['sockets_to_connect_to']) # show me the money! main_window.show() # let everything asyncorous run try: event_loop.run_forever() # catch ctrl-C event to allow for graceful closing except KeyboardInterrupt: pass # tell Qt we're going out app.deleteLater() # close the event loop event_loop.close() # close the subprocesses for service in services: service.deactivate() # exit sys.exit()
def __init__(self): QApplication.__init__(self, sys.argv) loop = QEventLoop(self) self.loop = loop asyncio.set_event_loop(self.loop) self.userClient = Client(self.loop, args["user"]) self.loop.create_task(self.start()) self.gui = Gui(self.loop, self.userClient) loop.run_forever()
def main(): app = QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) dialogo = AplicacionDescargaAnalisisAsync() dialogo.exec() with loop: loop.run_forever() loop.close() sys.exit(app.exec_())
def main(): app = QApplication(sys.argv) loop = QEventLoop(app) # loop.set_debug(True) asyncio.set_event_loop(loop) # NEW must set the event loop lobby = QuickLobby(loop) loop.add_signal_handler(signal.SIGINT, lobby.shutdown, None) for window in lobby.rootObjects(): window.show() with loop: loop.run_forever()
def main(): parse_args(sys.argv) q_app = QApplication(sys.argv) q_app.setQuitOnLastWindowClosed(True) q_app.setApplicationName('FeelUOwn') app_event_loop = QEventLoop(q_app) asyncio.set_event_loop(app_event_loop) app = App() app.show() app_event_loop.run_forever() sys.exit(0)
def main(): # Build default paths for files. dirs = appdirs.AppDirs('QHangups', 'QHangups') default_log_path = os.path.join(dirs.user_data_dir, 'hangups.log') default_token_path = os.path.join(dirs.user_data_dir, 'refresh_token.txt') # Setup command line argument parser parser = argparse.ArgumentParser(prog='qhangups', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-d', '--debug', action='store_true', help='log detailed debugging messages') parser.add_argument('--log', default=default_log_path, help='log file path') parser.add_argument('--token', default=default_token_path, help='OAuth refresh token storage path') args = parser.parse_args() # Create all necessary directories. for path in [args.log, args.token]: directory = os.path.dirname(path) if directory and not os.path.isdir(directory): try: os.makedirs(directory) except OSError as e: sys.exit('Failed to create directory: {}'.format(e)) # Setup logging log_level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(filename=args.log, level=log_level, format=LOG_FORMAT) # asyncio's debugging logs are VERY noisy, so adjust the log level logging.getLogger('asyncio').setLevel(logging.WARNING) # ...and if we don't need Hangups debug logs, then uncomment this: # logging.getLogger('hangups').setLevel(logging.WARNING) # Setup QApplication app = QtWidgets.QApplication(sys.argv) app.setOrganizationName("QHangups") app.setOrganizationDomain("qhangups.eutopia.cz") app.setApplicationName("QHangups") app.setQuitOnLastWindowClosed(False) app.installTranslator(translator) app.installTranslator(qt_translator) # Start Quamash event loop loop = QEventLoop(app) asyncio.set_event_loop(loop) with loop: widget = QHangupsMainWidget(args.token) loop.run_forever()
def __init__(self): QApplication.__init__(self, sys.argv) loop = QEventLoop(self) self.loop = loop asyncio.set_event_loop(self.loop) self.gui = LoginDialogControl() self.gui.show() exit_code = self.exec_() if exit_code == 888: self.restart_program() else: sys.exit() loop.run_forever()
def main(): #QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL) #QCoreApplication.setAttribute(Qt.AA_UseOpenGLES) app = MainApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) app.threadExecutor = QThreadExecutor(10) if app.isClosing(): return 0 #app.setProxyStyle(ProxyStyle()) #return app.exec_() with loop: # context manager calls .close() when loop completes, and releases all resources loop.run_forever()
class App(QApplication): def __init__(self): QApplication.__init__(self, sys.argv) self.loop = QEventLoop(self) asyncio.set_event_loop(self.loop) self.client = Client(self.loop, f'user-{int(random()*10000)}') self.loop.create_task(self.start()) self.gui = MyWindow(self.loop, self.client) self.gui.show() self.loop.run_forever() async def start(self): clientConnection = self.loop.create_connection(lambda: self.client, '127.0.0.1', 8888) await asyncio.wait_for(clientConnection, 10000, loop=self.loop)
def main(self): # create event loop app = Qt.QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # NEW must set the event loop # authentication process auth_ = ClientAuth(db_path=self.db_path) login_wnd = LoginWindow(auth_instance=auth_) if login_wnd.exec_() == QtWidgets.QDialog.Accepted: # Each client will create a new protocol instance client_ = ChatClientProtocol(db_path=self.db_path, loop=loop, username=login_wnd.username, password=login_wnd.password) # create Contacts window wnd = ContactsWindow(client_instance=client_, user_name=login_wnd.username) client_.gui_instance = wnd # reference from protocol to GUI, for msg update with loop: # cleaning old instances del auth_ del login_wnd # connect to our server try: coro = loop.create_connection(lambda: client_, self.args["addr"], self.args["port"]) server = loop.run_until_complete(coro) except ConnectionRefusedError: print('Error. wrong server') exit(1) # start GUI client wnd.show() client_.get_from_gui() # asyncio.ensure_future(client_.get_from_gui(loop)) # Serve requests until Ctrl+C try: loop.run_forever() except KeyboardInterrupt: pass except Exception: pass
class App(QApplication): def __init__(self): QApplication.__init__(self, sys.argv) self.loop = QEventLoop(self) asyncio.set_event_loop(self.loop) self.userClient = EchoClientProtocol(self.loop, 'user') self.loop.create_task(self.start()) self.gui = Gui(self.loop, self.userClient) self.loop.run_forever() async def start(self): clientConnection = self.loop.create_connection(lambda: self.userClient, '127.0.0.1', 8888) await asyncio.wait_for(clientConnection, 1000) transport, protocol = clientConnection self.userClient.connection_made(transport)
def __init__(self): QApplication.__init__(self, sys.argv) loop = QEventLoop(self) self.loop = loop asyncio.set_event_loop(self.loop) self.gui = MainFormControl(self.loop) self.gui.show() stylesheet = getstylesheetfromQss('ui.qss') self.gui.setStyleSheet(stylesheet) exit_code = self.exec_() if exit_code == 888: self.restart_program() else: sys.exit() loop.run_forever()
class Application(QtWidgets.QApplication): def __init__(self): super().__init__([]) self.setApplicationName('PyPlaybin example') self.setApplicationVersion('1.0.0') self.setOrganizationDomain('net.jeromelaheurte') Playbin.start_glib_loop() self._loop = QEventLoop() asyncio.set_event_loop(self._loop) self.window = MainWindow() def run(self): with self._loop: self._loop.run_forever()
def start(): app = QApplication(sys.argv) eventLoop = QEventLoop(app) asyncio.set_event_loop(eventLoop) try: window = Window() #Window() window.show() logger.info("window start") with eventLoop: eventLoop.run_forever() sys.exit(0) except Exception: logger.exception("got some error")
def main(): if qVersion() < '5.5.0': raise 'not supported qt version < 5.5.0' app = QCoreApplication(sys.argv) pyctrl() loop = QEventLoop(app) loop.add_signal_handler(signal.SIGINT, sigint_handler) asyncio.set_event_loop(loop) rto = StartupManager() rto.start() global g_w2t g_w2t = rto app.aboutToQuit.connect(on_app_about_close) qDebug('qt&loop...{}'.format(rto)) with loop: loop.run_forever() # sys.exit(app.exec_()) return
def main(): app = QtWidgets.QApplication(sys.argv) # create the event loop and set it in asyncio event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # login_window = QtWidgets.QMainWindow() ui = LoginWindow([getURL(), getWSURL()]) try: event_loop.run_forever() # catch ctrl-C event to allow for graceful closing except KeyboardInterrupt: pass app.deleteLater() event_loop.close() sys.exit()
class App(QApplication): def __init__(self): QApplication.__init__(self, sys.argv) self.loop = QEventLoop(self) asyncio.set_event_loop(self.loop) self.userClient = EchoClientProtocol(self.loop, 'user') self.loop.create_task(self.start()) self.window = MyWindow(self.loop, self.userClient) self.window.show() self.loop.run_forever() async def start(self): print('[START CLIENT]') clientConnection = self.loop.create_connection(lambda: self.userClient, '127.0.0.1', 8888) await asyncio.wait_for(clientConnection, 10000, loop=self.loop)
def main(): if qVersion() < "5.5.0": raise "not supported qt version < 5.5.0" app = QCoreApplication(sys.argv) pyctrl() loop = QEventLoop(app) loop.add_signal_handler(signal.SIGINT, sigint_handler) asyncio.set_event_loop(loop) rto = StartupManager() rto.start() global g_w2t g_w2t = rto app.aboutToQuit.connect(on_app_about_close) qDebug("qt&loop...{}".format(rto)) with loop: loop.run_forever() # sys.exit(app.exec_()) return
def __init__(self): QApplication.__init__(self, sys.argv) # Establish loop as Quamash Event Loop loop = QEventLoop(self) self.loop = loop asyncio.set_event_loop(loop) self.idle = False self.trayIcon = None self.themes = themes self.options = Options try: self.theme = themes[self.options["theme"]["theme"]] except KeyError: self.theme = themes["Pesterchum 2.5"] self.theme_name = self.theme["name"] self.moods = Moods self.emojis = Emojis self.mentions = Mentions self.setStyleSheet(self.theme["styles"]) self.nick = None self.client = DiscordClient(app=self, loop=self.loop) self.user, self.passwd, self.token, self.botAccount = UserAuth if not UserAuth[0] and not UserAuth[1] and not UserAuth[2]: self.openAuth(i=True) save_auth(( self.user, self.passwd, self.token, self.botAccount, )) asyncio.ensure_future(self.connecting()) asyncio.ensure_future(self.runbot()) self.gui = Gui(self.loop, self) loop.run_forever()
def main(): # create the GUI app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) main_window = MainWindow() # need chat_slot to be able to add to add the chat signal chat_slot = main_window.central_widget.message_area.chat_slot settings = get_settings_helper() # this methods also handles passing in values to websites plugin_manager = instantiate_plugin_manager(settings) main_window.set_settings(settings) chat_list = plugin_manager.get_instances() # connect the sockets signals to the GUI for chat in chat_list: chat.chat_signal.connect(chat_slot) chat.connected_signal.connect(main_window.status_bar.set_widget_status) listener_interface = pluginmanager.PluginInterface() listener_interface.collect_plugins(plugins) listener_list = listener_interface.get_instances() # flake8: noqa # main_window.central_widget.message_area.listeners = listener_list main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass for chat in chat_list: if chat.process: chat.process.terminate() event_loop.close() sys.exit()
class Application: def __init__(self): self.app = QGuiApplication(sys.argv) self.touchscreens = list(filter(lambda d: d.type() == QTouchDevice.TouchScreen, QTouchDevice.devices())) if self.touchscreens: logger.info("touchscreens detected, disabling mouse: %s" % self.touchscreens) # self.app.setOverrideCursor(QCursor(Qt.BlankCursor)) else: logger.error("No touchscreen detected!") self.engine = QQmlApplicationEngine() self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) def run(self): tracemalloc.start(25) self.engine.load("ui/window.qml") self.win = self.engine.rootObjects()[0] self.win.show() with self.loop: ## context manager calls .close() when loop completes, and releases all resources self.loop.run_forever()
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() # plugins to include different websites (and listeners?) plugin_manager = PluginManager() plugin_manager.register_main_window(main_window) # User Settings settings_manager = SettingsManager() settings_manager.register_main_window(main_window) settings_manager.register_plugin_manager(plugin_manager) # listeners handeled separatly for now listener_interface = pluginmanager.PluginInterface() listener_interface.collect_plugins(plugins) listener_list = listener_interface.get_instances() # flake8: noqa # main_window.central_widget.message_area.listeners = listener_list main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass app.deleteLater() plugin_manager.terminate_plugins() event_loop.close() sys.exit()
def start(): app = QApplication(sys.argv) # 将Qt事件循环写到asyncio事件循环里。 # QEventLoop不是Qt原生事件循环, # 是被asyncio重写的事件循环。 eventLoop = QEventLoop(app) asyncio.set_event_loop(eventLoop) main = Window() main.show() # 当前音乐的显示信息。 # 因为需要布局之后重新绘制的宽高。 # 这个宽高会在show之后才会改变。 # 需要获取宽,高并嵌入到父窗口里。 main.playWidgets.currentMusic.resize(main.navigation.width(), 64) main.playWidgets.currentMusic.move( 0, main.height() - 64 - main.playWidgets.height()) with eventLoop: eventLoop.run_forever() sys.exit(0)
#!/usr/bin/env python """ Created by howie.hu at 2018/5/23. """ import asyncio import os import sys from PyQt5.QtWidgets import QApplication from quamash import QEventLoop sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from owllook_gui.config import Config from owllook_gui.wigdets.home import OwlHome app = QApplication(sys.argv) event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) try: with event_loop: main = OwlHome(event_loop) event_loop.run_forever() sys.exit(0) except: Config.LOGGER.error("程序运行出错", exc_info=True)
def wire_tap(msg): ex.insertText(msg.data.decode()) def main(loop, subject): nc = NATS() yield from nc.connect(f"{sys.argv[1]}:{sys.argv[2]}", loop=loop) async def mh_s1(msg): await wire_tap(msg) yield from nc.subscribe(subject, cb=wire_tap) if __name__ == '__main__': if len(sys.argv) != 4: print( "Usage: python nats_scrolling_plaintext_edit.py [host] [port] [queue]" ) else: app = QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) loop.run_until_complete(main(loop, subject=sys.argv[3])) ex = QtWiretap() loop.run_forever()
# 功能。 def setText(self, text): self.text = text self.titleLabel.setText( "搜索<font color='#23518F'>“{0}”</font><br>".format(self.text)) if __name__ == '__main__': app = QApplication(sys.argv) # 将Qt事件循环写到asyncio事件循环里。 # QEventLoop不是Qt原生事件循环, # 是被asyncio重写的事件循环。 eventLoop = QEventLoop(app) asyncio.set_event_loop(eventLoop) main = Window() main.show() # 当前音乐的显示信息。 # 因为需要布局之后重新绘制的宽高。 # 这个宽高会在show之后才会改变。 # 需要获取宽,高并嵌入到父窗口里。 main.playWidgets.currentMusic.resize(main.navigation.width(), 64) main.playWidgets.currentMusic.move( 0, main.height() - 64 - main.playWidgets.height()) eventLoop.run_forever() sys.exit(0)
from quamash import QEventLoop try: import signal signal.signal(signal.SIGINT, signal.SIG_DFL) except ImportError: pass def configureLogging(): try: logging.config.dictConfig(settings.LOGGING) except: from utils.logging import QtHandler logging.basicConfig(level=logging.WARNING, handlers=[QtHandler()]) if __name__ == '__main__': app = Application(sys.argv) settings.init(app) configureLogging() log = logging.getLogger(__name__) log.info('starting app') loop = QEventLoop(app) asyncio.set_event_loop(loop) app.start() sys.exit(loop.run_forever())
os.mkdir(SONGS_PATH) if __name__ == "__main__": ensure_data_dir() app = QApplication(sys.argv) app.setQuitOnLastWindowClosed(True) app.setWindowIcon(QIcon(WINDOW_ICON)) app.setApplicationName("FeelUOwn") app_event_loop = QEventLoop(app) asyncio.set_event_loop(app_event_loop) qss = QSS_PATH with open(qss, "r") as qssfile: app.setStyleSheet(qssfile.read()) if MODE != DEBUG: f_handler = open(LOGFILE, 'w') sys.stdout = f_handler sys.stderr = f_handler w = Controller() w.move((QApplication.desktop().width() - w.width())/2, (QApplication.desktop().height() - w.height())/2) w.show() app_event_loop.run_forever() sys.exit()
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop and set it in asyncio event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() settings_data = main_window.settings_model.root # Create the recving messaging interface messager = ZmqMessaging() cmd_line_address = settings_data['display']['address'] if cmd_line_address: messager.publish_to_address(cmd_line_address) messager.message_signal.connect(main_window.chat_slot) messager.connected_signal.connect(main_window.status_bar.set_widget_status) clear = main_window.central_widget.message_area.clear messager.clear_signal.connect(clear) main_window.command_line_signal.connect(messager.publish_message) sockets = settings_data['sockets_to_connect_to'] cmd_line_address = settings_data['display']['address'] for socket in sockets: if socket: try: messager.subscribe_to_publisher(socket) except ZMQError: # TODO: change to a logging command s = 'socket address to connect to {} is throwing errors!' print(s.format(socket)) try: if cmd_line_address: messager.publish_to_address(cmd_line_address) except ZMQError: s = 'command line address to connect to {} is throwing errors!' print(s.format(cmd_line_address)) plugin_manager = pluginmanager.PluginInterface() plugin_manager.set_entry_points('chatimusmaximus.gui') # plugins, names plugins, _ = plugin_manager.collect_entry_point_plugins() for plug in plugins: plug(main_window, messager) # show me the money! main_window.show() # let everything asyncorous run try: event_loop.run_forever() # catch ctrl-C event to allow for graceful closing except KeyboardInterrupt: pass # tell Qt we're going out app.deleteLater() # close the event loop event_loop.close() # exit sys.exit()
class SimpleApplet: def __init__(self, main_widget_class, cmd_description=None, default_update_delay=0.0): self.main_widget_class = main_widget_class self.argparser = argparse.ArgumentParser(description=cmd_description) self.argparser.add_argument( "--update-delay", type=float, default=default_update_delay, help="time to wait after a mod (buffering other mods) " "before updating (default: %(default).2f)") group = self.argparser.add_argument_group("standalone mode (default)") group.add_argument( "--server", default="::1", help="hostname or IP of the master to connect to " "for dataset notifications " "(ignored in embedded mode)") group.add_argument( "--port", default=3250, type=int, help="TCP port to connect to") self.argparser.add_argument( "--embed", default=None, help="embed into GUI", metavar="IPC_ADDRESS") self._arggroup_datasets = self.argparser.add_argument_group("datasets") self.dataset_args = set() def add_dataset(self, name, help=None, required=True): kwargs = dict() if help is not None: kwargs["help"] = help if required: self._arggroup_datasets.add_argument(name, **kwargs) else: self._arggroup_datasets.add_argument("--" + name, **kwargs) self.dataset_args.add(name) def args_init(self): self.args = self.argparser.parse_args() self.datasets = {getattr(self.args, arg.replace("-", "_")) for arg in self.dataset_args} def quamash_init(self): app = QtWidgets.QApplication([]) self.loop = QEventLoop(app) asyncio.set_event_loop(self.loop) def ipc_init(self): if self.args.embed is not None: self.ipc = AppletIPCClient(self.args.embed) self.loop.run_until_complete(self.ipc.connect()) def ipc_close(self): if self.args.embed is not None: self.ipc.close() def create_main_widget(self): self.main_widget = self.main_widget_class(self.args) if self.args.embed is not None: self.ipc.set_close_cb(self.main_widget.close) if os.name == "nt": # HACK: if the window has a frame, there will be garbage # (usually white) displayed at its right and bottom borders # after it is embedded. self.main_widget.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.main_widget.show() win_id = int(self.main_widget.winId()) self.loop.run_until_complete(self.ipc.embed(win_id)) else: # HACK: # Qt window embedding is ridiculously buggy, and empirical # testing has shown that the following procedure must be # followed exactly on Linux: # 1. applet creates widget # 2. applet creates native window without showing it, and # gets its ID # 3. applet sends the ID to host, host embeds the widget # 4. applet shows the widget # 5. parent resizes the widget win_id = int(self.main_widget.winId()) self.loop.run_until_complete(self.ipc.embed(win_id)) self.main_widget.show() self.ipc.fix_initial_size() else: self.main_widget.show() def sub_init(self, data): self.data = data return data def filter_mod(self, mod): if self.args.embed is not None: # the parent already filters for us return True if mod["action"] == "init": return True if mod["path"]: return mod["path"][0] in self.datasets elif mod["action"] in {"setitem", "delitem"}: return mod["key"] in self.datasets else: return False def emit_data_changed(self, data, mod_buffer): self.main_widget.data_changed(data, mod_buffer) def flush_mod_buffer(self): self.emit_data_changed(self.data, self.mod_buffer) del self.mod_buffer def sub_mod(self, mod): if not self.filter_mod(mod): return if self.args.update_delay: if hasattr(self, "mod_buffer"): self.mod_buffer.append(mod) else: self.mod_buffer = [mod] asyncio.get_event_loop().call_later(self.args.update_delay, self.flush_mod_buffer) else: self.emit_data_changed(self.data, [mod]) def subscribe(self): if self.args.embed is None: self.subscriber = Subscriber("datasets", self.sub_init, self.sub_mod) self.loop.run_until_complete(self.subscriber.connect( self.args.server, self.args.port)) else: self.ipc.subscribe(self.datasets, self.sub_init, self.sub_mod) def unsubscribe(self): if self.args.embed is None: self.loop.run_until_complete(self.subscriber.close()) def run(self): self.args_init() self.quamash_init() try: self.ipc_init() try: self.create_main_widget() self.subscribe() try: self.loop.run_forever() finally: self.unsubscribe() finally: self.ipc_close() finally: self.loop.close()
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