Qt Script之calculator
简易计算器主要有数字,一元操作符,二元操作符,和memory操作
初始状态等待输入操作数,若输入的是运算符得到的运算结果依然是0.若输入的是数字则显示出来
并将等待操作数设置为false,下次若还是数字则直接添加到后面如果是一元运算符则直接得出结果
显示出来,若是二元运算符则分别用sumSoFar(记录加减操作数),factorSoFar(记录乘除操作数)和用
pendingAdditiveOperator(加减),pendingMultiplicativeOperator(乘除)运算符并设置等待操作数为true
//main.cpp
int main(int argc, char **argv)
{
Q_INIT_RESOURCE(calculator);//初始化资源
QApplication app(argc, argv);
//! [0a]
QScriptEngine engine;//JS引擎解释执行JS代码
//! [0a]
//JS调试窗口
if !defined(QT_NO_SCRIPTTOOLS)
QScriptEngineDebugger debugger;
debugger.attachTo(&engine);
QMainWindow *debugWindow = debugger.standardWindow();
debugWindow->resize(1024, 640);
//debugWindow->show();
endif
//! [0b] 加载JS代码
QString scriptFileName(":/calculator.js");
QFile scriptFile(scriptFileName);
scriptFile.open(QIODevice::ReadOnly);
engine.evaluate(scriptFile.readAll(), scriptFileName);
scriptFile.close();
//! [0b]
//! [1]加载界面UI文件
QUiLoader loader;
QFile uiFile(":/calculator.ui");
uiFile.open(QIODevice::ReadOnly);
QWidget *ui = loader.load(&uiFile);
uiFile.close();
//! [1]
//! [2]
QScriptValue ctor = engine.evaluate("Calculator");//执行Calculator代码
QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership);//创建一个script下的UI对象
QScriptValue calc = ctor.construct(QScriptValueList() << scriptUi);//构造Calculator对象
//! [2]
if !defined(QT_NO_SCRIPTTOOLS)
QLineEdit *display = ui->findChild<QLineEdit*>("display");
QObject::connect(display, SIGNAL(returnPressed()),
debugWindow, SLOT(show()));
endif
//! [3]
ui->show();
return app.exec();
//! [3]
}
//calculator.js
Function.prototype.bind = function() {
var func = this;//this即Function
var thisObject = arguments[0];//函数执行上下文
var args = Array.prototype.slice.call(arguments, 1);//将具有length属性的对象转成数组
return function() {
return func.apply(thisObject, args);//调用func函数
}
}
//! [0]
function Calculator(ui)
{
this.ui = ui;//获取界面
this.pendingAdditiveOperator = Calculator.NO_OPERATOR;//未决定的加法操作符
this.pendingMultipl