从qt调用javascript函数返回空字符串

时间:2014-02-03 16:17:58

标签: javascript c++ qt

我试图从Qt调用Javascript函数。我的HTML页面看起来像这样,

<html>
<body>
<script type="text/javascript">
 myoperations.submit();

function test(){
  return "Called me!";
 }
 </script>

</body>
</html>

这是我的Qt文件

 /.. all necessary include ../ 
 class MyJavaScriptOperations : public QObject {
   Q_OBJECT
   public:
    MyJavaScriptOperations(){

      qDebug() << "In constructor";
    }

 public slots:
   Q_INVOKABLE
  void submit()
   {
    QWebView *view2 = new QWebView();
    view2->resize(400,500);
    QVariant f1result = view2->page()->mainFrame()->evaluateJavaScript("test()");
    qDebug() << f1result.toString();
    view2->show();
   }
};


 int main(int argc, char *argv[])
 {
  QApplication a(argc, argv); 

   QWebView *view = new QWebView();
   view->resize(400, 500);
   view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", new MyJavaScriptOperations);
   view->load(QUrl("file:///C:/programs/test.html"));
   view->show();
   return a.exec();
 }

#include "main.moc"

在控制台中,我得到f1result为“”(空字符串)。为什么不显示返回值?

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

您在submit()中创建了第二个QWebView,而不是使用添加了对象的QWebView。这是您的代码的固定版本:

QWebView *view;
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    MyJavaScriptOperations(){
        qDebug() << "In constructor";
    }

    Q_INVOKABLE void submit()
    {
        QVariant f1result = view->page()->mainFrame()->evaluateJavaScript("test()");
        qDebug() << f1result.toString();
    }
};


int main(int argc, char *argv[])
{
    QApplication a(argc, argv); 

    view = new QWebView;
    view->resize(400, 500);
    view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", new MyJavaScriptOperations);
    view->load(QUrl("file:///tmp/o/index.html"));
    view->show();
    return a.exec();
}

#include "main.moc"