当你使用QT5.5 的WebEngine 打开一个http协议的网页,并想执行网页上的JS方法。
我用的方法是,
1、在xxx.qml里面 添加一个函数:
function animation(url)
{
wbview.runJavaScript("window.animation_run()", function(result) { return true;});
}
wbview,是WebEngineView的ID
window.animation_run() -- 就是网页上的JS方法。function(result) { return true;} 是我随意写的。
2、在QT应用程序里添加:
QMetaObject::invokeMethod(m_pRootObj, "animation", Q_RETURN_ARG(QVariant, retVal), Q_ARG(QVariant, 0));
这句话就是调用 animation 方法的。
如此就可以在QT里面去调用网页上的JavaScript的方法了
xxx.qml如下所示:
import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.2
import QtWebEngine 1.1
import "qrc:///qml/Resource/func.js" as Funcs
ApplicationWindow
{
signal messageEvent
id: mainwin
visible: true;
width: animated.width;
height: animated.height + 24;
flags: Qt.Window | Qt.FramelessWindowHint
color: Qt.rgba(0.5, 0.5, 0.5, 0.5)
Keys.forwardTo: keyhandle
AnimatedImage {
id: animated;
source: "qrc:/animator/Resource/loading.gif";
Keys.forwardTo: keyhandle
onCurrentFrameChanged: {
//info.text = "%1/%2".arg(animated.currentFrame).arg(animated.frameCount);
}
}
Row{
spacing: 4;
anchors.horizontalCenter: parent.horizontalCenter;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 4;
Text {
id: info;
width: 60;
height: 24;
color: "red";
verticalAlignment: Text.AlignVCenter;
horizontalAlignment: Text.AlignRight;
text: "Loading ..."
}
}
WebEngineView
{
id: wbview
visible: false
width: Screen.width
height: Screen.height
anchors.fill: parent
opacity: 1.0
Keys.forwardTo: keyhandle
//url: initialUrl
onNewViewRequested: { //supported in v1.1
messageEvent();
Funcs.LogOutput();
}
}
function loadUrl(url)
{
//goto fullwin.qml
wbview.url = url;
return url;
}
function animation(url)
{
wbview.runJavaScript("window.animation_run()", function(result) { return true;});
}
function showUrl(url)
{
//goto fullwin.qml
animated.paused = true
animated.visible = false
//minimum window first
mainwin.x = 0
mainwin.y = 0
mainwin.width = 0
mainwin.height = 0
//maxmium window
mainwin.flags = Qt.Window | Qt.FramelessWindowHint | Qt.WindowFullScreen
mainwin.width = 2000
mainwin.height = 1280
wbview.visible = true
return url;
}
MouseArea {
anchors.fill: parent;
acceptedButtons: Qt.LeftButton | Qt.RightButton;
onDoubleClicked: {
if(mouse.button == Qt.RightButton){
messageEvent();
Funcs.LogOutput();
Qt.quit();
}
}
}
Rectangle {
id: keyhandle
width: 1
height: 1
focus: true
Keys.onPressed: {
messageEvent();
Funcs.LogOutput();
Qt.quit();
}
Keys.onEscapePressed: {
messageEvent();
Funcs.LogOutput();
Qt.quit();
}
}
}