当前位置:网站首页>Pyqt5 rapid development and actual combat 5.4 web page interaction
Pyqt5 rapid development and actual combat 5.4 web page interaction
2022-07-28 21:55:00 【Ding Jiaxiong】
PyQt5 Rapid development and actual combat
List of articles
5. The first 5 Chapter PyQt5 Advanced interface controls
5.4 Web interaction
PyQt 5 Use QWebEngineView Control to display HTML page , Yes, in the old version QWebView Class is no longer maintained , because QWebEngineView Use Chromium The kernel can bring users a better experience .
Qt Slowly eliminated the ancient WebKit, Instead, use WebEngine frame .WebEngine It's based on Google Chromium Engine developed , That is, Google's Chromium engine .WebEngine The framework is based on Chromium Upper Content API encapsulation , The input cost is relatively small , Can be well supported HTML 5.
stay PyQt5 Through PyQt5.QtWebKitWidgets.QWebEngineView Class to use web page controls
Qobject → QLayout → QWidget → QWenEngineView
5.4.1 QWebEngineView Common methods in class
| Method | describe |
|---|---|
| load(QUrl url) | Load the specified URL And display |
| setHtml(QString &html) | Set the content of the web page view to the specified HTML Content |
OWebEngineView Control use load() Function loads a Web page , It's actually using HTTP GET Method loading Web page . This control can load local Web Pages can also be loaded remotely externally Web page .
First, install it by yourself
pip install PyQtWebEngine -i https://pypi.tuna.tsinghua.edu.cn/simple

from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import *
view = QWebEngineView()
view.load(QUrl("https://blog.csdn.net/weixin_44226181?type=blog"))
view.show()
5.4.2 Case study —— Load and display external Web page
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle(" Open the external web page case ")
self.setGeometry(5,30,1355,730)
self.browser = QWebEngineView()
self.browser.load(QUrl("https://blog.csdn.net/weixin_44226181?type=blog"))
self.setCentralWidget(self.browser)
if __name__ == '__main__':
from pyqt5_plugins.examples.exampleqmlitem import QtCore
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())

5.4.3 Case study —— Load and display local Web page
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle(" Open the local page case ")
self.setGeometry(5,30,555,330)
self.browser = QWebEngineView()
url = r'D:/DingJiaxiong/PycharmProjects/PyQt5Study/ Web interaction /index.html'
self.browser.load(QUrl(url))
self.setCentralWidget(self.browser)
if __name__ == '__main__':
from pyqt5_plugins.examples.exampleqmlitem import QtCore
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())

5.4.4 Case study —— Load and display embedded HTML Code
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle(" Open the local page HTML Code case ")
self.setGeometry(5, 30, 555, 330)
self.browser = QWebEngineView()
self.browser.setHtml(""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> Ding Jiaxiong !</title> </head> <body> <h1> Hello,DingJiaxiong! </h1> </body> </html> """)
self.setCentralWidget(self.browser)
if __name__ == '__main__':
from pyqt5_plugins.examples.exampleqmlitem import QtCore
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())

After testing , Use QWebEngine View Object's setHtml()) Function rendering HTML When the page is , If used in the page JavaScript The code exceeds 2MB, The page rendered by the program will fail to render , A large amount of blank space will appear in the page .
5.4.5 Case study ——PyQt call JavaScript Code
adopt QWebEnginePage Class runJavaScript(str, Callable) Function can be easily implemented PyQt and HTML/JavaScript Two way communication , It has also been realized. Python Code and HTML/JavaScript Code decoupling , Facilitate the division and cooperation of developers .
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
from pyqt5_plugins.examples.exampleqmlitem import QtCore
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
# Create a application example
app = QApplication(sys.argv)
win = QWidget()
win.setWindowTitle('Web On the page JavaScript And QWebEngineView Interaction examples ')
# Create a vertical layout
layout = QVBoxLayout()
win.setLayout(layout)
# Create a QWebEngineView object
view = QWebEngineView()
view.setHtml(''' <html> <head> <title>A Demo Page</title> <script language="javascript"> // Completes the full-name control and // shows the submit button function completeAndReturnName() { var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var full = lname + ' ' + fname; document.getElementById('fullname').value = full; document.getElementById('submit-btn').style.display = 'block'; return full; } </script> </head> <body> <form> <label for="fname">First name:</label> <input type="text" name="fname" id="fname"></input> <br /> <label for="lname">Last name:</label> <input type="text" name="lname" id="lname"></input> <br /> <label for="fullname">Full name:</label> <input disabled type="text" name="fullname" id="fullname"></input> <br /> <input style="display: none;" type="submit" id="submit-btn"></input> </form> </body> </html> ''')
# Create a button to call JavaScript Code
button = QPushButton(' Set full name ')
def js_callback(result):
print(result)
def complete_name():
view.page().runJavaScript('completeAndReturnName();', js_callback)
# Button connection 'complete_name' Slot , When a button is clicked, a signal is triggered
button.clicked.connect(complete_name)
# hold QWebView and button Load into layout Layout
layout.addWidget(view)
layout.addWidget(button)
# Show windows and run app
win.show()
sys.exit(app.exec_())

5.4.6 Case study ——JavaScript call PyQt Code
JavaScript call PyOt Code , Refer to PyOt It can be connected with the loaded Web The page carries out two-way data interaction . First , Use QWebEngineView Loading objects Web After the page , You can get the form input data in the page , stay Web Page through JavaScript The code collects data submitted by users . then , stay Web On the page ,JavaScript Transfer data to by bridge connection PyQt. Last ,PyQt Receive the data transmitted by the page , After business processing , You can also return the processed data to Web page .
establish QWebChannel object
establish QWebChannel object , Register an object that needs to be bridged , In order to Web Page JavaScript Use .
channel = QWebChannel() myobj = MySharedObject() channel.registerObject("bridge",myobj) view.page().setWebChannel(channel)Create shared data PyQt object
class MySharcedObject(QWidget): def __init__(self): super(MySharcedObject, self).__init__() def _setStrValue(self,str): print(" Get page parameters : %s" % str) # Define the method of publishing strValue = pyqtProperty(str,fset = _setStrValue)Externally provided PyOt Object methods , Need to use pyqtProperty() Function to expose it .
stay PyQt5 Use in pyqtProperty() Function to define PyQt Properties in objects , How this function is used and the standard Python Module property() The same function .PyQt5.QtCore.pyqtProperty() Functional API as follows :
PyQt5.Qtcore.pyqtProperty(type[, fget=None[,fset=None[, freset=None [,fdel=None[, doc=None[, designable=True[, scriptable=True[, stored=True[,user=False[,constant=False[, final=False[,notify=None [, revision=0]]]]]]]]])Parameter description
Parameters explain type Required , Type of attribute fget Optional , To get the value of a property fset Optional , Used to set the value of the property freset Optional , Used to reset the value of the property to its default value fdel Optional , Used to delete properties Doc Optional , Property of the document string designable Optional , Set up Qt DESIGNABLE sign scriptable Optional , Set up Qt SCRIPTABLE sign stored Optional , Set up Qt STORED sign user Optional , Set up Qt USER sign constant Optional , Set up Qt CONSTANT sign final Optional , Set up Qt FINAL sign notify Optional , Unbound notification signal revision Optional , Export the version to QML Test cases
from PyQt5.QtCore import QObject, pyqtProperty class MyObject(QObject): def __init__(self, inVal=20): self.val = inVal def readVal(self): print('readVal=%s' % self.val) return self.val def setVal(self, val): print('setVal=%s' % val) self.val = val ppVal = pyqtProperty(int, readVal, setVal) if __name__ == '__main__': obj = MyObject() print('\n#1') obj.ppVal = 10 print('\n#2') print('obj.ppVal=%s' % obj.ppVal) print('obj.readVal()=%s' % obj.readVal())
Create call PyQt Of Web page
This machine starts the service directly
<!DOCTYPE html> <html lang="en"> <head> <title>A Demo Page</title> <meta charset="UTF-8"> <script src="qwebchannel.js"></script> <script> function completeAndReturnName() { var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var full = lname + ' ' + fname; document.getElementById('fullname').value = full; document.getElementById('submit-btn').style.display = 'block'; return full; } document.addEventListener("DOMContentLoaded", function () { new QWebChannel(qt.webChannelTransport, function (channel) { //alert('111 channel=' + channel ) window.bridge = channel.objects.bridge; alert('bridge=' + bridge + '\n from pyqt Parameters from =' + window.bridge.strValue); }); }); function onShowMsgBox() { //alert('window.bridge=' + window.bridge); if (window.bridge) { //alert('bridge.strValue=' + window.bridge.strValue ) ; //bridge.sayHello('999') var fname = document.getElementById('fname').value; window.bridge.strValue = fname; } } </script> </head> <body> <form> <label for=" full name ">user name:</label> <input type="text" name="fname" id="fname"></input> <br/> <input type="button" value=" Pass parameters to pyqt" onclick="onShowMsgBox()"> <input type="reset" value=' Reset '/> </form> </body> </html>
example
from PyQt5.QtWidgets import QApplication , QWidget , QVBoxLayout from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtCore import QUrl from MySharedObject import MySharedObject from PyQt5.QtWebChannel import QWebChannel import sys from pyqt5_plugins.examples.exampleqmlitem import QtCore QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) # Create a application example app = QApplication(sys.argv) win = QWidget() win.setWindowTitle('Web On the page JavaScript And QWebEngineView Interaction examples ') # Create a vertical layout layout = QVBoxLayout() win.setLayout(layout) # Create a QWebEngineView object view = QWebEngineView() htmlUrl = 'http://127.0.0.1:8000/web/index.html' view.load( QUrl( htmlUrl )) # Create a QWebChannel object , Used to deliver pyqt Parameter to JavaScript channel = QWebChannel( ) myObj = MySharedObject() channel.registerObject( "bridge", myObj ) view.page().setWebChannel(channel) # hold QWebView and button Load into layout Layout layout.addWidget(view) # Show windows and run app win.show() sys.exit(app.exec_())MySharedObject.py
from PyQt5.QtCore import QObject from PyQt5.QtCore import pyqtProperty from PyQt5.QtWidgets import QWidget,QMessageBox class MySharedObject(QWidget): def __init__( self): super( MySharedObject, self).__init__() def _getStrValue( self): # return '100' def _setStrValue( self, str ): # print(' Get page parameters :%s'% str ) QMessageBox.information(self,"Information", ' Get page parameters :%s'% str ) # You need to define the method of publishing strValue = pyqtProperty(str, fget=_getStrValue, fset=_setStrValue)

边栏推荐
- 小霸王被申请破产!公司成“老赖” ,法人被限制高消费
- Data interpolation -- normalize data of different magnitude
- RHCSA第一天
- Standard C language learning summary 10
- [极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势
- 详解visual studio 2015在局域网中远程调试程序
- Leetcode 19. delete the penultimate node of the linked list [knowledge points: speed pointer, recursion, stack]
- Log slimming operation: how to optimize from 5g to 1g! (glory Collection Edition)
- 世界肝炎日 | 基层也能享受三甲资源,智慧医疗系统如何解决“看病难”?
- 【英雄哥七月集训】第 28天:动态规划
猜你喜欢

Week 6 Linear Models for Classification (Part B)

8、 QoS queue scheduling and message discarding

LeetCode链表问题——面试题02.07.链表相交(一题一文学会链表)

Introduction to wechat applet development, develop your own applet

Is it necessary to calibrate the fluke dtx-1800 test accuracy?

Zhuzhou Jiufang middle school carried out drowning prevention and fire safety education and training activities

Matlab | basic knowledge summary I

kali里的powersploit、evasion、weevely等工具的杂项记录

物联网技术栈之网关技术

纳米金偶联抗体/蛋白试剂盒(20nm,1mg/100μg/500 μg偶联量)的制备
随机推荐
Soft test --- database (3) data operation
[Bluetooth Bluetooth development] VIII. Transmission layer of ble protocol
搞事摸鱼一天有一天
How to design workflow engine gracefully (glory Collection Edition)
微信小程序开发入门,自己开发小程序
Leetcode 19. delete the penultimate node of the linked list [knowledge points: speed pointer, recursion, stack]
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势
Cy3/cy5/cy5.5/cy7 fluorescent labeling antibody / protein Kit (10~100mg labeling amount)
SkiaSharp 之 WPF 自绘 拖曳小球(案例版)
中国农业工程学会农业水土工程专业委员会-第十二届-笔记
Research on intangible cultural heritage image classification based on multimodal fusion
使用Mock技术帮助提升测试效率的小tips,你知道几个?
酷派主动终止针对小米公司的专利侵权诉讼
Implementation of sequence table
Wechat applet development company, do you know how to choose?
Automatic filling of spare parts at mobile end
数据插值——对不同量级的数据进行归一化
技术选型Rust——事后分析
标准C语言学习总结10
Meeting notice of OA project (Query & whether to attend the meeting & feedback details)