Qt4:如何通过QtWebkit从C ++调用页面中的JavaScript函数?
我正在尝试使用Qt4的WebKit端口/实现编写一个简单的日志查看器。我的HTML代码如下所示:
I'm trying to write a simple log viewer using Qt4's WebKit port/implementation. My HTML code looks like this:
更具体地说,我试图找出如何调用< script>
来自我的C ++代码的HTML文档中的部分。
More specifically, I'm trying to find out how to call the add_message() function which is defined in the <script>
section in the HTML document from my C++ code.
// Doesn't work:
QWebElement targetElement = chatView->page()->mainFrame()->findFirstElement("head").firstChild("script");
// Function is not included, either...
qDebug() << targetElement.tagName() << targetElement.functions();
// The ultimate attempt in calling the function anyway:
QVariant functionResult = targetElement.callFunction("add_message");
如果您使用的是Qt 4.5,请执行以下操作: :
If you are using Qt 4.5 do it something like this:
htmlView->page()->mainFrame()->evaluateJavaScript("add_message(); null");
注意:脚本末尾的 null
是出于性能问题。 QWebFrame :: evaluateJavaScript
返回 QVariant
,其中包含脚本中的最后一个值。评估脚本中的最后一个值可能非常耗时,因此在结尾处放置 null
会立即返回。
Note: null
at the end of script is for performance issue. QWebFrame::evaluateJavaScript
returns QVariant
with last value in the script. Evaluating last value in the script may be really time consuming, so putting null
at the end makes it return immediately.