analitics

Pages

Monday, December 6, 2021

Python Qt5 : QtWebEngineWidgets and button.

In this tutorial I will show you how to add a simple button to the application build with QtWebEngineWidgets using the addWidget to a QVBoxLayout with a lay variable.
The button named PyQt5 nothing button is not connected.
Let's see this default example:
import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineSettings, QWebEngineView

class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWebEngineView()
        lay = QVBoxLayout(self)
        lay.addWidget(self.view)
        self.resize(640, 480)

class WebEnginePage(QWebEnginePage):
    def createWindow(self, _type):
        w = Widget()
        w.show()
        return w.view.page()

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=None)

        self.setWindowTitle("PyQt5 ... another example !!")
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        button = QPushButton('PyQt5 nothing button', self)
        button.setToolTip('This is an example button')

        self.webview = QWebEngineView()
        self.page = WebEnginePage()
        self.webview.setPage(self.page)
        self.webview.settings().setAttribute(
            QWebEngineSettings.FullScreenSupportEnabled, True
        )

        self.webview.load(
            QUrl("https://www.youtube.com/watch?v=BVT3acNFzqc?rel=0&showinfo=0")
        )

        lay = QVBoxLayout(central_widget)
        lay.addWidget(button)
        lay.addWidget(self.webview)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

if __name__ == "__main__":
    main()