繁体   English   中英

PySide6 我可以将回调与其调用方方法同步吗?

[英]PySide6 Can i synchronize a callback with its caller method..?

这是我的代码。

from PySide6 import QtGui,QtCore,QtWidgets,QtWebEngineWidgets
from PySide6.QtWebEngineCore import QWebEngineDownloadRequest, QWebEnginePage

# all these are in some class
self.myView = QtWebEngineWidgets.QWebEngineView()

def getValue(self):
    self.myView.page().runJavaScript(
        '''
        (function () {
            finds = document.getElementsByClassName('ps');
            if (finds.length > 0) return finds[0].offsetWidth;
            return -1;
        })();
        ''', 0, self._getvalueCallback)
    # i want to wait for the callback and return the value.
    # want to make it to work synchronously.

def _getvalueCallback(self, value):
    if type(value) is float:
        self._value = int(value)
    else:
        self._value = -1

这可能吗..? 我尝试使用threading.Event但没有工作,因为event.waiting()只是阻塞了线程和回调。

您可以使用 QEventLoop:

from collections import deque
from functools import partial

from PySide6 import QtGui, QtCore, QtWidgets, QtWebEngineWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.myView = QtWebEngineWidgets.QWebEngineView()
        self.setCentralWidget(self.myView)
        self.myView.load(QtCore.QUrl("https://stackoverflow.com/"))

        QtCore.QTimer.singleShot(4000, self.handle_timeout)

    def handle_timeout(self):
        value = self.getValue()
        print("value:", value)

    def getValue(self):
        q = deque()
        loop = QtCore.QEventLoop()
        self.myView.page().runJavaScript(
            """
            (function () {
                finds = document.getElementsByClassName('ps');
                if (finds.length > 0) return finds[0].offsetWidth;
                return -1;
            })();
            """,
            0,
            partial(self._getvalueCallback, loop, q),
        )
        loop.exec()
        return q.pop()

    def _getvalueCallback(self, loop, q, value):
        q.append(int(value) if isinstance(value, float) else -1)
        loop.quit()


if __name__ == "__main__":
    app = QtWidgets.QApplication()
    mw = MainWindow()
    mw.show()
    app.exec()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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