0

I've looked through the internet and many discussions now, but I haven't seen or figured out a way to trigger a function within the PyQT window class from the outside. I'm sure this concept applies to others windows or ways to create windows in PyQT.

But in my example, I am using QWebEngineView, and want to call func_to_be_called(), which runs a javascript function in the html window, when a condition is met in the outside external_func(). I don't know how to implement this correctly though, so if anyone could help me out a bit I would greatly appreciate it! All of my attempts have been fruitless so far....

import os
import sys
import threading
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtGui
from PyQt5.QtWebChannel import QWebChannel


class Browser(QtWebEngineWidgets.QWebEngineView):

    def __init__(self, html):
        super().__init__()
        self.url = QtCore.QUrl.fromLocalFile(os.getcwd() + os.path.sep)
        self.page().setHtml(html, baseUrl=self.url)

    def func_to_be_called(self):
        self.page().runJavaScript("js_func()", self.callback)

    def callback(self, return_value):
        print(return_value)


class Window(QtWidgets.QMainWindow):

    def __init__(self, html):
        super().__init__()
        self.html = html
        self.init_widgets()
        self.init_layout()

    def init_widgets(self):
        self.browser = FloatBrowser(self.html)

    def init_layout(self):
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.browser)

        central_widget = QtWidgets.QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)


def external_func():
    while True:
        if an_external_condition_is_met:
            window.browser.func_to_be_called()  # No idea how to do this?


def start_window(html):
    app = QtWidgets.QApplication(sys.argv)
    window = Window(html)
    window.show()

    threading.Thread(target=external_func).start()  # How to implement this correctly?

    app.exec_()


if __name__ == '__main__':
    start_window(my_html)

rugdog
  • 3
  • 2

0 Answers0