Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QScriptEngine import custom object



  • Hello,
    I have problem with import custom object to the script.
    In custom object is another custom object, and here is a problem.
    I don't know where I do misstage...

    Headers of two classes:

    class PERSON: public QObject{
    	Q_OBJECT
    public:
    	Q_PROPERTY(QString  name MEMBER name)
    	PERSON(QObject * parent=nullptr):QObject(parent){}
    	PERSON(const PERSON & other):QObject(other.parent()){
    		name=other.name;
    	}
    	PERSON & operator=(const PERSON & other){
    		name=other.name;
    		return *this;
    	}
    	bool operator!=(const PERSON & other){
    		return name==other.name?true:false;
    	}
    	QString name;
    };
    Q_DECLARE_METATYPE(PERSON)
    
    class CITY: public QObject{
    	Q_OBJECT
    public:
    	Q_PROPERTY(QString  cityName MEMBER cityName)
    	Q_PROPERTY(PERSON  commander MEMBER commander)
    	CITY(QObject * parent=nullptr):QObject(parent){}
    	CITY(const CITY & other):QObject(other.parent()){
    		commander=other.commander;
    		cityName=other.cityName;
    	}
    	CITY & operator=(const CITY & other){
    		commander=other.commander;
    		cityName=other.cityName;
    		return *this;
    	}
    	PERSON commander;
    	QString cityName;
    };
    Q_DECLARE_METATYPE(CITY)
    

    Here is code:

    	CITY * city=new CITY(this);
    	city->cityName="Prague";
    	city->commander.name="Novak";
    	QScriptEngine engine;
    	QScriptValue objectValue = engine.newQObject(city);
    	engine.globalObject().setProperty("city", objectValue);
    	qDebug()<<"old City:"<<city->cityName<<" old Commander:"<<city->commander.name;
    	qDebug()<<"SCRIPT OUT:"<<engine.evaluate("city.cityName='Brno';city.commander.name='Pepa';city.commander.name").toString();
    	qDebug()<<"new City:"<<city->cityName<<" new Commander:"<<city->commander.name;
    

    And here is an output:

    old City: "Prague"  old Commander: "Novak"
    SCRIPT OUT: "undefined"
    new City: "Brno"  new Commander: "Novak"
    
    

    So please could you help me?

    Thanks!!



  • If I use:

    Q_PROPERTY(PERSON * commander READ getCommander)
    

    instead

    Q_PROPERTY(PERSON  commander MEMBER commander)
    

    Now It's working. Could anyone explain this mystery to me?
    Only pointer to object is allowed to access to class member? Cannot be reference?


Log in to reply