1

对于这个问题QT QWebEnginePage::setWebChannel() 传输对象,我已经尝试与 Vicky Chijwani 的答案完全相同 ,一切都很好,但我无法调用 jshelper 的任何方法或属性。

请看我的代码 myclass.h

class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject *parent = 0);
    void print();

    int num;

signals:

public slots:
};

我的类.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);
}

主窗口.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()));
}

最后是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>

问题是这两行永远不会正确执行

alert( jshelper.num ); // gives 'undefined' message
jshelper.print(); //will not work

我的代码有什么问题,我试图在 4 天左右解决这个问题,但我无法修复它。

4

2 回答 2

2

我知道在 QWebKit 下,我必须让成员函数看起来像这样:

public slots:
    Q_INVOKABLE void print();
于 2015-09-28T18:59:42.577 回答
2

我知道我迟到了,但如果有问题的函数在插槽部分中声明,则不必使用 Q_INVOKABLE。如果有几个功能,打字会稍微少一些。

class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject *parent = 0);

slots:
    void print();
}
于 2015-12-02T20:24:31.873 回答