Search code examples
pythonpyqtpyqt5connexion

How to run a PyQt app with connexion module?


I want to run a connexion server in a Qt app, but i don't know how doin this.

I've tried stuff like below, but execution is stuck in "connexion loop" and button "close server" won't show unit i ctrl-c connexion server in console... :

import sys, os

import connexion
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QPushButton

connex_app = connexion.App("Hello World")

class OpennoteserverDlg(QPushButton):

    def __init__(self, parent=None):
        super().__init__(
                "&Close Server", parent)

        self.clicked.connect(self.close)
        self.setWindowTitle("Opennote-server")

app = QApplication(sys.argv)
form = OpennoteserverDlg()
form.show()

app.connex_app = connex_app
app.connex_app.run()
app.exec_()

Solution

  • The run() method is blocking, so it will not allow the GUI event loop to be executed, causing several GUI tasks not to work correctly. The solution is to run the server in another thread

    import signal
    import sys
    import threading
    
    import connexion
    
    from PyQt5.QtWidgets import QApplication, QPushButton
    
    
    class OpennoteserverDlg(QPushButton):
        def __init__(self, parent=None):
            super().__init__("&Close Server", parent)
    
            self.clicked.connect(self.close)
            self.setWindowTitle("Opennote-server")
    
    
    def run_server():
        connex_app = connexion.App("Hello World")
        connex_app.run()
    
    
    if __name__ == "__main__":
    
        signal.signal(signal.SIGINT, signal.SIG_DFL)
    
        app = QApplication(sys.argv)
    
        form = OpennoteserverDlg()
        form.show()
    
        threading.Thread(target=run_server, daemon=True).start()
        sys.exit(app.exec_())