qt调用js

https://github.com/mygit03/DoJS

基于 Qt5.10.1 调用 Python 脚本实现简单的四则运算

 

程序通过调用js脚本的函数执行计算(将计算公式写入js脚本,在程序中通过传参数调用js脚本中的函数进行计算,最后将计算结果返回,显示到界面)

//DoJS.pro

#------------------------------------------------- # # Project created by QtCreator 2017-03-22T10:16:33 # #-------------------------------------------------   QT       += core gui script   greaterThan(QT_MAJOR_VERSION, 4): QT += widgets   TARGET = DoJS TEMPLATE = app     SOURCES += main.cpp\         widget.cpp   HEADERS  += widget.h   FORMS    += widget.ui   DISTFILES += \     TransCal.js   RESOURCES += \     dojs.qrc //widget.h

#ifndef WIDGET_H #define WIDGET_H   #include <QWidget>   namespace Ui { class Widget; }   class Widget : public QWidget {     Q_OBJECT   public:     explicit Widget(QWidget *parent = 0);     ~Widget();       void readJS();   private slots:     void on_btn_cal_clicked();   private:     Ui::Widget *ui; };   #endif // WIDGET_H //widget.cpp

#include "widget.h" #include "ui_widget.h"   #include <QDebug> #include <QFile> #include <QTextStream> #include <QScriptEngine> #include <QScriptValue> #include <QScriptValueList>   Widget::Widget(QWidget *parent) :     QWidget(parent),     ui(new Ui::Widget) {     ui->setupUi(this);       ui->lineEdit_var1->setText("12");     ui->lineEdit_var2->setText("0.5"); }   Widget::~Widget() {     delete ui; }   void Widget::readJS() {     QString result = "";     QFile scriptFile(":/TransCal.js");     if (!scriptFile.open(QIODevice::ReadOnly))     {         result.clear();         qWarning() << "encodePass.js open failed";         return;     }     QTextStream out(&scriptFile);     QString contents = out.readAll();     scriptFile.close();       double var1 = ui->lineEdit_var1->text().toDouble();     double var2 = ui->lineEdit_var2->text().toDouble();     qDebug() << "var1:" << var1 << "var2:" << var2;       QScriptValueList args;      //调用js方法时传入的参数     args << QScriptValue(var1) << QScriptValue(var2);     QScriptEngine engine;     QScriptValue js = engine.evaluate(contents);        //个人理解:加载js文本到操作引擎     QScriptValue func;     func = engine.globalObject().property("trans2wCal");   //调用js方法     result = func.call(QScriptValue(), args).toString();     qDebug() << "result:" << result;     ui->lineEdit_sub->setText(result);       func = engine.globalObject().property("trans3wCal");   //调用js方法     result = func.call(QScriptValue(), args).toString();     qDebug() << "result:" << result;     ui->lineEdit_mul->setText(result); }   void Widget::on_btn_cal_clicked() {     readJS(); }

//TransCal.js

//trans.js   function trans2wCal(var1,var2) {     return var1+var2; }   function trans3wCal(var1,var2) {     return var1*var2+5; } //资源文件:dojs.qrc --------------------- 作者:GraceLand525 来源:CSDN 原文:https://blog.csdn.net/graceland525/article/details/64906354 版权声明:本文为博主原创文章,转载请附上博文链接!

posted on 2019-03-01 17:20  杜鹃醉鱼鱼  阅读(232)  评论(0编辑  收藏  举报

导航