1

我目前有一个功能 QT 应用程序,有几个按钮。

我需要直接从 javascript 控制我的应用程序,如下例所示,其中 AccessControl 是我的 QObject 类:

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);
    }
}

我现有的应用程序像这样连接信号和插槽:

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

我是 QT 的初学者,我想做的就是让用户可以使用脚本而不是单击 UI。

我已经阅读了 QTScript 文档,但我确实很难理解它。

如果有人可以向我解释如何做到这一点,或者如果您有一些好且容易理解的例子,那就太好了!

编辑以获取有关我的问题的更多信息:

我的应用程序是一个访问控制模拟器。我有几个按钮来开门、关门、配置价格……我想编写这个应用程序的脚本,以便在每个可能的情况下创建测试,而不需要点击 UI 的用户在场。

谢谢。

4

2 回答 2

1

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.

于 2013-11-27T08:38:48.957 回答
1

您可以将一个类连接到 JavaScript。这是一个 PySide python 示例。

class MyCLass(object):
    @QtCore.Slot(str)
    def doSomething(self, info):
        # do something with the string info here

frame.addToJavaScriptWindowObject("varName", MyClass)
frame.evaluateJavaScript("varName.doSomething('string')")

我认为这就是你在 C++ 中的做法。这是插槽http://qt-project.org/doc/qt-4.8/signalsandslots.html的链接。QWebFrame 可以将对象添加到 javascript 并运行 javascript 代码。

class MyClass {
public slots:
     void doSomething(String info);
于 2013-11-26T14:10:49.557 回答