2017-07-10 16 views
0

在基于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() 
+0

您是否使用PyQt4的或pyqt5?你想使用qml吗? – eyllanesc

+0

想要使用qml,非常基本的功能,我认为在这种情况下没有区别,如果我使用puqt4或pyqt5。同时我实际上使用了piside。 – Juriy

+0

QDeclarativeView在PyQt5中不存在。 – eyllanesc

回答

0

的GUI创建一个无限循环,如果QT(PyQt4的,pyqt5和pyside)做到这一点通过功能exec_(),瓶也需要两者不能在同一个线程中共存的原因相同,因此我们为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 
} 
+0

正如我认为有信号..谢谢你漂亮的实施。 – Juriy