I am working on a pyqt5 application which opens up a Qwebengineview. I am also attaching a handler to the QWebchannel to communicate between javascript and python methods and setting it to the QWebengineview.
Everything is working as expected. The above code loads the HTML and the CallHandler's test() method is called from javascript. And it ran smoothly. However, when a call from javascript is made to getScriptsPath() method, the function receives the call but returns nothing.
Below are the python and HTML codes respectively.
import os
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QUrl, QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
class CallHandler(QObject):
trigger = pyqtSignal(str)
@pyqtSlot()
def test(self):
print('call received')
@QtCore.pyqtSlot(int, result=str)
def getScriptsPath(self, someNumberToTest):
file_path = os.path.dirname(os.path.abspath(__file__))
print('call received for path', file_path)
return file_path
class Window(QWidget):
"""docstring for Window"""
def __init__(self):
super(Window, self).__init__()
##channel setting
self.channel = QWebChannel()
self.handler = CallHandler(self)
self.channel.registerObject('handler', self.handler)
self.view = QWebEngineView(self)
self.view.page().setWebChannel(self.channel)
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test.html"))
local_url = QUrl.fromLocalFile(file_path)
self.view.load(local_url)
def main():
app = QApplication(sys.argv)
window = Window()
# window.showFullScreen()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
HTMLfile
<html>
<head>
</head>
<body>
<center>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script language="JavaScript">
var xyz = "HI";
window.onload = function(){
new QWebChannel(qt.webChannelTransport, function (channel) {
window.handler = channel.objects.handler;
//testing handler object by calling python method.
handler.test();
handler.trigger.connect(function(msg){
console.log(msg);
});
});
}
var getScriptsPath = function(){
file_path = handler.getScriptsPath();
//Logging the recieved value which is coming out as "undefined"
console.log(file_path);
};
</script>
<button onClick="getScriptsPath()">print path</button>
</br>
<div id="test">
<p>HI</p>
</div>
</center>
</body></html>
I am not able to decipher why handler.getScriptsPath() 's returned value is not available in javascript.