我是靠谱客的博主 悲凉大米,最近开发中收集的这篇文章主要介绍pyside2中打开的外部页面WebEngineView与python部分的交互,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

pyside2中打开的外部页面WebEngineView与python部分的交互

19年末在涉及到python中打开外部页面的应用时,花了很多时间在网上找可实现的方式,从pyqt5到pyside2,最后是从国外的网站找到了可用的demo,和大家分享一下.(python3以上才支持pyside2)
附上参考的网址:https://justcode.nimbco.com/PyInstaller-with-Qt5-WebEngineView-using-PySide2/

首先在python代码中

import os
from pathlib import Path
from PySide2.QtWidgets import QApplication
from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PySide2.QtWebChannel import QWebChannel
from PySide2.QtCore import QUrl, Slot, QObject, QUrl

data_dir = Path(os.path.abspath(os.path.dirname(__file__))) / 'data'

class Handler(QObject):
    def __init__(self, *args, **kwargs):
        super(Handler, self).__init__(*args, **kwargs)

    #@Slot是关键,是js中调用的接口,经测试,只能传一个参数,传对象参数时需要把它专为json字符串
    @Slot(str, result=str)
    def sayHello(self, name):        
        return f"Hello from the other side, {name}"

class WebEnginePage(QWebEnginePage):
    def __init__(self, *args, **kwargs):
        super(WebEnginePage, self).__init__(*args, **kwargs)

    def javaScriptConsoleMessage(self, level, message, lineNumber, sourceId):
        print("WebEnginePage Console: ", level, message, lineNumber, sourceId)

if __name__ == "__main__":
    
    # Set up the main application
    app = QApplication([])
    app.setApplicationDisplayName("Greetings from the other side")

    # Use a webengine view
    view = QWebEngineView()
    view.resize(500,200)

    # Set up backend communication via web channel
    handler = Handler()
    #channel是页面中可以拿到的,顾名思义,一个通道
    channel = QWebChannel()
    # Make the handler object available, naming it "backend"
    channel.registerObject("backend", handler)

    # Use a custom page that prints console messages to make debugging easier
    page = WebEnginePage()
    page.setWebChannel(channel)
    view.setPage(page)

    # Finally, load our file in the view
    url = QUrl.fromLocalFile(f"{data_dir}/index.html")
    view.load(url)
    view.show()

    app.exec_()

然后是html和js中的代码

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta content="IE=edge" http-equiv="X-UA-Compatible">
  //qwebchannel.js是必须要导入的
  <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
  <title>Hello</title>
</head>
<body style="text-align: center; font-size: 1.5rem">
  <h2>
    My name is: <input id="nameInput">
  </h2>
<input type="file">
  <div id="result">
  </div>
  <button id="sayHello" style="font-size: 1.5rem">
    Say Hello
  </button>
  <script>
    document.addEventListener('contextmenu', event => event.preventDefault());
    document.addEventListener('DOMContentLoaded', function () {
      
      const nameInput = document.getElementById('nameInput');
      const result = document.getElementById('result'); 
      const sayHello = document.getElementById('sayHello');
      
      // Obtain the exposed python object interface(拿到channel中注册的对象)
      const getBackend = new Promise((resolve, reject) => {
        new QWebChannel(qt.webChannelTransport, 
          (channel) => resolve(channel.objects.backend));
      })

      // Call to the other side(调用python方法,并拿到返回值)
      sayHello.addEventListener('click', function(){
        result.textContent = '';
        getBackend.then((backend) => {
          backend.sayHello(nameInput.value, (prediction) => {
            result.textContent = prediction;
          });              
        })
      });
    });
  </script>
</body>
</html>

js中的那部分代码在angularjs的框架中可以直接书写
所必须的qwebchannel.js可以在附件里找到

最后

以上就是悲凉大米为你收集整理的pyside2中打开的外部页面WebEngineView与python部分的交互的全部内容,希望文章能够帮你解决pyside2中打开的外部页面WebEngineView与python部分的交互所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部