QT通過JS與HTML的互動
阿新 • • 發佈:2018-11-29
標頭檔案加入
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();
}