1

Searching on GUI-based http server (as I need to do some GUI notification from my program, when rest GET would be catched). Found this solution. How to do something like this properly (variant below isn't work):

@app.route('/')
def main():
    # Create declarative and use it how I want

    view = QDeclarativeView()
    # Create an URL to the QML file
    url = QUrl('view.qml')
    # Set the QML file and show
    view.setSource(url)
    view.show()
Juriy
  • 565
  • 1
  • 5
  • 17

1 Answers1

0

The GUI creates an infinite loop, in case qt (pyqt4, pyqt5 and pyside) do it through the function exec_(), Flask also needs the same reason why both can not coexist in the same thread, therefore We created a new thread for Flask.

In this thread we will send the data through signals to the main thread and this will be responsible for displaying the data.

The following code implements the above.

*.py

from flask import Flask
from PySide import QtCore, QtGui, QtDeclarative

import sys

app = Flask(__name__)

@app.route('/')
def main():
    w = FlaskThread._single
    date = QtCore.QDateTime.currentDateTime()
    w.signal.emit("date: {} function: {}".format(date.toString("dd.MM.yyyy hh:mm:ss.zzz"), "main"))
    return "Hello world!"

class FlaskThread(QtCore.QThread):
    signal = QtCore.Signal(str)
    _single = None
    def __init__(self, application):
        QtCore.QThread.__init__(self)
        if FlaskThread._single:
            raise FlaskThread._single
        FlaskThread._single = self
        self.application = application

    def __del__(self):
        self.wait()

    def run(self):
        self.application.run()


def provide_GUI_for(application):
    qtapp = QtGui.QApplication(sys.argv)

    webapp = FlaskThread(application)

    view = QtDeclarative.QDeclarativeView()
    url = QtCore.QUrl('view.qml')
    view.setSource(url)
    root = view.rootObject()
    webapp.signal.connect(lambda text: root.setProperty("text", text))

    view.show()

    qtapp.aboutToQuit.connect(webapp.terminate)
    QtGui.QApplication.setQuitOnLastWindowClosed(False)

    webapp.start()

    return qtapp.exec_()


if __name__ == '__main__':
    sys.exit(provide_GUI_for(app))

view.qml

import QtQuick 1.0

Text { 
    width: 320
    height: 240
    text: "nothing"
    color: "red"
    horizontalAlignment: Text.AlignHCenter
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241