1、.pro工程文件中添加引用
QT += webenginewidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
2、定義一個bridge類
#include <QObject>
#include<QMessageBox>
class bridge : public QObject
{
void jscallme(const QString &text)
{
if(text ==QString::fromLocal8Bit("2"))
{
//QMessageBox::information(NULL, "jscallme", text);
system("gnome-terminal -x bash -c 'cd /home/rtour/workspace/qt-screen/rtour/sh;./setup_bei.sh'&");
}else {
system("gnome-terminal -x bash -c 'cd /home/rtour/workspace/qt-screen/rtour/sh;./setup_hong_test.sh'&");
}
}
};
此處jscallme為HTML中將會喚起的方法
system方法為喚起終端執(zhí)行命令
3、在工程內(nèi)創(chuàng)建webengine
ui->setupUi(this);
webView = new QWebEngineView(this);
webView->load(QUrl("http://localhost:3000/"));
setCentralWidget(webView);
webChannel = new QWebChannel(webView->page());
bridge *bridge = new bridge();
webChannel->registerObject("bridge", bridge);
webView->page()->setWebChannel(webChannel);
這里http://localhost:3000/是HTML文件的地址,我是通過nginx代理發(fā)布的。
registerObject("bridge", bridge);我的理解為將"bridge"這個通道的代理交給bridge這個實例對象來處理,同時在html里也會通過"bridge"喚起jscallme這個方法的
4、html創(chuàng)建通道
首先是引用一個js文件,這個文件在qt的安裝位置內(nèi)可以找到
<script src="qwebchannel.js"></script>
//獲取bridge對象
new QWebChannel(qt.webChannelTransport, function(channel) {
window.bridge = channel.objects.bridge;
})
//通過bridge喚起jscallme
function onShowMsgBox() {
if (window.bridge) {
window.bridge.jscallme(line)
}
}