Qt QWebEngine 加载网页及交互,实现C++与JS 相互调用
#include <QApplication>
#include <QWebEngineView>
#include <QWebChannel>
class MyApi : public QObject {
Q_OBJECT
public:
explicit MyApi(QObject *parent = nullptr) : QObject(parent) {}
public slots:
void greetFromJavaScript() {
qDebug() << "Greetings from JavaScript!";
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWebEngineView view;
MyApi api;
QWebChannel channel;
channel.registerObject(QStringLiteral("api"), &api);
view.page()->setWebChannel(&channel);
view.setUrl(QUrl(QStringLiteral("qrc:/index.html")));
view.show();
return app.exec();
}
HTML 文件 (index.html
):
<!DOCTYPE html>
<html>
<head>
<title>Qt for WebEngine Example</title>
<script src="qwebchannel.js"></script>
</head>
<body>
<script>
new QWebChannel(qt.webChannelTransport, function(channel) {
var api = channel.objects.api;
window.addEventListener('DOMContentLoaded', function() {
document.getElementById('greetButton').addEventListener('click', function() {
api.greetFromJavaScript();
});
});
});
</script>
<button id="greetButton">Greet from C++</button>
</body>
</html>
确保 qwebchannel.js
文件是存在的,并且可以通过 QRC 资源系统访问。这个例子展示了如何在 C++ 和 JavaScript 之间建立通信,以及如何从 C++ 类中调用 JavaScript 函数。
评论已关闭