现在这段代码适用于插槽机制。但是,我也想尝试信号方式。但是,我无法这样做?有关它的更多想法吗?
我想从QT调用Javascript的函数f1。但是,我无法这样做。我没有看到JS f1()收到回调。我已经按照之前的帖子Qt QWEBview JavaScript callback进行了跟踪。但是,我无法这样做。这是我的代码。
#include <QtGui/QApplication>
#include <QApplication>
#include <QDebug>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
class MyJavaScriptOperations : public QObject {
Q_OBJECT
public:
QWebView *view;
MyJavaScriptOperations();
Q_INVOKABLE qint32 MultOfNumbers(int a, int b) {
qDebug() << a * b;
return (a*b);
}
public slots:
void callback();
public:
void firecb();
signals:
void done();
};
MyJavaScriptOperations::MyJavaScriptOperations()
{
view = new QWebView();
view->resize(400, 500);
connect(view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(callback()));
view->load(QUrl("./shreyas.html"));
view->show();
qDebug()<<view;
}
void MyJavaScriptOperations::callback()
{
qDebug()<<"Sending hello text";
QString function = "f1()";
view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", this);
//view->page()->mainFrame()->evaluateJavaScript("f1()");
done();
}
void MyJavaScriptOperations::firecb()
{
qDebug()<<"Emitting Signal";
done();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyJavaScriptOperations *jvs = new MyJavaScriptOperations;
jvs->firecb();
return a.exec();
}
#include "main.moc"
html文件。
<head>
<script LANGUAGE="JavaScript">
function f1()
{
alert('f1 called from qtclass with message');
document.write("HELLLLLLLLL");
}
myoperations.callback(f1);
function f2()
{
var result = myoperations.MultOfNumbers(3,7);
document.write(result);
alert('f1 called from qtclass with message');
}
function f3()
{
alert('f3');
}
myoperations.done.connect(f3);
</script>
</head>
<body>
test html
<input type="button" value="click" onclick="f2()">
</body>
答案 0 :(得分:1)
您必须在QObject
信号调用的插槽中注入addToJavaScriptWindowObject()
调用QWebFrame::javaScriptWindowObjectCleared()
,其他地方加载URL将清除之前注入的所有JS对象。
请参阅addToJavaScriptWindowObject
上的文档。