赞
踩
QWebEngineView 加载网页后,重写mousepressevent捕获鼠标点击事件,无响应原因是
QWebEngineView在加载界面后,被本身的child接收了该事件,
解决办法:同过重载event,截取QEvent::ChildAdded事件
- from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
- from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings
- from PyQt5.QtCore import Qt
- from PyQt5.QtCore import QTimer, QEventLoop, QObject, pyqtSignal, QEvent
-
- class QWebEngineView_New(QWebEngineView):
- js_result = pyqtSignal(str)
- def __init__(self, parent=None):
- super(QWebEngineView_New, self).__init__(parent)
- self.load(QtCore.QUrl())
- self.focusProxy().installEventFilter(self)
- self.setMouseTracking(True) #追踪鼠标
- self._glwidget = None
-
- def eventFilter(self, source, event):
- # QWebEngineView 覆盖了 event() 方法,所以它没有调用 QWidget 事件处理程序
- if event.type() == QEvent.MouseButtonPress:
- print(f'eventtype:{event.type()} ChildAdded: {QEvent.ChildAdded} MouseButtonPress:{QEvent.MouseButtonPress}')
- print(source is self._glwidget)
- if event.type() == QEvent.ChildAdded and event.child().isWidgetType():
- self._glwidget = event.child()
- self._glwidget.installEventFilter(self)
- elif (event.type() == QEvent.MouseButtonPress):
- #print(Qt.LeftButton)
- #print(QEvent.MouseButtonPress)
- #print('event_type:', event.type())
- print('web-view mouse-press:', event.pos())
- pos = event.pos()
- self._run_javascript(pos.x(), pos.y())
- return super(QWebEngineView_New, self).eventFilter(source, event)
-
- def _run_javascript(self, x, y):
- # 在这里写入你的 JavaScript 代码
- # js_code = "alert('Hello from JavaScript!');"
- js_code = '''function myFunction(){return document.elementFromPoint(%s, %s).textContent;}myFunction();'''
- js_code = js_code % (x, y)
- # self.fatherWindow.tabWidget.currentWidget().page().runJavaScript(js_code, self.js_callback)
- self.page().runJavaScript(js_code, self.js_callback)
-
- def js_callback(self, result):
- # 获取点击部位的内容
- if not result:
- return
- jsresult = result.replace('\n', '')
- print('jsresult :', jsresult )
- self.js_result.emit(jsresult ) # 将内容传给信号槽
-
- if __name__ == "__main__":
- import sys
- app = QtWidgets.QApplication(sys.argv)
- view = QWebEngineView_New()
- view.load(QtCore.QUrl("https://www.baidu.com"))
- view.show()
- sys.exit(app.exec_())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。