[Qt-interest] How to write a class derive from QObject-based class in QtScript
cubetan
cubetan at 163.com
Tue Aug 9 07:52:06 CEST 2011
Dear Friends,
I want to derive from a QObject-based class using QtScript.
I write a Person class derived from QObject firstly:
class Person : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
public:
Person(const QString& name, QObject* parent=0) :
_name(name), QObject(parent)
{
}
void setName(const QString& name) { this->_name = name; }
QString name() const { return _name; }
Q_INVOKABLE QString toString() const {
return QString::fromLatin1("Person: ") + _name;
}
private:
QString _name;
};
Q_DECLARE_METATYPE(Person*)
then create a constructor function:
static QScriptValue personConstructor(QScriptContext* ctx, QScriptEngine* engine)
{
QString name = ctx->argument(0).toString();
Person* person = new Person(name);
return engine->newQObject(person);
}
QScriptValue ctor = engine->newFunction(personConstructor);
QScriptValue metaObject = engine->newQMetaObject(&Person::staticMetaObject, ctor);
engine->globalObject().setProperty("Person", metaObject);
In javascript, I define a function:
Employee = function(name, salary) {
Person.call(this, name);
this.salary = salary;
}
Employee.prototype = new Person('tan');
Employee.prototype.toString = function() {
print('Employee: ' + this.salary);
}
var e = new Employee('tan',123);
then have a error: undefined function Person.call. How can I define the call function?
var p = new Person('tan');
p instanceof Object; //return true
p instanceof Person; //return false why? How can I get true?
2011-08-09
cubetan
More information about the Qt-interest-old
mailing list