PyQt5:QWebEngineView窗口调整时出现显示失真问题
Hey there, let's fix that QWebEngineView distortion issue when resizing your window. I've dealt with similar rendering glitches in PyQt5 before, so here are a few practical solutions you can test out:
1. Force the web page to re-render on resize
Sometimes the underlying web page doesn't detect the window size change properly, leading to distorted rendering. You can manually trigger a resize event for the page and force a repaint by overriding the resizeEvent in your WebView class:
import sys from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout from PyQt5.QtWebEngineWidgets import QWebEngineView class IFace(QWidget): def __init__(self): super().__init__() self.setGeometry(300, 300, 1000, 500) self.view = WebView(self) self.setLayout(QGridLayout(self)) self.layout().addWidget(self.view, 0, 0) self.layout().setContentsMargins(0, 0, 0, 0) class WebView(QWebEngineView): def __init__(self, parent=None): super().__init__(parent) def resizeEvent(self, event): super().resizeEvent(event) # Trigger a resize event for the web page to re-layout self.page().runJavaScript("window.dispatchEvent(new Event('resize'));") # Force the widget to repaint self.update() if __name__ == "__main__": app = QApplication(sys.argv) window = IFace() window.show() sys.exit(app.exec_())
2. Tweak WebEngine settings to disable problematic hardware acceleration
In some environments, hardware acceleration can cause rendering artifacts during resizing. Try disabling related settings in your WebView:
from PyQt5.QtWebEngineWidgets import QWebEngineSettings class WebView(QWebEngineView): def __init__(self, parent=None): super().__init__(parent) # Disable hardware-accelerated features that might cause distortion self.settings().setAttribute(QWebEngineSettings.Accelerated2dCanvasEnabled, False) self.settings().setAttribute(QWebEngineSettings.WebGLEnabled, False) # Enable smooth scrolling/rendering self.settings().setAttribute(QWebEngineSettings.SmoothScrollingEnabled, True)
3. Ensure the WebView has the right size policy
Double-check that your WebView is set to expand with the window. Add this line to your IFace class's __init__ method:
from PyQt5.QtWidgets import QSizePolicy # Inside IFace.__init__ self.view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
This makes sure the web view takes up all available space in the layout and resizes correctly with the window.
4. Update your PyQt5/PyQtWebEngine version
Sometimes this is a known bug in older versions of Qt WebEngine. Try upgrading to the latest stable release:
pip install --upgrade pyqt5 pyqtwebengine
Start with the first solution—it's the most likely fix for resize-related distortion. If that doesn't work, try disabling hardware acceleration next.
内容的提问来源于stack exchange,提问作者Dragon

