Studying QtScript examples and using my own code (see my previous post regarding QtScript ) I can't quite understand how QtScript instantiate C++ classes where constructor has arguments.

Tracing the code (shown below) I can see that default constructor with no arguments get called, then my factory code get called and correct test(int) is called with agrument (10, in my case), but at the end of it my script receives an instance constructed with prototype where default constructor is invoked (_i == 0) . So, when following script is evaluated, returned value is 1 and not 11 as I expect.

Any comments, suggestions are very much appreciated.
Qt Code:
  1. //Script that is evaluated
  2. var t = new test(10)
  3. t.val + 1
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. // part of the code that evaluates script
  2. QString script = scriptText; // above script
  3. QScriptEngine interpreter;
  4. test::registerWithScript("test", interpreter);
  5. QScriptValue result = interpreter.evaluate(script);
To copy to clipboard, switch view to plain text mode 
Qt Code:
  1. // support class to help with default constructor and registering
  2. template <typename T> class Scriptable
  3. {
  4. public:
  5. Scriptable()
  6. {
  7. }
  8.  
  9.  
  10. static void registerWithScript(const char* scriptObjName, QScriptEngine& scriptengine)
  11. {
  12. T* t = new T();
  13. QScriptValue obj = scriptengine.newQObject(t, QScriptEngine::ScriptOwnership);
  14. scriptengine.setDefaultPrototype(qMetaTypeId<T>(),obj);
  15. QScriptValue objCtor = scriptengine.newFunction(objectConst, obj);
  16. scriptengine.globalObject().setProperty(scriptObjName, objCtor);
  17. }
  18.  
  19. private:
  20. static QScriptValue objectConst (QScriptContext* context, QScriptEngine* scriptengine)
  21. {
  22. boost::scoped_ptr<T> t(T::factory (context));
  23. return scriptengine->toScriptValue(*t);
  24. }
  25. };
  26.  
  27.  
  28. //test class; to study QtScript
  29. class test : public QObject, public QScriptable, public Scriptable<test>
  30. {
  31. Q_OBJECT
  32. Q_PROPERTY(int val READ val WRITE set)
  33. public:
  34. test (int i = 0) : _i(i)
  35. {
  36. }
  37. test (const test& another) : _i(another._i)
  38. {
  39. int i = _i;
  40. }
  41. virtual ~test ()
  42. {
  43. int i = _i;
  44. }
  45.  
  46. test& operator = (const test& another)
  47. {
  48. _i = another._i;
  49. return *this;
  50. }
  51. void set(int i)
  52. {
  53. _i = i;
  54. }
  55. int val()
  56. {
  57. return _i;
  58. }
  59.  
  60. static test* factory (QScriptContext* context)
  61. {
  62. if (context->argumentCount() == 0)
  63. return new test();
  64. else
  65. {
  66. int i = context->argument(0).toInt32();
  67. return new test(i);
  68. }
  69. }
  70. private:
  71. int _i;
  72. };
  73.  
  74. Q_DECLARE_METATYPE(test)
  75. Q_DECLARE_METATYPE(test*)
To copy to clipboard, switch view to plain text mode