QString variable to Javascript: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
[[Category:snippets]] | [[Category:snippets]] | ||
[[Category:Developing_with_Qt::QtWebKit]] | |||
Small snippet showing how to call two javascript functions, one without any param, and one with a QString param… | 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 | This is a simple html to test with | ||
<code> | |||
<html&amp;gt; | |||
<head&amp;gt; | |||
<script type="text/javascript"> | |||
function displaymessage(str) | |||
{ | |||
alert(str); | |||
} | |||
function displayhello() | function displayhello() | ||
{ | |||
alert("Hello"); | |||
} | |||
</script&amp;gt; | |||
</head&amp;gt; | |||
<body&amp;gt; | |||
<form&amp;gt; | |||
<input type="button" value="Click me!"> | |||
</form&amp;gt; | |||
</body&amp;gt; | |||
</html&amp;gt; | |||
</code> | |||
Now using the Designer, load this page to a QWebView in your mainwindow. And in the mainwindow.cpp | Now using the Designer, load this page to a QWebView in your mainwindow. And in the mainwindow.cpp | ||
<code> | <code> | ||
QWebFrame *frame = ui->webView->page()->mainFrame(); | |||
// | // the below line will call the javascript function that does not have any param | ||
frame->evaluateJavaScript("displayhello()"); | |||
QString param = QString( | // 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); | |||
</code> |
Revision as of 11:05, 25 February 2015
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&amp;gt;
<head&amp;gt;
<script type="text/javascript">
function displaymessage(str)
{
alert(str);
}
function displayhello()
{
alert("Hello");
}
</script&amp;gt;
</head&amp;gt;
<body&amp;gt;
<form&amp;gt;
<input type="button" value="Click me!">
</form&amp;gt;
</body&amp;gt;
</html&amp;gt;
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);