QT通過JS與HTML的交互
阿新 • • 發佈:2018-11-29
mit 一個 widget web url .get 連接 conn cor 頭文件加入
QT += core gui webenginewidgets webchannel
通過QWebChannel與JS交互原理
QWebEnginePage *page = new QWebEnginePage(this); webView->setPage(page); webView->load(QUrl("qrc:/html/index.html")); webView->show(); QWebChannel *channel = new QWebChannel(this); //註冊一個content 這裏的內容通過JS的content來獲取 channel->registerObject(QString("content"),this); page->setWebChannel(channel);
註意:一定要先給WebView設置page,在加載網頁,否則網頁出不來!
QT發送信息到JS:
signals: void sendText(const QString &s_user,const QString &s_pwd); //點擊按鈕 設置發送的文本 void MainWindow::callJSBtnClicked() { //emit sendText(user->text(),password->text()); sendText(user->text(),password->text()); user->setText(""); password->setText(""); }
QT接收到JS的信息
public slots:
void receiveText(const QString &r_user,const QString &r_pwd);
void MainWindow::receiveText(const QString &r_user, const QString &r_pwd)
{
user->setText(r_user);
password->setText(r_pwd);
}
JS中對信息的操作
window.onload = function () { new QWebChannel(qt.webChannelTransport,function (channel) { var content = channel.objects.content; //接收QT發送來的 content.sendText.connect(function (s_user, s_pwd) { document.getElementById("userName").value = s_user; document.getElementById("userPwd").value = s_pwd; }) //傳給QT document.getElementById("submit").onclick = function () { var userName = document.getElementById("userName").value; var userPwd = document.getElementById("userPwd").value; document.getElementById("userName").value = ""; document.getElementById("userPwd").value = ""; content.receiveText(userName,userPwd); } }) }
在MainWindow中關閉連接
MainWindow::~MainWindow()
{
this->disconnect();
}
QT通過JS與HTML的交互