实现QObject与JavaScript通讯(基于QWebEngine + QWebChannel)

通过使用QtWebEngine加载相关页面,然后用QtWebChannel作为Qt与Javascript交互通讯的桥梁;

1.Qt工程涉及profile文件QtJSInteract.pro

  1. TEMPLATE = app
  2. TARGET = QtJSConnect
  3. INCLUDEPATH += .
  4.  
  5. QT += webenginewidgets webchannel
  6.  
  7. HEADERS += TMainWindow.h TInteractObject.h
  8.  
  9. SOURCES += main.cpp TMainWindow.cpp TInteractObject.cpp
  10.  
  11. RESOURCES += Resource.qrc

2.工程引用资源Resource.qrc

  1. <!DOCTYPE RCC>
  2. <RCC version="1.0">
  3. <qresource>
  4. <file>qwebchannel.js</file>
  5. </qresource>
  6. </RCC>

其中qwebchannel.js是官方自动例子的js文件,可从Qt安装目录拷贝;

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2015 The Qt Company Ltd.
  4. ** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
  5. ** Contact: http://www.qt.io/licensing/
  6. **
  7. ** This file is part of the QtWebChannel module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL21$
  10. ** Commercial License Usage
  11. ** Licensees holding valid commercial Qt licenses may use this file in
  12. ** accordance with the commercial license agreement provided with the
  13. ** Software or, alternatively, in accordance with the terms contained in
  14. ** a written agreement between you and The Qt Company. For licensing terms
  15. ** and conditions see http://www.qt.io/terms-conditions. For further
  16. ** information use the contact form at http://www.qt.io/contact-us.
  17. **
  18. ** GNU Lesser General Public License Usage
  19. ** Alternatively, this file may be used under the terms of the GNU Lesser
  20. ** General Public License version 2.1 or version 3 as published by the Free
  21. ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
  22. ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
  23. ** following information to ensure the GNU Lesser General Public License
  24. ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
  25. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  26. **
  27. ** As a special exception, The Qt Company gives you certain additional
  28. ** rights. These rights are described in The Qt Company LGPL Exception
  29. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  30. **
  31. ** $QT_END_LICENSE$
  32. **
  33. ****************************************************************************/
  34.  
  35. "use strict";
  36.  
  37. var QWebChannelMessageTypes = {
  38. signal: ,
  39. propertyUpdate: ,
  40. init: ,
  41. idle: ,
  42. debug: ,
  43. invokeMethod: ,
  44. connectToSignal: ,
  45. disconnectFromSignal: ,
  46. setProperty: ,
  47. response: ,
  48. };
  49.  
  50. var QWebChannel = function(transport, initCallback)
  51. {
  52. if (typeof transport !== "object" || typeof transport.send !== "function") {
  53. console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
  54. " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
  55. return;
  56. }
  57.  
  58. var channel = this;
  59. this.transport = transport;
  60.  
  61. this.send = function(data)
  62. {
  63. if (typeof(data) !== "string") {
  64. data = JSON.stringify(data);
  65. }
  66. channel.transport.send(data);
  67. }
  68.  
  69. this.transport.onmessage = function(message)
  70. {
  71. var data = message.data;
  72. if (typeof data === "string") {
  73. data = JSON.parse(data);
  74. }
  75. switch (data.type) {
  76. case QWebChannelMessageTypes.signal:
  77. channel.handleSignal(data);
  78. break;
  79. case QWebChannelMessageTypes.response:
  80. channel.handleResponse(data);
  81. break;
  82. case QWebChannelMessageTypes.propertyUpdate:
  83. channel.handlePropertyUpdate(data);
  84. break;
  85. default:
  86. console.error("invalid message received:", message.data);
  87. break;
  88. }
  89. }
  90.  
  91. this.execCallbacks = {};
  92. this.execId = ;
  93. this.exec = function(data, callback)
  94. {
  95. if (!callback) {
  96. // if no callback is given, send directly
  97. channel.send(data);
  98. return;
  99. }
  100. if (channel.execId === Number.MAX_VALUE) {
  101. // wrap
  102. channel.execId = Number.MIN_VALUE;
  103. }
  104. if (data.hasOwnProperty("id")) {
  105. console.error("Cannot exec message with property id: " + JSON.stringify(data));
  106. return;
  107. }
  108. data.id = channel.execId++;
  109. channel.execCallbacks[data.id] = callback;
  110. channel.send(data);
  111. };
  112.  
  113. this.objects = {};
  114.  
  115. this.handleSignal = function(message)
  116. {
  117. var object = channel.objects[message.object];
  118. if (object) {
  119. object.signalEmitted(message.signal, message.args);
  120. } else {
  121. console.warn("Unhandled signal: " + message.object + "::" + message.signal);
  122. }
  123. }
  124.  
  125. this.handleResponse = function(message)
  126. {
  127. if (!message.hasOwnProperty("id")) {
  128. console.error("Invalid response message received: ", JSON.stringify(message));
  129. return;
  130. }
  131. channel.execCallbacks[message.id](message.data);
  132. delete channel.execCallbacks[message.id];
  133. }
  134.  
  135. this.handlePropertyUpdate = function(message)
  136. {
  137. for (var i in message.data) {
  138. var data = message.data[i];
  139. var object = channel.objects[data.object];
  140. if (object) {
  141. object.propertyUpdate(data.signals, data.properties);
  142. } else {
  143. console.warn("Unhandled property update: " + data.object + "::" + data.signal);
  144. }
  145. }
  146. channel.exec({type: QWebChannelMessageTypes.idle});
  147. }
  148.  
  149. this.debug = function(message)
  150. {
  151. channel.send({type: QWebChannelMessageTypes.debug, data: message});
  152. };
  153.  
  154. channel.exec({type: QWebChannelMessageTypes.init}, function(data) {
  155. for (var objectName in data) {
  156. var object = new QObject(objectName, data[objectName], channel);
  157. }
  158. // now unwrap properties, which might reference other registered objects
  159. for (var objectName in channel.objects) {
  160. channel.objects[objectName].unwrapProperties();
  161. }
  162. if (initCallback) {
  163. initCallback(channel);
  164. }
  165. channel.exec({type: QWebChannelMessageTypes.idle});
  166. });
  167. };
  168.  
  169. function QObject(name, data, webChannel)
  170. {
  171. this.__id__ = name;
  172. webChannel.objects[name] = this;
  173.  
  174. // List of callbacks that get invoked upon signal emission
  175. this.__objectSignals__ = {};
  176.  
  177. // Cache of all properties, updated when a notify signal is emitted
  178. this.__propertyCache__ = {};
  179.  
  180. var object = this;
  181.  
  182. // ----------------------------------------------------------------------
  183.  
  184. this.unwrapQObject = function(response)
  185. {
  186. if (response instanceof Array) {
  187. // support list of objects
  188. var ret = new Array(response.length);
  189. for (var i = ; i < response.length; ++i) {
  190. ret[i] = object.unwrapQObject(response[i]);
  191. }
  192. return ret;
  193. }
  194. if (!response
  195. || !response["__QObject*__"]
  196. || response.id === undefined) {
  197. return response;
  198. }
  199.  
  200. var objectId = response.id;
  201. if (webChannel.objects[objectId])
  202. return webChannel.objects[objectId];
  203.  
  204. if (!response.data) {
  205. console.error("Cannot unwrap unknown QObject " + objectId + " without data.");
  206. return;
  207. }
  208.  
  209. var qObject = new QObject( objectId, response.data, webChannel );
  210. qObject.destroyed.connect(function() {
  211. if (webChannel.objects[objectId] === qObject) {
  212. delete webChannel.objects[objectId];
  213. // reset the now deleted QObject to an empty {} object
  214. // just assigning {} though would not have the desired effect, but the
  215. // below also ensures all external references will see the empty map
  216. // NOTE: this detour is necessary to workaround QTBUG-40021
  217. var propertyNames = [];
  218. for (var propertyName in qObject) {
  219. propertyNames.push(propertyName);
  220. }
  221. for (var idx in propertyNames) {
  222. delete qObject[propertyNames[idx]];
  223. }
  224. }
  225. });
  226. // here we are already initialized, and thus must directly unwrap the properties
  227. qObject.unwrapProperties();
  228. return qObject;
  229. }
  230.  
  231. this.unwrapProperties = function()
  232. {
  233. for (var propertyIdx in object.__propertyCache__) {
  234. object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]);
  235. }
  236. }
  237.  
  238. function addSignal(signalData, isPropertyNotifySignal)
  239. {
  240. var signalName = signalData[];
  241. var signalIndex = signalData[];
  242. object[signalName] = {
  243. connect: function(callback) {
  244. if (typeof(callback) !== "function") {
  245. console.error("Bad callback given to connect to signal " + signalName);
  246. return;
  247. }
  248.  
  249. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  250. object.__objectSignals__[signalIndex].push(callback);
  251.  
  252. if (!isPropertyNotifySignal && signalName !== "destroyed") {
  253. // only required for "pure" signals, handled separately for properties in propertyUpdate
  254. // also note that we always get notified about the destroyed signal
  255. webChannel.exec({
  256. type: QWebChannelMessageTypes.connectToSignal,
  257. object: object.__id__,
  258. signal: signalIndex
  259. });
  260. }
  261. },
  262. disconnect: function(callback) {
  263. if (typeof(callback) !== "function") {
  264. console.error("Bad callback given to disconnect from signal " + signalName);
  265. return;
  266. }
  267. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  268. var idx = object.__objectSignals__[signalIndex].indexOf(callback);
  269. if (idx === -) {
  270. console.error("Cannot find connection of signal " + signalName + " to " + callback.name);
  271. return;
  272. }
  273. object.__objectSignals__[signalIndex].splice(idx, );
  274. if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === ) {
  275. // only required for "pure" signals, handled separately for properties in propertyUpdate
  276. webChannel.exec({
  277. type: QWebChannelMessageTypes.disconnectFromSignal,
  278. object: object.__id__,
  279. signal: signalIndex
  280. });
  281. }
  282. }
  283. };
  284. }
  285.  
  286. /**
  287. * Invokes all callbacks for the given signalname. Also works for property notify callbacks.
  288. */
  289. function invokeSignalCallbacks(signalName, signalArgs)
  290. {
  291. var connections = object.__objectSignals__[signalName];
  292. if (connections) {
  293. connections.forEach(function(callback) {
  294. callback.apply(callback, signalArgs);
  295. });
  296. }
  297. }
  298.  
  299. this.propertyUpdate = function(signals, propertyMap)
  300. {
  301. // update property cache
  302. for (var propertyIndex in propertyMap) {
  303. var propertyValue = propertyMap[propertyIndex];
  304. object.__propertyCache__[propertyIndex] = propertyValue;
  305. }
  306.  
  307. for (var signalName in signals) {
  308. // Invoke all callbacks, as signalEmitted() does not. This ensures the
  309. // property cache is updated before the callbacks are invoked.
  310. invokeSignalCallbacks(signalName, signals[signalName]);
  311. }
  312. }
  313.  
  314. this.signalEmitted = function(signalName, signalArgs)
  315. {
  316. invokeSignalCallbacks(signalName, signalArgs);
  317. }
  318.  
  319. function addMethod(methodData)
  320. {
  321. var methodName = methodData[];
  322. var methodIdx = methodData[];
  323. object[methodName] = function() {
  324. var args = [];
  325. var callback;
  326. for (var i = ; i < arguments.length; ++i) {
  327. if (typeof arguments[i] === "function")
  328. callback = arguments[i];
  329. else
  330. args.push(arguments[i]);
  331. }
  332.  
  333. webChannel.exec({
  334. "type": QWebChannelMessageTypes.invokeMethod,
  335. "object": object.__id__,
  336. "method": methodIdx,
  337. "args": args
  338. }, function(response) {
  339. if (response !== undefined) {
  340. var result = object.unwrapQObject(response);
  341. if (callback) {
  342. (callback)(result);
  343. }
  344. }
  345. });
  346. };
  347. }
  348.  
  349. function bindGetterSetter(propertyInfo)
  350. {
  351. var propertyIndex = propertyInfo[];
  352. var propertyName = propertyInfo[];
  353. var notifySignalData = propertyInfo[];
  354. // initialize property cache with current value
  355. // NOTE: if this is an object, it is not directly unwrapped as it might
  356. // reference other QObject that we do not know yet
  357. object.__propertyCache__[propertyIndex] = propertyInfo[];
  358.  
  359. if (notifySignalData) {
  360. if (notifySignalData[] === ) {
  361. // signal name is optimized away, reconstruct the actual name
  362. notifySignalData[] = propertyName + "Changed";
  363. }
  364. addSignal(notifySignalData, true);
  365. }
  366.  
  367. Object.defineProperty(object, propertyName, {
  368. configurable: true,
  369. get: function () {
  370. var propertyValue = object.__propertyCache__[propertyIndex];
  371. if (propertyValue === undefined) {
  372. // This shouldn't happen
  373. console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__);
  374. }
  375.  
  376. return propertyValue;
  377. },
  378. set: function(value) {
  379. if (value === undefined) {
  380. console.warn("Property setter for " + propertyName + " called with undefined value!");
  381. return;
  382. }
  383. object.__propertyCache__[propertyIndex] = value;
  384. webChannel.exec({
  385. "type": QWebChannelMessageTypes.setProperty,
  386. "object": object.__id__,
  387. "property": propertyIndex,
  388. "value": value
  389. });
  390. }
  391. });
  392.  
  393. }
  394.  
  395. // ----------------------------------------------------------------------
  396.  
  397. data.methods.forEach(addMethod);
  398.  
  399. data.properties.forEach(bindGetterSetter);
  400.  
  401. data.signals.forEach(function(signal) { addSignal(signal, false); });
  402.  
  403. for (var name in data.enums) {
  404. object[name] = data.enums[name];
  405. }
  406. }
  407.  
  408. //required for use with nodejs
  409. if (typeof module === 'object') {
  410. module.exports = {
  411. QWebChannel: QWebChannel
  412. };
  413. }

3.涉及相关Qt工程文件

main.cpp 文件:

  1. #include <QApplication>
  2. #include "TMainWindow.h"
  3.  
  4. int main(int argc, char** argv)
  5. {
  6. QApplication app(argc, argv);
  7.  
  8. TMainWindow mainWindow;
  9. mainWindow.show();
  10. return app.exec();
  11. }

TMainWindow.h 文件:

  1. #ifndef TMAINWINDOW_H
  2. #define TMAINWINDOW_H
  3.  
  4. #include <QDialog>
  5.  
  6. QT_BEGIN_NAMESPACE
  7. class QPlainTextEdit;
  8. class QLineEdit;
  9. class QPushButton;
  10. class QWebEngineView;
  11. QT_END_NAMESPACE
  12.  
  13. class TMainWindow : public QDialog
  14. {
  15. Q_OBJECT
  16.  
  17. public:
  18. TMainWindow(QDialog *parent = );
  19. ~TMainWindow();
  20.  
  21. void OnReceiveMessageFromJS(QString strParameter);
  22.  
  23. signals:
  24. void SigSendMessageToJS(QString strParameter);
  25.  
  26. private:
  27. void OnSendMessageByInteractObj();
  28. void OnSendMessageByJavaScript();
  29.  
  30. QPlainTextEdit *mpQtContentTextEdit;
  31. QLineEdit *mpQtSendLineEdit;
  32. QPushButton *mpQtSendBtnByInteractObj;
  33. QPushButton *mpQtSendBtnByJavaScript;
  34. QWebEngineView *mpJSWebView;
  35. };
  36.  
  37. #endif //TMAINWINDOW_H

TMainWindow.cpp 文件:

  1. #include "TMainWindow.h"
  2. #include "TInteractObject.h"
  3.  
  4. #include <QPlainTextEdit>
  5. #include <QLineEdit>
  6. #include <QPushButton>
  7. #include <QHBoxLayout>
  8. #include <QVBoxLayout>
  9. #include <QGroupBox>
  10. #include <QWebChannel>
  11. #include <QWebEngineView>
  12. #include <QFileInfo>
  13.  
  14. TMainWindow::TMainWindow(QDialog *parent)
  15. : QDialog(parent)
  16. {
  17. //---Qt widget and layout---
  18. mpQtContentTextEdit = new QPlainTextEdit(this);
  19. mpQtContentTextEdit->setMidLineWidth();
  20. mpQtContentTextEdit->setReadOnly(true);
  21.  
  22. mpQtSendLineEdit = new QLineEdit(this);
  23. mpQtSendBtnByInteractObj = new QPushButton("Send", this);
  24. mpQtSendBtnByInteractObj->setToolTip(tr("Send message by Interact object style"));
  25.  
  26. mpQtSendBtnByJavaScript = new QPushButton("Send2", this);
  27. mpQtSendBtnByJavaScript->setToolTip(tr("Send message by runJavaScript style"));
  28.  
  29. QHBoxLayout *pQtSendHLayout = new QHBoxLayout;
  30. pQtSendHLayout->setMargin();
  31. pQtSendHLayout->setSpacing();
  32. pQtSendHLayout->addWidget(mpQtSendLineEdit);
  33. pQtSendHLayout->addSpacing();
  34. pQtSendHLayout->addWidget(mpQtSendBtnByInteractObj);
  35. pQtSendHLayout->addSpacing();
  36. pQtSendHLayout->addWidget(mpQtSendBtnByJavaScript);
  37.  
  38. QVBoxLayout *pQtTotalVLayout = new QVBoxLayout;
  39. pQtTotalVLayout->setMargin();
  40. pQtTotalVLayout->setSpacing();
  41. pQtTotalVLayout->addWidget(mpQtContentTextEdit);
  42. pQtTotalVLayout->addSpacing();
  43. pQtTotalVLayout->addLayout(pQtSendHLayout);
  44.  
  45. QGroupBox *pQtGroup = new QGroupBox("Qt View", this);
  46. pQtGroup->setLayout(pQtTotalVLayout);
  47.  
  48. //---Web widget and layout---
  49. mpJSWebView = new QWebEngineView(this);
  50.  
  51. QWebChannel *pWebChannel = new QWebChannel(mpJSWebView->page());
  52. TInteractObj *pInteractObj = new TInteractObj(this);
  53. pWebChannel->registerObject(QStringLiteral("interactObj"), pInteractObj);
  54.  
  55. mpJSWebView->page()->setWebChannel(pWebChannel);
  56. mpJSWebView->page()->load(QUrl::fromLocalFile(QFileInfo("./JSTest.html").absoluteFilePath()));
  57. mpJSWebView->show();
  58.  
  59. QVBoxLayout *pJSTotalVLayout = new QVBoxLayout();
  60. pJSTotalVLayout->setMargin();
  61. pJSTotalVLayout->setSpacing();
  62. pJSTotalVLayout->addWidget(mpJSWebView);
  63.  
  64. QGroupBox *pWebGroup = new QGroupBox("Web View", this);
  65. pWebGroup->setLayout(pJSTotalVLayout);
  66.  
  67. //---TMainWindow total layout---
  68. QHBoxLayout *mainLayout = new QHBoxLayout;
  69. mainLayout->setMargin();
  70. mainLayout->setSpacing();
  71. mainLayout->addWidget(pQtGroup);
  72. mainLayout->addSpacing();
  73. mainLayout->addWidget(pWebGroup);
  74. setLayout(mainLayout);
  75. this->setMinimumSize(, );
  76.  
  77. connect(mpQtSendBtnByInteractObj, &QPushButton::clicked, this, &TMainWindow::OnSendMessageByInteractObj);
  78. connect(mpQtSendBtnByJavaScript, &QPushButton::clicked, this, &TMainWindow::OnSendMessageByJavaScript);
  79. connect(pInteractObj, &TInteractObj::SigReceivedMessFromJS, this, &TMainWindow::OnReceiveMessageFromJS);
  80. connect(this, &TMainWindow::SigSendMessageToJS, pInteractObj, &TInteractObj::SigSendMessageToJS);
  81. }
  82.  
  83. TMainWindow::~TMainWindow()
  84. {
  85. }
  86.  
  87. void TMainWindow::OnReceiveMessageFromJS(QString strParameter)
  88. {
  89. if (strParameter.isEmpty())
  90. {
  91. return;
  92. }
  93.  
  94. mpQtContentTextEdit->appendPlainText(strParameter);
  95. }
  96.  
  97. void TMainWindow::OnSendMessageByInteractObj()
  98. {
  99. QString strMessage = mpQtSendLineEdit->text().trimmed();
  100. if (strMessage.isEmpty())
  101. {
  102. return;
  103. }
  104.  
  105. emit SigSendMessageToJS(strMessage);
  106. }
  107.  
  108. void TMainWindow::OnSendMessageByJavaScript()
  109. {
  110. QString strMessage = mpQtSendLineEdit->text().trimmed();
  111. if (strMessage.isEmpty())
  112. {
  113. return;
  114. }
  115.  
  116. strMessage = QString("Received string from Qt: %1").arg(strMessage);
  117. mpJSWebView->page()->runJavaScript(QString("output('%1');").arg(strMessage));
  118. }

说明:

TInteractObject.h 文件:

  1. #ifndef TINTERACT_OBJECT_H
  2. #define TINTERACT_OBJECT_H
  3.  
  4. #include <QObject>
  5.  
  6. class TInteractObj : public QObject
  7. {
  8. Q_OBJECT
  9.  
  10. public:
  11. TInteractObj(QObject *parent);
  12. ~TInteractObj();
  13.  
  14. Q_INVOKABLE void JSSendMessage(QString strParameter); //Called by JS: Send message to Qt
  15.  
  16. signals:
  17. void SigReceivedMessFromJS(QString strParameter); //Receive message from Web
  18.  
  19. void SigSendMessageToJS(QString strParameter); //Send message to Web
  20. };
  21.  
  22. #endif //TINTERACT_OBJECT_H

说明:

TInteractObject.cpp 文件:

  1. #include "TInteractObject.h"
  2.  
  3. TInteractObj::TInteractObj(QObject *parent)
  4. :QObject(parent)
  5. {
  6. }
  7.  
  8. TInteractObj::~TInteractObj()
  9. {
  10. }
  11.  
  12. void TInteractObj::JSSendMessage(QString strParameter)
  13. {
  14. emit SigReceivedMessFromJS(strParameter);
  15. }

4.页面端模拟文件JSTest.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
  6. <script type="text/javascript">
  7. //---Web show receive message---
  8. function output(message)
  9. {
  10. var output = document.getElementById("output");
  11. output.innerHTML = output.innerHTML + message + "\n";
  12. }
  13.  
  14. //Web initial loading
  15. window.onload = function() {
  16. output("");
  17. new QWebChannel(qt.webChannelTransport, function(channel) {
  18.  
  19. //Get Qt interact object
  20. var interactObj = channel.objects.interactObj;
  21.  
  22. //Web send message to Qt
  23. document.getElementById("send").onclick = function() {
  24. var input = document.getElementById("input");
  25. if (!input.value) {
  26. return;
  27. }
  28.  
  29. //Web use the interface of Qt
  30. interactObj.JSSendMessage(input.value);
  31. input.value = "";
  32. }
  33.  
  34. //Web connect the Qt signal, then Qt can call "output" function
  35. interactObj.SigSendMessageToJS.connect(function(str) {
  36. output("Received string from Qt: " + str);
  37. });
  38. });
  39. }
  40.  
  41. </script>
  42. <style type="text/css">
  43. html {
  44. height: 100%;
  45. width: 100%;
  46. }
  47. #input {
  48. width: 650px;
  49. margin: 0 10px 0 0;
  50. }
  51. #send {
  52. width: 90px;
  53. margin: 0;
  54. }
  55. #output {
  56. width: 770px;
  57. height: 550px;
  58. }
  59. </style>
  60. </head>
  61. <body>
  62. <textarea id="output" readonly="readonly"></textarea><br />
  63. <input id="input" />
  64. <input type="submit" id="send" value="Send" onclick="javascript:click();" />
  65. </body>
  66. </html>

说明:

5.运行效果

Qt界面Send按钮通过QtWebChannel绑定对象,向Web页面端发送消息("Hello JavaScript");
Qt界面Send2按钮通过runJavaScript调用页面端公共接口,向Web页面端发送消息("Hello JavaScript");
Web页面端Send按钮通过关联Qt界面公共接口,向Qt端发送消息("Hello Qt");

实现QObject与JavaScript通讯(基于QWebEngine + QWebChannel)的更多相关文章

  1. Qt webKit可以做什么(四)--实现本地QObject和JavaScript交互

    Qt webKit可以做什么(四)--实现本地QObject和JavaScript交互 Qt webKit可以做什么(四)--实现本地QObject和JavaScript交互

  2. 深入了解JavaScript中基于原型(prototype)的继承机制

    原型 前言 继承是面向对象编程中相当重要的一个概念,它对帮助代码复用起到了很大的作用. 正文 Brendan Eich在创建JavaScript时,没有选择当时最流行的类继承机制,而是借鉴Self,用 ...

  3. JavaScript学习总结(九)——Javascript面向(基于)对象编程

    一.澄清概念 1.JS中"基于对象=面向对象" 2.JS中没有类(Class),但是它取了一个新的名字叫“原型对象”,因此"类=原型对象" 二.类(原型对象)和 ...

  4. php和c++socket通讯(基于字节流,二进制)

    研究了一下PHP和C++socket通讯,用C++作为服务器端,php作为客户端进行. socket通讯是基于协议的,因此,只要双方协议一致就行. 关于协议的选择:我看过网上大部分协议都是在应用层的协 ...

  5. JavaScript学习总结(5)——Javascript面向(基于)对象编程

    一.澄清概念 1.JS中"基于对象=面向对象" 2.JS中没有类(Class),但是它取了一个新的名字叫"原型对象",因此"类=原型对象" ...

  6. 【javascript】基于javascript的小时钟

    计时事件:通过JavaScript,我们可以设置在一段时间间隔后执行一段代码,而不仅仅是在函数调用后立即执行. 在JavaScript中,使用计时事件是很容易的,主要有两个事件供我们使用 setTim ...

  7. JavaScript实现基于数组的栈

    class StackArray {   constructor() {     this.items = [];   }   push(element) {     this.items.push( ...

  8. android 蓝牙开发---与蓝牙模块进行通讯 基于eclipse项目

      2017.10.20 之前参加一个大三学长的创业项目,做一个智能的车锁App,用到嵌入式等技术,App需要蓝牙.实时位置等技术,故查了几篇相关技术文章,以此参考!             //先说 ...

  9. JavaScript 闭包&基于闭包实现柯里化和bind

    闭包: 1 函数内声明了一个函数,并且将这个函数内部的函数返回到全局 2 将这个返回到全局的函数内中的函数存储到全局变量中 3 内部的函数调用了外部函数中的局部变量 闭包简述: 有权访问另一个函数局部 ...

随机推荐

  1. Tornado+MySQL模拟SQL注入

    实验环境: python 3.6 + Tornado 4.5 + MySQL 5.7 实验目的: 简单模拟SQL注入,实现非法用户的成功登录 一.搭建环境 1.服务端的tornado主程序app.py ...

  2. Python3 常用数据类型语法

    1.int类型 int类型的数据是没有长度限制的,它的最大长度只与计算机的内存有关. bin(i)      返回二进制表示结果, hex(i)      十六进制, int(i)       整数( ...

  3. Gist - Fetch Usage

    Introduction Do you prefer the usage of "ES6 Promise"? If you do, you will like the usage ...

  4. vijos1080题解

    题目: 对于一个递归函数w(a,b,c) 如果a<=0 or b<=0 or c<=0就返回值1. 如果a>20 or b>20 or c>20就返回w(20,20 ...

  5. 构建自己的Tomcat镜像

    在很多情况下,我们会不满足于官方提供的Tomcat镜像.比如官方镜像的时区为UTC时间,并不是北京时间:再比如在特定硬件环境下,jdk的随机数生成器初始化过慢问题.此时,我们就会考虑构建自己的Tomc ...

  6. poj3320 (尺取法)

    n个数,求最小区间覆盖着n个数中所有的不相同的数字. 解题思路: AC代码: import java.util.HashMap; import java.util.HashSet; import ja ...

  7. POJ 2251 三维BFS(基础题)

    Dungeon Master Description You are trapped in a 3D dungeon and need to find the quickest way out! Th ...

  8. java面向对象浅析

    1.(了解) 面向对象 vs 面向过程 例子:人开门:把大象装冰箱 2.面向对象的编程关注于类的设计!1)一个项目或工程,不管多庞大,一定是有一个一个类构成的.2)类是抽象的,好比是制造汽车的图纸. ...

  9. Hadoop的介绍、搭建、环境

    HADOOP背景介绍 1.1Hadoop产生背景 HADOOP最早起源于Nutch.Nutch的设计目标是构建一个大型的全网搜索引擎,包括网页抓取.索引.查询等功能,但随着抓取网页数量的增加,遇到了严 ...

  10. nyoj_471:好多的树(容斥原理)

    题目链接: http://acm.nyist.net/JudgeOnline/problem.php?pid=471 还是直接上代码.. #include<bits/stdc++.h> u ...