如何在QWebEngineView中将值从QML传递到JavaScript
How to pass value from QML to JavaScript in QWebEngineView
DataManager
是一个类,我可以通过以下代码(Qt版本5.8.0(在QML中访问它。
DataManager *d = new DataManager;
QQuickView *viewver = new QQuickView;
viewver->rootContext()->setContextProperty("dataManager", d);
现在在QML中,我创建了一个WebEngineView
在这里我正在加载一个运行良好的本地HTML文件。
WebEngineView{
id : webEnginView
anchors.fill: parent
url : dataManager.htmlURL();
}
现在我想访问加载的 HTML 文件的 JavaScript 代码中的dataManager
值。提前谢谢。
QML 代码
import QtQuick 2.0
import QtWebEngine 1.4
import QtWebChannel 1.0
Item{
id:root
height: 500
width: 500
// Create WebChannel
WebChannel{
id:webChannel
}
//Now, let’s create an object that we want to publish to the HTML/JavaScript clients:
QtObject {
id: myObject
objectName: "myObject"
// the identifier under which this object
// will be known on the JavaScript side
//WebChannel.id: "webChannel"
property var send: function (arg) {
sendTextMessage(arg);
}
// signals, methods and properties are
// accessible to JavaScript code
signal someSignal(string message);
function someMethod(message) {
console.log(message);
someSignal(message);
return dataManager.getGeoLat();
}
property string hello: "world";
}
Rectangle{
anchors.fill: parent
color: "black"
WebEngineView{
id : webEnginView
anchors.fill: parent
url : dataManager.htmlURL();
webChannel: webChannel
}
}
Component.onCompleted: {
webChannel.registerObject("foo", myObject);
//Expose C++ object
webChannel.registerObject("bar", dataManager);
}
}
网页代码
<script type="text/javascript" src="qrc:/Map/qwebchannel.js"></script>
<script type="text/javascript">
new QWebChannel(qt.webChannelTransport, function(channel) {
// all published objects are available in channel.objects under
// the identifier set in their attached WebChannel.id property
var foo = channel.objects.foo;
var dManager = channel.objects.bar;
// access a property
alert(foo.hello);
// connect to a signal
foo.someSignal.connect(function(message) {
alert("Got signal: " + message);
});
// invoke a method, and receive the return value asynchronously
foo.someMethod("bar", function(ret) {
alert("Got return value: " + ret);
});
});
</script>
相关文章:
- 从C++实例化QML
- 使用CMake创建QML插件
- QT通过C++添加映射QML项目
- 如何在没有信号的情况下从C++执行QML插槽
- QML按钮点击功能执行顺序
- 如何在本地机器上运行c++和javascript客户端代码(hackerbank风格)
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 建议在运行时将带有类实例的列表从c++导入qml
- Qt Quick-如何仅从c++代码与qml属性交互
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 如何在QWebEngineView中将值从QML传递到JavaScript
- 解析JavaScript QML项目至C QT
- Javascript 函数作为从 c++ 定义的 QML 属性
- QML/QT 无法将 C++ 中的 QList<QVariantMap> 转换为 JavaScript 中的对象数组
- 如何关闭QML/JavaScript代码中的窗口(涉及C 代码)
- 如何延迟QML中的JavaScript操作
- 如何从 qml 将 javascript 对象发送到C++
- 在QML中使用facebook javascript SDK Graph API
- QML是在编译时被翻译成本机代码,还是在运行时被解释为JavaScript在web浏览器中的运行方式
- 从c++调用qml - javascript中的方法.范围的问题