如何使用flask-desktop创建新窗口

时间:2017-07-10 05:55:44

标签: python flask pyside pyqt5

在基于GUI的http服务器上进行搜索(因为我需要从我的程序中执行一些GUI通知,以便在休息时获取GET)。找到this解决方案。如何正确地做这样的事情(下面的变体不起作用):

@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()

1 个答案:

答案 0 :(得分:0)

GUI创建一个无限循环,如果qt(pyqt4,pyqt5和pyside)通过函数exec_()执行,Flask也需要同样的原因,为什么两者不能在同一个线程中共存,因此我们创建了Flask的新主题。

在这个线程中,我们将通过信号将数据发送到主线程,这将负责显示数据。

以下代码实现了上述内容。

<强> *。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
}