Qt:无法从javascript调用共享对象方法/属性 [英] Qt: Cannot invoke shared object methods/properties from javascript
问题描述
我尝试完全一样的Vicky Chijwani的答案这个问题
QT QWebEnginePage: :setWebChannel()传输对象
和一切正常,但我无法调用任何方法或jshelper的属性。
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.
请仔细看看我的代码
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
$ b
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
$ b
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
我的代码有什么问题,我试图解决这个问题约4天,但我不能够解决它。
what is wrong with my code, I am trying to fix this issue around 4 days but I couldn't able to fix it.
推荐答案
我知道在QWebKit,我不得不使成员函数如下:
I know under QWebKit, I had to make the members functions look like this:
public slots:
Q_INVOKABLE void print();
这篇关于Qt:无法从javascript调用共享对象方法/属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!