Skip to content

PySide2嵌入HTML使用Flask响应

501字约2分钟

前后端

2021-10-15

project 结构

  • root
    • dist
      • css
      • fonts
      • img
      • js
        • favicon.ico
        • index.html
    • pyside_flask_desk
      • __init__.py
    • app.py
    • run_test.py
  1. dist: 文件夹为前端内容, 其中包括前端的html, css, js等内容
  2. pyside_flask_desk: 文件夹内 \_\_init\_\_.py 文件为创建Qt窗口, 并使用线程启动flask
  3. run_test.py: 为程序主入口

程序主入口 run_test.py

#! -*- coding:utf-8 -*-
import sys
import os
from app import *
from PySide2.QtCore import QFileInfo
from pyside_flask_desk import init_gui

sys.path.append((os.path.dirname(os.path.abspath(os.path.dirname(__file__)))).replace("\\", "/"))


if __name__ == '__main__':
    root = QFileInfo(__file__).absolutePath()
    init_gui(app, port=5000, window_title="钓鱼城", icon=root + "/dist/favicon.ico")

注意

其中icon的路径必须使用绝对路径, 相对路径无法加载

init_gui 函数创建Qt主窗口, 线程启动flask

import sys
from PySide2 import QtCore, QtWidgets, QtGui, QtWebEngineWidgets
import socket


class ApplicationThread(QtCore.QThread):
    def __init__(self, application, port=5000):
        super(ApplicationThread, self).__init__()
        self.application = application
        self.port = port

    def __del__(self):
        self.wait()

    def run(self):
        # flask app.run()
        self.application.run(port=self.port, threaded=True)


class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self, root_url):
        super(WebPage, self).__init__()
        self.root_url = root_url

    def home(self):
        self.load(QtCore.QUrl(self.root_url))

        
def init_gui(application, icon, port, width=800, height=600,
             window_title="PyFladesk", argv=None):
    if argv is None:
        argv = sys.argv

    # 创建主窗口框架
    qtapp = QtWidgets.QApplication(argv)
    
    # 线程启动flask
    webapp = ApplicationThread(application, port)
    webapp.start()
    # connect function:关闭qtapp窗口时, 调用flask的终止
    qtapp.aboutToQuit.connect(webapp.terminate) 

    # 创建主窗口, 并设置大小, 标题, icon
    window = QtWidgets.QMainWindow()
    window.resize(width, height)
    window.setWindowTitle(window_title)
    window.setWindowIcon(QtGui.QIcon(icon))

    # 创建WebEngineView并套入主窗口
    webView = QtWebEngineWidgets.QWebEngineView(window)
    window.setCentralWidget(webView)

    # 通过home()加载url,并将page放入view
    page = WebPage('http://localhost:{}'.format(port))
    page.home()
    webView.setPage(page)
	
    # 显示窗口
    window.show()
    return qtapp.exec_()

app.py flask后端响应

from flask import Flask,  render_template

app = Flask(__name__, static_url_path='', static_folder='dist', template_folder='dist')


app.config['EXPLAIN_TEMPLATE_LOADING'] = True

# 路由
@app.route('/')
def greet():
    return render_template('index.html')

注意

其中static_url_path=''不可缺少, 是由于前端html中将资源加载的目录写死为根目录.

static_folder='dist', template_folder='dist'根据具体project的实际情况写html, css等文件在的文件夹即可. 该文件为flask接口主文件, 接口开发写法跟之前通用版本相同.

最终效果:

钓鱼城系统Qt版本首页
钓鱼城系统Qt版本首页