当前位置:   article > 正文

pyqt5 QWebEngineView 重写mousepressevent捕获鼠标点击事件,无响应_python qwebengineview 点击事件

python qwebengineview 点击事件
QWebEngineView 加载网页后,重写mousepressevent捕获鼠标点击事件,无响应原因是

QWebEngineView在加载界面后,被本身的child接收了该事件,

解决办法:同过重载event,截取QEvent::ChildAdded事件

  1. from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
  2. from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings
  3. from PyQt5.QtCore import Qt
  4. from PyQt5.QtCore import QTimer, QEventLoop, QObject, pyqtSignal, QEvent
  5. class QWebEngineView_New(QWebEngineView):
  6. js_result = pyqtSignal(str)
  7. def __init__(self, parent=None):
  8. super(QWebEngineView_New, self).__init__(parent)
  9. self.load(QtCore.QUrl())
  10. self.focusProxy().installEventFilter(self)
  11. self.setMouseTracking(True) #追踪鼠标
  12. self._glwidget = None
  13. def eventFilter(self, source, event):
  14. # QWebEngineView 覆盖了 event() 方法,所以它没有调用 QWidget 事件处理程序
  15. if event.type() == QEvent.MouseButtonPress:
  16. print(f'eventtype:{event.type()} ChildAdded: {QEvent.ChildAdded} MouseButtonPress:{QEvent.MouseButtonPress}')
  17. print(source is self._glwidget)
  18. if event.type() == QEvent.ChildAdded and event.child().isWidgetType():
  19. self._glwidget = event.child()
  20. self._glwidget.installEventFilter(self)
  21. elif (event.type() == QEvent.MouseButtonPress):
  22. #print(Qt.LeftButton)
  23. #print(QEvent.MouseButtonPress)
  24. #print('event_type:', event.type())
  25. print('web-view mouse-press:', event.pos())
  26. pos = event.pos()
  27. self._run_javascript(pos.x(), pos.y())
  28. return super(QWebEngineView_New, self).eventFilter(source, event)
  29. def _run_javascript(self, x, y):
  30. # 在这里写入你的 JavaScript 代码
  31. # js_code = "alert('Hello from JavaScript!');"
  32. js_code = '''function myFunction(){return document.elementFromPoint(%s, %s).textContent;}myFunction();'''
  33. js_code = js_code % (x, y)
  34. # self.fatherWindow.tabWidget.currentWidget().page().runJavaScript(js_code, self.js_callback)
  35. self.page().runJavaScript(js_code, self.js_callback)
  36. def js_callback(self, result):
  37. # 获取点击部位的内容
  38. if not result:
  39. return
  40. jsresult = result.replace('\n', '')
  41. print('jsresult :', jsresult )
  42. self.js_result.emit(jsresult ) # 将内容传给信号槽
  43. if __name__ == "__main__":
  44. import sys
  45. app = QtWidgets.QApplication(sys.argv)
  46. view = QWebEngineView_New()
  47. view.load(QtCore.QUrl("https://www.baidu.com"))
  48. view.show()
  49. sys.exit(app.exec_())

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号