简体   繁体   中英

PyQt embed QWebEngineView in Main Window

I'm coming from a tkinter background where everything can be put in a frame.

How can I get my current working codes result (which launches a WebEngine View of a page, google in this instance) to sit inside a main window like shown in the image? Going by the image I want the WebEngine to be housed in the "Green" Box for example.

Pyqt 布局

Working code including all versions used

"""
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_())

You have to use a 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_())

You could use a vertical layout to hold the two red boxes. And then use a horizontal layout to hold the QWebEngineView and the vertical layout. Zetcode has a good tutorial for layouts . Code heavily borrowed from @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_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM