How to use QWebChannel

23 Views Asked by At

I am creating an application in python code using app pycharm, displaying the interface using QWebEngineView. I don't know how to connect html code to python code, I want to be able to transmit and receive data from html code to python code. This is my python code

import os
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl
from PyQt5.QtWebChannel import QWebChannel
from MainWindow import Ui_MainWindow


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.web_view = QWebEngineView(self)
        self.setCentralWidget(self.web_view)
        self.load_local_web_page("testhtml.html")

    def load_local_web_page(self, relative_html_path):
        absolute_html_path = os.path.join(os.path.dirname(__file__), relative_html_path)
        self.web_view.setUrl(QUrl.fromLocalFile(absolute_html_path))

    def closeEvent(self, event):
        msg_box = QMessageBox()
        msg_box.setWindowTitle("Xác nhận")
        msg_box.setText("Bạn có muốn đóng ứng dụng?")
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.move(self.pos().x() + self.width() - msg_box.width() + 390, self.pos().y())
        result = msg_box.exec_()
        if result == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

This is my html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML with SVG</title>
</head>
<body>

<svg>

</svg>

<script>

</script>

</body>
</html>

I tried many times following chatGPT but no success. Hope bro can help

0

There are 0 best solutions below