1

I'm using Python in Jupyter notebook and Chrome browser, coding pyqt5 app. In some parts of the code, I need to use QWebEngineView for HTML Combobox widget ( not using Qcombox() ). The next code is when select an option from the combobox and click the "Print Selected Value" button, the selected value should be printed in the browser console. However, no value printed when click on the button. How can fix this issue?

The code:

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView    
from PyQt5.QtWidgets import QApplication, QMainWindow

html = """
<!DOCTYPE html>
<html>
<head>
    <title>HTML ComboBox</title>
    <script>
        function printSelectedValue() {
            var combobox = document.getElementById("myComboBox");
            var selectedValue = combobox.value;
            console.log("Selected Value: " + selectedValue);
        }
    </script>
</head>
<body>
    <select id="myComboBox">
        <option value="Option 1">Option 1</option>
        <option value="Option 2">Option 2</option>
        <option value="Option 3">Option 3</option>
    </select>

    <button onclick="printSelectedValue()">Print Selected Value</button>
</body>
</html>
"""


app = QApplication(sys.argv)
web_engine_view = QWebEngineView()
web_engine_view.setHtml(html)
web_engine_view.show()

sys.exit(app.exec_())
John
  • 107
  • 1
  • 14

1 Answers1

1

QWebEngineView widget in PyQt5 does not provide a way to communicate directly between the HTML content and the Python code.

    import sys

    from PyQt5.QtCore import QUrl, QObject, pyqtSlot
    from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
    from PyQt5.QtWebChannel import QWebChannel
    from PyQt5.QtWidgets import QApplication, QMainWindow
........
..........
........
    app = QApplication(sys.argv)

    web_engine_view = QWebEngineView()
    page = QWebEnginePage(web_engine_view)
    channel = QWebChannel()
    my_object = MyObject()
    channel.registerObject("myObject", my_object)
    page.setWebChannel(channel)
    web_engine_view.setPage(page)
    web_engine_view.setHtml(html)
    web_engine_view.show()

    sys.exit(app.exec_())
  • That looks promising. Many thanks. Does MyObject() means we need to call Qobject class? – John Jun 20 '23 at 15:09
  • 1
    Yes, in order to create an object that can be registered with the QWebChannel, you need to inherit from the QObject class provided by PyQt5. – hilmi uğur Jun 21 '23 at 06:11