PyQt 在 Main 中嵌入 QWebEngineView Window

PyQt embed QWebEngineView in Main Window

我来自 tkinter 背景,所有东西都可以放在框架中。

如何让我当前的工作代码结果(启动页面的 Web 引擎视图,在本例中为 google)位于主 window 中,如图所示?例如,我希望将 WebEngine 安装在“绿色”盒子中。

工作代码包括所有使用的版本

"""
Python version - 3.7.3
PyQt5            5.15.3
PyQt5-Qt         5.15.2
PyQt5-sip        12.8.1
PyQtWebEngine    5.15.3
PyQtWebEngine-Qt 5.15.2
"""

import sys

from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView

url = 'https://google.com'

app = QApplication(sys.argv)

# QWebEngineView
browser = QWebEngineView()
browser.load(QUrl(url))
browser.show()

sys.exit(app.exec_())

您必须使用 QGridLayout:

import sys

from PyQt5.QtWidgets import QApplication, QGridLayout, QMainWindow, QTextEdit, QWidget
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView

url = "https://google.com"

app = QApplication(sys.argv)

w = QMainWindow()

browser = QWebEngineView()
browser.load(QUrl(url))

central_widget = QWidget()
w.setCentralWidget(central_widget)

lay = QGridLayout(central_widget)
lay.addWidget(browser, 0, 0, 2, 1)
lay.addWidget(QTextEdit(), 0, 1)
lay.addWidget(QTextEdit(), 1, 1)

lay.setColumnStretch(0, 1)
lay.setColumnStretch(1, 1)

lay.setRowStretch(0, 1)
lay.setRowStretch(1, 1)

w.show()

sys.exit(app.exec_())

您可以使用垂直布局来容纳两个红色框。然后使用水平布局来容纳 QWebEngineView 和垂直布局。 Zetcode 有一个 good tutorial for layouts。从@eyllanesc 大量借用的代码:

import sys

from PyQt5.QtWidgets import (QApplication, QMainWindow, 
                             QHBoxLayout, QVBoxLayout,
                             QTextEdit, QWidget)
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView

url = "https://google.com"

app = QApplication(sys.argv)

w = QMainWindow()

browser = QWebEngineView()
browser.load(QUrl(url))

central_widget = QWidget()
w.setCentralWidget(central_widget)

vertical = QVBoxLayout()
vertical.addWidget(QTextEdit())
vertical.addWidget(QTextEdit())

horizontal = QHBoxLayout(central_widget)
horizontal.addWidget(browser)
horizontal.addLayout(vertical)

w.show()

sys.exit(app.exec_())