Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Use an asyncio loop at the same time as a PySide application
Qt 6.11 is out! See what's new in the release blog

Use an asyncio loop at the same time as a PySide application

Scheduled Pinned Locked Moved Unsolved Qt for Python
2 Posts 2 Posters 243 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Mahmoud_213
    wrote on last edited by
    #1

    Hi everybody,

    I am trying to create a xmpp client using the slixmpp library which uses Asyncio but the loop of Asyncio used for slixmpp client module prevents the graphics application code from running so that if I put the slixmpp loop on the graphics window doesn't show, and if I put the graphics window loop on the slixmpp client doesn't launch.

    Here is my code with the loop of slixmpp client commented.

    # Slixmpp: The Slick XMPP Library
    # Copyright (C) 2010  Nathanael C. Fritz
    # This file is part of Slixmpp.
    # See the file LICENSE for copying permission.
    
    from PySide6.QtWidgets import (QApplication, QWidget, QMainWindow, QLineEdit, QPlainTextEdit, QPushButton,
    QVBoxLayout)
    import PySide6.QtAsyncio as QtAsyncio
    
    import logging
    from getpass import getpass
    from argparse import ArgumentParser
    
    import asyncio
    import slixmpp
    import sys
    
    class ChatWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            w=QWidget()
            main_layout=QVBoxLayout()
            w.setLayout(main_layout)
            self.setCentralWidget(w)
    
            self.messages_box=QPlainTextEdit()
            self.messages_box.setReadOnly(1)
            main_layout.addWidget(self.messages_box)
    
            self.message_to_send=QLineEdit()
            main_layout.addWidget(self.message_to_send)
    
            button=QPushButton("Envoyer")
            button.clicked.connect(self.send_message)
            main_layout.addWidget(button)
    
            button=QPushButton("Quitter")
            button.clicked.connect(self.quit_app)
            main_layout.addWidget(button)
    
        def send_message(self):
            "Envoi d'un message"
    
        def quit_app(self):
            self.destroy()
            sys.exit(0)
    
    class EchoBot(slixmpp.ClientXMPP):
    
        """
        A simple Slixmpp bot that will echo messages it
        receives, along with a short thank you message.
        """
    
        def __init__(self, jid, password):
            slixmpp.ClientXMPP.__init__(self, jid, password)
    
            # The session_start event will be triggered when
            # the bot establishes its connection with the server
            # and the XML streams are ready for use. We want to
            # listen for this event so that we we can initialize
            # our roster.
            self.add_event_handler("session_start", self.start)
    
            # The message event is triggered whenever a message
            # stanza is received. Be aware that that includes
            # MUC messages and error messages.
            self.add_event_handler("message", self.message)
    
        async def start(self, event):
            """
            Process the session_start event.
    
            Typical actions for the session_start event are
            requesting the roster and broadcasting an initial
            presence stanza.
    
            Arguments:
                event -- An empty dictionary. The session_start
                         event does not provide any additional
                         data.
            """
            self.send_presence()
            await self.get_roster()
    
        def message(self, msg):
            """
            Process incoming message stanzas. Be aware that this also
            includes MUC messages and error messages. It is usually
            a good idea to check the messages's type before processing
            or sending replies.
    
            Arguments:
                msg -- The received message stanza. See the documentation
                       for stanza objects and the Message stanza to see
                       how it may be used.
            """
            if msg['type'] in ('chat', 'normal'):
                msg.reply("Thanks for sending\n%(body)s" % msg).send()
    
    # Setup the command line arguments.
    parser = ArgumentParser(description=EchoBot.__doc__)
    
    # Output verbosity options.
    parser.add_argument("-q", "--quiet", help="set logging to ERROR",
                        action="store_const", dest="loglevel",
                        const=logging.ERROR, default=logging.INFO)
    parser.add_argument("-d", "--debug", help="set logging to DEBUG",
                        action="store_const", dest="loglevel",
                        const=logging.DEBUG, default=logging.INFO)
    
    # JID and password options.
    parser.add_argument("-j", "--jid", dest="jid",
                        help="JID to use")
    parser.add_argument("-p", "--password", dest="password",
                        help="password to use")
    
    args = parser.parse_args()
    
    # Setup logging.
    logging.basicConfig(level=args.loglevel,
                        format='%(levelname)-8s %(message)s')
    
    if args.jid is None:
        args.jid = input("Votre JID: ")
    if args.password is None:
        args.password = input("Votre mot de passe: ")
    
    # Setup the EchoBot and register plugins. Note that while plugins may
    # have interdependencies, the order in which you register them does
    # not matter.
    xmpp = EchoBot(args.jid, args.password)
    xmpp.register_plugin('xep_0030') # Service Discovery
    xmpp.register_plugin('xep_0004') # Data Forms
    xmpp.register_plugin('xep_0060') # PubSub
    xmpp.register_plugin('xep_0199') # XMPP Ping
    
    # Connect to the XMPP server and start processing XMPP stanzas.
    xmpp.connect()
    
    app=QApplication()
    
    w=ChatWindow()
    w.show()
    
    app.exec()
    
    #asyncio.get_event_loop().run_forever()
    
    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      Did you check the Eratosthenes example ?

      It used the QtAsyncio.run method to start the event loop and asyncio integration.

      When reading the example, check that you have the asyncio implementation shown as there are two different implementations shown.

      Hope it helps

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved