QString variable to Javascript: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Add "cleanup" tag)
(Decode HTML entity names)
Line 8: Line 8:
This is a simple html to test with
This is a simple html to test with
<code>
<code>
<html&amp;amp;gt;
<html>
  <head&amp;amp;gt;
  <head>
  <script type="text/javascript">
  <script type="text/javascript">
  function displaymessage(str)
  function displaymessage(str)
Line 20: Line 20:
  alert("Hello");
  alert("Hello");
  }
  }
  </script&amp;amp;gt;
  </script>
  </head&amp;amp;gt;
  </head>


<body&amp;amp;gt;
<body>
  <form&amp;amp;gt;
  <form>
  <input type="button" value="Click me!">
  <input type="button" value="Click me!">
  </form&amp;amp;gt;
  </form>
  </body&amp;amp;gt;
  </body>
</html&amp;amp;gt;
</html>
</code>
</code>



Revision as of 17:33, 12 March 2015

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

Small snippet showing how to call two javascript functions, one without any param, and one with a QString param…

This is a simple html to test with

<html>
 <head>
 <script type="text/javascript">
 function displaymessage(str)
 {
 alert(str);
 }

function displayhello()
 {
 alert("Hello");
 }
 </script>
 </head>

<body>
 <form>
 <input type="button" value="Click me!">
 </form>
 </body>
</html>

Now using the Designer, load this page to a QWebView in your mainwindow. And in the mainwindow.cpp

 QWebFrame *frame = ui->webView->page()->mainFrame();

 // the below line will call the javascript function that does not have any param
 frame->evaluateJavaScript("displayhello()");

// now this is how to call the javascript function which takes a QString param
 QString data("Qt is the Best!"); // can be some large data, say from a file

QString param = QString("displaymessage('%1')").arg(data); // FIXME: Does not work if "data" contains a quote character!
 frame->evaluateJavaScript(param);