和Js交互操作

This commit is contained in:
Irony 2019-05-22 10:45:15 +08:00
parent e77811a68a
commit d2d4eda021
5 changed files with 142 additions and 1 deletions

View file

@ -55,6 +55,7 @@ encoding//QWebEngineView/GetCookie.py=utf-8
encoding//QWebEngineView/JsSignals.py=utf-8
encoding//QWebView/DreamTree.py=utf-8
encoding//QWebView/GetCookie.py=utf-8
encoding//QWebView/JsSignals.py=utf-8
encoding//QWidget/Lib/CustomPaintWidget.py=utf-8
encoding//QWidget/Lib/CustomWidget.py=utf-8
encoding//QWidget/WidgetStyle.py=utf-8

View file

@ -0,0 +1,39 @@
<!DOCTYPE html>
<html>
<head>
<title>测试</title>
<script>
// 这里绑定窗口的标题变化信号这个信号是由QWidget内部的
Bridge.windowTitleChanged.connect({fun: function(title) {
showLog("标题被修改为:" + title);
}}, "fun");
// 绑定自定义的信号customSignal
Bridge.customSignal.connect({fun: function(text) {
showLog("收到自定义信号内容:" + text);
}}, "fun");
function showLog(text) {
var ele = document.getElementById("result");
ele.value = ele.value + text + "\n";
}
</script>
</head>
<body>
<h3>1、测试修改窗口属性</h3>
windowTitle 是Qt窗口本身的属性, 当标题被修改后会触发本身的windowTitleChanged信号<br>
<input type="text" id="title" placeholder="请输入标题" />
<p></p>
<button onclick="javascript:Bridge.windowTitle = document.getElementById('title').value;">测试修改标题</button>
<h3>2、调用Python中的方法callFromJs</h3>
callFromJs(str) 函数是由Python代码中定义, 通过@pyqtSlot(str)装饰器暴露出来<br>
<button onclick="javascript:Bridge.callFromJs('test');">Bridge.callFromJs('test')</button>
<h3>3、发送自定义信号</h3>
点击底部的按钮将会发送customSignal信号出来网页中收到该信号将会在下面日志框输出内容<br>
<p>日志</p>
<textarea id="result" rows="20" cols="100"></textarea>
</body>
</html>

92
QWebView/JsSignals.py Normal file
View file

@ -0,0 +1,92 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2019年4月27日
@author: Irony
@site: https://pyqt5.com https://github.com/892768447
@email: 892768447@qq.com
@file: QWebEngineView.JsSignals
@description:
"""
import os
from time import time
from PyQt5.QtCore import QUrl, pyqtSlot, pyqtSignal
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebView
from PyQt5.QtWidgets import QMessageBox, QWidget, QVBoxLayout, QPushButton
__Author__ = 'Irony'
__Copyright__ = 'Copyright (c) 2019'
class WebView(QWebView):
customSignal = pyqtSignal(str)
def __init__(self, *args, **kwargs):
super(WebView, self).__init__(*args, **kwargs)
self.initSettings()
# 暴露接口对象
self.page().mainFrame().javaScriptWindowObjectCleared.connect(self._exposeInterface)
def _exposeInterface(self):
"""向Js暴露调用本地方法接口
"""
self.page().mainFrame().addToJavaScriptWindowObject('Bridge', self)
# 注意pyqtSlot用于把该函数暴露给js可以调用
@pyqtSlot(str)
def callFromJs(self, text):
QMessageBox.information(self, "提示", "来自js调用{}".format(text))
def sendCustomSignal(self):
# 发送自定义信号
self.customSignal.emit('当前时间: ' + str(time()))
@pyqtSlot(str)
@pyqtSlot(QUrl)
def load(self, url):
'''
eg: load("https://pyqt5.com")
:param url: 网址
'''
return super(WebView, self).load(QUrl(url))
def initSettings(self):
'''
eg: 初始化设置
'''
# 获取浏览器默认设置
settings = self.settings()
# 开启开发人员工具
settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
# 设置默认编码
settings.setDefaultTextEncoding('UTF-8')
class Window(QWidget):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
layout = QVBoxLayout(self)
self.webview = WebView(self)
layout.addWidget(self.webview)
layout.addWidget(QPushButton(
'发送自定义信号', self, clicked=self.webview.sendCustomSignal))
self.webview.windowTitleChanged.connect(self.setWindowTitle)
self.webview.load(QUrl.fromLocalFile(
os.path.abspath('Data/JsSignals.html')))
if __name__ == "__main__":
from PyQt5.QtWidgets import QApplication
import sys
app = QApplication(sys.argv)
w = Window()
w.show()
w.move(100, 100)
sys.exit(app.exec_())

View file

@ -17,4 +17,13 @@
从`page()`中得到`QNetworkAccessManager`,在从中得到`QNetworkCookieJar`,
最后得到cookie,当然也可以设置自己的`QNetworkCookieJar`
![GetCookie](ScreenShot/GetCookie.png)
![GetCookie](ScreenShot/GetCookie.png)
## 3、和Js交互操作
[运行 JsSignals.py](JsSignals.py)
通过`QWebFrame`的`addToJavaScriptWindowObject`函数提供进行Python对象和Javascript的交互
具体看代码中的注释
![JsSignals](ScreenShot/JsSignals.gif)

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 KiB