代码之家  ›  专栏  ›  技术社区  ›  Juriy

如何使用flask desktop创建新窗口

  •  1
  • Juriy  · 技术社区  · 8 年前

    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 回复  |  直到 8 年前
        1
  •  0
  •   eyllanesc    8 年前

    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
    }