Cannot invoke shared object methods/properties from javascript
-
I have tried QWebengine, QWebChannel as per the qt documentation for sharing C++ object with javascript. but I cant able to access any methods or properties in the c++ object.
kindly look at my code
myclass.h
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
void print();int num;
signals:
public slots:
};
myclass.cppMyClass::MyClass(QObject *parent) : QObject(parent)
{
num=100;
}void MyClass::print()
{
QMessageBox bx;
bx.exec();
}mywebengineview.h
class MyWebEngineView : public QWebEngineView
{
public:
MyWebEngineView(QWidget *parent);MyClass helper;
};
mywebengineview.cpp
MyWebEngineView::MyWebEngineView(QWidget *parent): QWebEngineView(parent)
{
QWebChannel *channel = new QWebChannel(page());
channel->registerObject(QStringLiteral("jshelper"), &helper);load(QUrl::fromLocalFile(QFileInfo("../html/index.html").absoluteFilePath()));
page()->setWebChannel(channel);
}mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);view = new MyWebEngineView(this); view->setGeometry(10, 10, 500, 500); view->load(QUrl::fromLocalFile(QFileInfo("../html/index.html").absoluteFilePath())); // Slot for testing library function call connect ((QObject*)ui->pushButton,SIGNAL(clicked()),this,SLOT(OnTest()));
}
finally javascript
<script type="text/javascript">
var jshelper;
document.addEventListener("DOMContentLoaded", function () {
new QWebChannel(qt.webChannelTransport, function(channel) {
alert('ok');
// all published objects are available in channel.objects under
// the identifier set in their attached WebChannel.id propertyjshelper = channel.objects.jshelper; alert( jshelper.num ); jshelper.print(); }); }); </script>
The problem is these two lines never executes properly
alert( jshelper.num ); // gives 'undefined' message
jshelper.print(); //will not work