GUI创建一个无限循环,以防qt(pyqt4、pyqt5和pyside)通过函数执行
exec_()
,Flask也需要相同的原因,为什么两者不能在同一个线程中共存,因此我们为Flask创建了一个新线程。
在这个线程中,我们将通过信号将数据发送到主线程,主线程负责显示数据。
以下代码实现了上述功能。
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))
视图.qml
import QtQuick 1.0
Text {
width: 320
height: 240
text: "nothing"
color: "red"
horizontalAlignment: Text.AlignHCenter
}