我正在尝试让我的PyQt应用程序与JS通信,但无法从python获取值。我在python端有两个插槽来获取和打印数据。在示例中,将一个int从JS传递给python,python将其添加5并将其传递回,然后JS调用另一个插槽以打印新值。
var backend = null;
var x = 15;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
backend.getRef(x, function(pyval){
backend.printRef(pyval)
});
});
@pyqtSlot(int)
def getRef(self, x):
print('inside getRef', x)
return x + 5
@pyqtSlot(int)
def printRef(self, ref):
print('inside printRef', ref)
输出:
inside getRef 15
Could not convert argument QJsonValue(null) to target type int .
预期:
inside getRef 15
inside printRef 20
我不知道为什么返回的值为空。我如何将pyval存储到js端的变量中以供以后使用?
├── index.html
└── main.py
main.py
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannel class Backend(QtCore.QObject): @QtCore.pyqtSlot(int, result=int) def getRef(self, x): print("inside getRef", x) return x + 5 @QtCore.pyqtSlot(int) def printRef(self, ref): print("inside printRef", ref) if __name__ == "__main__": import os import sys app = QtWidgets.QApplication(sys.argv) backend = Backend() view = QtWebEngineWidgets.QWebEngineView() channel = QtWebChannel.QWebChannel() view.page().setWebChannel(channel) channel.registerObject("backend", backend) current_dir = os.path.dirname(os.path.realpath(__file__)) filename = os.path.join(current_dir, "index.html") url = QtCore.QUrl.fromLocalFile(filename) view.load(url) view.resize(640, 480) view.show() sys.exit(app.exec_())
index.html的
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
var backend = null;
var x = 5;
window.onload = function()
{
new QWebChannel(qt.webChannelTransport, function(channel) {
backend = channel.objects.backend;
backend.getRef(x, function(pyval) {
backend.printRef(pyval);
});
});
}
</script>
</head>
</html>