Make a class inherit form QDeclarativeItem, copy constructor.
-
Hello,
I am working on a project where the user interface is completelly made with QML but I need my own types of objects. Therefore, I have implemented a class (let's call it A) completelly independent of QML and now I want to make A instanciable through QML. I know that to to so, I need to make A inherit from QDeclarativeItem. The point is: mi class A has a copy constructor, and QDeclarativeItem's is private, therefore I cannot call it. How can I then make my copy constructor?
Thank you!
-
First of all, for what you want to do, you don't have to inherit from QDeclarativeItem.
If class A is not a visual item that you want to show through QML then you will make it inherit from QObject. Still you will need again to create a copy constructor.
@class A : public QObject
{
Q_OBJECTpublic:
//normal constructor
A(QObject* parent=NULL);//copy constructor
A(A& otherInstance){
//assign properties one by one from "otherInstance" to "this"
}//Invocable function (non slot)
Q_INVOKABLE void fun();public slots:
signals:private:
//class properties
//...
}
@Remember that invocable methods from QML are the ones that are either defined as Q_INVOKABLE or as slots.
-
Thank you for your answer and your time!
I have a general question about what you said: if QObject's copy constructor is private, then my copy constructor cannot call it. Therefore, what happens to all the attributes I inherit from QObjcet? qre they well copied? or should y call the default QObject constructor?
Secondly, I believe that I do have to inherit from QDeclarativeItem... but maybe I didn't get it right from the examples I have read.... What I want to do is draw in QML something (a circle in fact) that is an instance of my class A. The user can then for example change the color of the circle (with a click, for example) and this would change both the actual color of the circle and a variable in my class called "color" (even though my class A has many attributes and methods that are not related to teh QML interface).
Sorry if I didn't explain it really well. To do so, do I need to inherit from QDeclarativeItem?Thankyou for you answer!
-
Yes you are correct. You do have to inherit from QDeclarativeItem since it is a visual item.
Now regarding the copy constructor. The reason why the copy construction of any QObject is private is because by default the Qt standards what to make you use pointers instead of many copied instances. For this you can read the following from the documentation: "No copy constructor or assignment operator":http://doc.qt.digia.com/qt/qobject.html#no-copy-constructor-or-assignment-operator
So what you can do next in your code. Make all the assignments regarding your class A to use only pointers or references. For example, a common use-case is when you want to return from a function an instance of this class. Return the pointer, not a copy of the object.
I hope you got the general idea :)