Qt: Cannot invoke shared object methods/properties from javascript

只谈情不闲聊 提交于 2019-12-30 11:53:05

问题


I have tried exactly same as the answer of Vicky Chijwani for this question QT QWebEnginePage::setWebChannel() transport object and everything fine but I cant able to invoke any methods or properties of jshelper.

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.cpp

MyClass::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()));
}

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 property

                jshelper = 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

what is wrong with my code, I am trying to fix this issue around 4 days but I couldn't able to fix it.

来源:https://stackoverflow.com/questions/32784400/qt-cannot-invoke-shared-object-methods-properties-from-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!