当前位置:网站首页>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)

边栏推荐
- 株洲市九方中学开展防溺水、消防安全教育培训活动
- 微信小程序开发公司你懂得选择吗?
- 怎样巧用断言+异常处理类,使代码更简洁!(荣耀典藏版)
- HCIA comprehensive experiment (take Huawei ENSP as an example)
- 凡尔赛天花板:“毕业两年月薪才35K,真是没出息啊~~”
- 节省70%的显存,训练速度提高2倍!浙大&阿里提出在线卷积重新参数化OREPA,代码已开源!(CVPR 2022 )
- 入行4年,跳槽2次,我摸透了软件测试这一行~
- 聊一聊数据库的行存与列存
- Week 6 Linear Models for Classification (Part B)
- Research on intangible cultural heritage image classification based on multimodal fusion
猜你喜欢

Msfvenom makes master and controlled terminals

I have been in the industry for 4 years and changed jobs twice. I have understood the field of software testing~

两个全局变量__dirname和__filename 、fs模块常用功能进一步介绍

怎样巧用断言+异常处理类,使代码更简洁!(荣耀典藏版)

小程序开发需要什么技术

Introduction to wechat applet development, develop your own applet

Miscellaneous records of powersploit, evaluation, weevery and other tools in Kali

Wechat applet development company, do you know how to choose?

网格数据生成函数meshgrid

Leetcode linked list question - interview question 02.07. linked list intersection (learn linked list by one question and one article)
随机推荐
Construction of Chinese traditional embroidery classification model based on xception TD
MySQL
【英雄哥七月集训】第 28天:动态规划
ST法国三座工厂大罢工,芯片缺货情况或将更加严重!
fluke dtx-1800测试精度有必要进行原厂校准吗?
作价11.5亿元,1206件设备注入合资公司!SK海力士抢食大陆晶圆代工市场!
微星宝安工厂失火!官方回应:无人员受伤,产线不受影响!
Meta opens the project aria pilot dataset and will develop real-time 3D maps in the future
B+ tree height calculation of MySQL
Edited by vimtutor
Mysql的B+树高度计算
Apple M1 processor details: performance and energy efficiency have doubled, and Intel Core i9 is no match!
For the next generation chromebook, MediaTek launched new chipsets mt8192 and mt8195
Vimtutor编辑
Detailed explanation of JVM memory layout (glory collection version)
Talk about row storage and column storage of database
世界肝炎日 | 基层也能享受三甲资源,智慧医疗系统如何解决“看病难”?
日志瘦身神操作:从5G优化到1G到底是怎么做到的!(荣耀典藏版)
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势
Nano gold coupled antibody / protein Kit (20nm, 1mg/100 μ g/500 μ G coupling amount) preparation