由于当前C++项目需要使用ajax库去post调用ashx接口,接口地址如下所示:
需要传递的参数如下:
然后发现qml比较好调用库,所以本章通过C++界面去获取qml方法来实现调用ashx接口(以一个C++界面demo程序为例)
1.抓post数据
通过网页获取到的post数据如下所示:
所以查询20191121~20191122期间时则填入内容: "deptCode=021&startDate=20191121&endDate=20191122"
2.导入库
文件如下所示:
//GETfunctionget(url, success, failure)
{var xhr = newXMLHttpRequest;
("GET", url);
=function() {
handleResponse(xhr, success, failure);
}
();
}//POSTfunction post(url, arg, success, failure)
{var xhr = newXMLHttpRequest;
("POST", url);
("Content-Length", );
("Content-Type", "application/x-www-form-urlencoded;"); //用POST的时候一定要有这句=function() {
handleResponse(xhr, success, failure);
}
(arg);
}//处理返回值function handleResponse(xhr, success, failure){if ( ==) {if ( == 200){if (success != null && success !=undefined)
{var result =;try{
success(result, (result));
}catch(e){
success(result, {});
}
}
}else{if (failure != null && failure !=undefined)
failure(, );
}
}
}
3.写
import QtQuick 2.3import QtQuick.Window2.2import"" asAjax
Item {function getWrenchTools(deptCode,startDate,endDate) {
console.log("Got message:", deptCode,startDate,endDate)//打印参数数据
("http://10.194.102.253/WLPTService/Pages/Tools/","deptCode="+deptCode+"&startDate="+startDate+"&endDate="+endDate+"",
);
}
这里表示定义一个getWrenchTools()方法,当post成功并返回数据时,则调用()回调函数(Widget: 该qml对应的C++类,后面会讲怎么捆绑的)
界面如下
然后写
#ifndef WIDGET_H#define WIDGET_H#include#include#include#include#include#include
namespaceUi {classwidget;
}class widget : publicQWidget
{
Q_OBJECT
QQmlApplicationEngine engine;
QObject*engineObject; //指向运行的qml对象
public:explicit widget(QWidget *parent = 0);~widget();private:
Ui::widget*ui;public:
Q_INVOKABLEvoidinvokeFunc(QVariant data1,QVariant data2);privateslots:voidon_pushButton_clicked();
};#endif //WIDGET_H
写
#include ""#include"ui_widget.h"#include#includewidget::widget(QWidget*parent) :
QWidget(parent),
ui(newUi::widget)
{
ui->setupUi(this);
()->setContextProperty("Widget",this);//将QML中的Widget变量指向为当前类.从而使QML和widget类连接起来
engineObject= QQmlComponent(&engine, "qrc:/").create(); //创建qml并获取运行中的qml对象
}
widget::~widget()
{deleteui;
}voidwidget::invokeFunc(QVariant data1,QVariant data2)
{
ui->plainTextEdit->setPlainText(());
}voidwidget::on_pushButton_clicked()
{
QVariant depatment= "021";
QVariant start= ui->start->text();
QVariant end= ui->end->text(); //"结束日期"
QMetaObject::invokeMethod(engineObject,"getWrenchTools",Q_ARG(QVariant, depatment)\
,Q_ARG(QVariant, start),Q_ARG(QVariant, end));
}
()->setContextProperty("Widget",this)的作用:
将QML中的Widget变量指向为当前类.从而使QML和widget类连接起来, 然后如果post成功则调用当前类的invokeFunc(QVariant data1,QVariant data2)方法,从而实现数据返回.
当按下同步按钮时,则调用on_pushButton_clicked():
由于engineObject指向运行中的qml对象,然后我们通过invokeMethod()就可以方便的请求调用qml对象中的getWrenchTools()函数.从而实现post请求
点击同步后,效果如下
注意-如果出现QQmlComponent: Component is not ready字段,说明qml和js所在路径不在界面文件夹里
创建文件的时候,就需要将文件都放在界面目录中,才行: