Search code examples
javascriptc++qtqtscript

Add javascript support to existing QT application


I curently have a functional QT app, with several buttons.

I need to control my application directly from javascript as the following example where AccessControl is my QObject class :

AccessControl.configure("price",10);
AccessControl.configure("autoClose",false);
var ret = AccessControl.sendAskAliveMessage() ;
if(!ret)
{
    AccessControl.print("Toll not found");
}
else
{
    ret = AccessControl.SendTransactionMessage() ;

    if(ret)
    {
        AccessControl.Open();
        wait(10000);
        AccessControl.Close();
    }
    else
    {
        AccessControl.printError(ret);
    }
}

My existing application connect signals and slots like that :

QObject::connect(&w, SIGNAL(SendTransaction()),
               &Toll, SLOT(SendTransactionMessage()));

I'm a beginner to QT, and all I want to do, is give the possibility to the user to use scripts instead of clicking on the UI.

I have read the QTScript documentation, but I have really some dificulties to understand it.

If anyone can explain me how to do it or if you have some good and easy example to understand, that will be great !

EDIT for more information on my question :

My application is an acess control simulator. I have several buttons in order to open the door, close it, configure the price, ... I want to script this application in order to create test every possible case, without the presence of a user who need to click on the UI.

Thanks.


Solution

  • I've found a really good example, who helped me a lot.

    You can find the code here : QTScriptTest

    Jay's and Justin answer are true, if the function is in "public slot", it will be accessible from script.

    My working code :

      MyClass AccessControl();
    
      QScriptEngine scriptEngine;
    
      QScriptValue AccessControlValue = scriptEngine.newQObject(&AccessControl);
      Q_ASSERT (AccessControl.isQObject());
    
      scriptEngine.globalObject().setProperty("AccessControl", AccessControlValue);
    
      [...]//SLOT and SIGNAL connection
    
      while(getchar() != 'q')  
      {
        QFile file("Script.js");
        file.open(QIODevice::ReadOnly);
        QScriptValue result = scriptEngine.evaluate(file.readAll());
    
        if(result.toString() != "undefined")
          std::cout << result.toString().toStdString() << std::endl;
    
        file.close();
    
        if (scriptEngine.hasUncaughtException()) 
        {
          int lineNo = scriptEngine.uncaughtExceptionLineNumber();
          printf("lineNo : %i", lineNo);
        }
      }
    

    With Justin example:

    class MyClass {
    public slots:
     void doSomething(String info);
    

    Now it works fine, and it evaluate my script everytime I press enter, so, I can modify my script without closing my application, and just reevaluate it.