当前位置: 首页 > news >正文

【Qt】Qt与Html网页进行数据交互

前言:此项目使用达梦数据库,以Qt制作服务器,Html制作网页客户端界面,可以通过任意浏览器访问。

1、Qt与网页进行数据交互

1.1、第一步:准备qwebchannel.js文件

直接在qt的安装路径里复制即可
在这里插入图片描述

1.2、第二步:在Qt的.pro文件加载webchannel组件

在.pro文件添加如下组件:

QT       += core gui sql webchannel widgets websockets

1.3、第三步:在main.cpp文件注册通信类

#include "MainWindow.h"
#include <QApplication>
#include <QDesktopServices>
#include <QDialog>
#include <QDir>
#include <QFileInfo>
#include <QUrl>
#include <QWebChannel>
#include <QWebSocketServer>
#include "core.h"
#include "../shared/websocketclientwrapper.h"
#include "../shared/websockettransport.h"
#include <QObject>int main(int argc, char *argv[])
{QApplication a(argc, argv);//以下三行代码可有可无,用来确保qwebchannel.js文件放在自己指定的文件夹里QFileInfo jsFileInfo(QDir::currentPath() + "/Web/js/qwebchannel.js");if (!jsFileInfo.exists())QFile::copy(":/qtwebchannel/qwebchannel.js",jsFileInfo.absoluteFilePath());// 设置QWebSocketServerQWebSocketServer server(QStringLiteral("QWebChannel Standalone Example Server"), QWebSocketServer::NonSecureMode);if (!server.listen(QHostAddress::Any, 12345))//12345是端口号,可以自己指定{qFatal("Failed to open web socket server.");return 1;}// 在QWebChannelAbstractTransport对象中包装WebSocket客户端WebSocketClientWrapper clientWrapper(&server);// setup the channelQWebChannel channel;QObject::connect(&clientWrapper, &WebSocketClientWrapper::clientConnected,&channel, &QWebChannel::connectTo);MainWindow w;//MainWindow 类是我自己搭建的服务器界面类Core core(&w);//Core 类是我自己搭建的用来作为Qt与Html通信的类channel.registerObject(QStringLiteral("core"), &core);//把Core注册成通信类w.show();//显示服务器界面return a.exec();
}

1.4、第四步:创建Core通信类

Core.h

#ifndef CORE_H
#define CORE_H#include "MainWindow.h"
#include <QObject>/*An instance of this class gets published over the WebChannel and is then accessible to HTML clients.该类的一个实例通过WebChannel发布,然后HTML客户端可以访问它。
*/
class Core : public QObject
{Q_OBJECTpublic:Core(MainWindow *dialog, QObject *parent = nullptr): QObject(parent), m_dialog(dialog){connect(dialog, &MainWindow::sendText, this, &Core::sendText);}signals:/*This signal is emitted from the C++ side and the text displayed on the HTML client side.该信号从Qt端发出,并在HTML客户端显示文本。*/void sendText(const QString &text);//html那边会监听这个信号,Qt这边发送text,html会直接接收到public slots:/*This slot is invoked from the HTML client side and the text displayed on the server side.此槽从HTML客户端调用,并在服务器端显示文本。*/void receiveText(const QString &text)//Html那边可以直接调用这个函数{qDebug()<<text;//text就是Html发过来的数据//m_dialog->displayMessage(MainWindow::tr("客户端: %1").arg(text));}private:MainWindow *m_dialog;
};#endif // CORE_H

1.5、第五步:创建html客户端

chatRoom.html

<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript" src="../js/qwebchannel.js"></script><script type="text/javascript">//BEGIN SETUPfunction output(message) {var output = document.getElementById("output");output.innerHTML = output.innerHTML + message + "\n";}window.onload = function() {if (location.search != "")var baseUrl = (/[?&]webChannelBaseUrl=([A-Za-z0-9\-:/\.]+)/.exec(location.search)[1]);elsevar baseUrl = "ws://localhost:12345";output("系统:连接WebSocket服务器" + baseUrl + ".");var socket = new WebSocket(baseUrl);socket.onclose = function() {console.error("web channel closed");};socket.onerror = function(error) {console.error("web channel error: " + error);};socket.onopen = function() {output("系统:连接WebSocket,设置QWebChannel.");new QWebChannel(socket, function(channel) {output("系统:连接成功!");// make core object accessible globallywindow.core = channel.objects.core;document.getElementById("send").onclick = function() {var input = document.getElementById("input");var text = input.value;if (!text) {return;}output("客户端:" + text);input.value = "";core.receiveText(text);}core.sendText.connect(function(message) {output("服务器: " + message);});core.receiveText("客户端已连接,准备发送/接收消息!");output("客户端:客户端已连接,准备发送/接收消息!");});}}//END SETUP</script><style type="text/css">html {height: 100%;width: 100%;}#input {width: 400px;margin: 0 10px 0 0;}#send {width: 90px;margin: 0;}#output {width: 500px;height: 300px;}</style></head><body><textarea id="output"></textarea><br /><input id="input" /><input type="submit" id="send" value="Send" οnclick="javascript:click();" /></body>
</html>

2、问题

2.1、问题一:Cannot invoke unknown method of index -1 on object webTransport(0x…)

问题描述:运行时,Qt向Js端发送消息没有问题,Js端向Qt端发送消息时失败。
原因及解决办法:使用Qt 5.11.2编译生成的可执行程序,而网页端用的是Qt 5.14的qwebchannel.js文件,版本不兼容导致的,换成对应的qwebchannel.js文件就好了

2.2、问题二:Qwebchannel is not defined at webSocket.socket.onopen

问题描述:加载时无法连接qt。
原因及解决办法:没有加载qwebchannel.js文件

<script type="text/javascript" src="../js/qwebchannel.js"></script>

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Matlab simulink建模与仿真 第七章(表查询库)
  • 【C++多线程编程】 线程安全与对象生命周期管理
  • ffmpeg的安装和使用教程
  • [数据集][目标检测]人脸口罩佩戴目标检测数据集VOC+YOLO格式8068张3类别
  • 【C++ 宏定义 使用】
  • vue3写一个无限树形菜单,递归组件
  • 利用AI进行社交媒体创作及管理的14种简单方法
  • AOSP:在rom中打入一个脚本
  • ARM----时钟
  • 【全网最全】2024年数学建模国赛B题31页完整建模过程+25页成品论文+matlab/python代码等(后续会更新
  • 【数据库】MySQL表的Updata(更新)和Delete(删除)操作
  • 【Hot100】LeetCode—394. 字符串解码
  • Post-Training有多重要?一文带你了解全部细节
  • 【MySQL00】【 杂七杂八】
  • Python 错误 TypeError 解析,实际错误实例详解 (五)
  • (三)从jvm层面了解线程的启动和停止
  • 《Java8实战》-第四章读书笔记(引入流Stream)
  • 【翻译】Mashape是如何管理15000个API和微服务的(三)
  • download使用浅析
  • ES6, React, Redux, Webpack写的一个爬 GitHub 的网页
  • hadoop集群管理系统搭建规划说明
  • Iterator 和 for...of 循环
  • LeetCode18.四数之和 JavaScript
  • MySQL QA
  • Node 版本管理
  • node学习系列之简单文件上传
  • php中curl和soap方式请求服务超时问题
  • Promise面试题2实现异步串行执行
  • Webpack 4x 之路 ( 四 )
  • 笨办法学C 练习34:动态数组
  • 从tcpdump抓包看TCP/IP协议
  • 对话 CTO〡听神策数据 CTO 曹犟描绘数据分析行业的无限可能
  • 看域名解析域名安全对SEO的影响
  • 入门级的git使用指北
  • 使用权重正则化较少模型过拟合
  • 世界上最简单的无等待算法(getAndIncrement)
  • 数组的操作
  • 以太坊客户端Geth命令参数详解
  • 正则学习笔记
  • ‌JavaScript 数据类型转换
  • #1015 : KMP算法
  • #include<初见C语言之指针(5)>
  • #中国IT界的第一本漂流日记 传递IT正能量# 【分享得“IT漂友”勋章】
  • (10)Linux冯诺依曼结构操作系统的再次理解
  • (2024)docker-compose实战 (9)部署多项目环境(LAMP+react+vue+redis+mysql+nginx)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第14章泛型第2节(泛型类的类构造函数)
  • (阿里云在线播放)基于SpringBoot+Vue前后端分离的在线教育平台项目
  • (附源码)springboot优课在线教学系统 毕业设计 081251
  • (附源码)计算机毕业设计SSM基于java的云顶博客系统
  • (含笔试题)深度解析数据在内存中的存储
  • (三)uboot源码分析
  • (图文详解)小程序AppID申请以及在Hbuilderx中运行
  • (学习日记)2024.02.29:UCOSIII第二节
  • .md即markdown文件的基本常用编写语法
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案