How do I copy object in Qt?

I'm using Qt and have some real basic problems. I have created my own widget MyTest that have a variable obj. I need to set this variable obj from an object outside of the widget so that the variable is copied not just a pointer to another object. I get an error message and can't figure out how to do this basic stuff. This is the code I'm using:

MyTest.h:

class MyTest : public QWidget
{
    Q_OBJECT

    public:
        void setObj(QObject &inobj);

        QObject obj;
    ....
}

MyTest.cpp:

void MyTest::setObj(QObject &inobj) {
    obj = inobj; //HERE I get the error message: "illegal access from 'QObject' to protected/private member 'QObject::operator=(const QObject &)'"
}

main.cpp:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QObject *ob = new QObject();

    MyTest w;
    w.setObj(*ob);
}

It seems the copy constructor and assignment operator are disabled. From this.

No copy constructor or assignment operator

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.


Aaron is correct about using the assignment operator.

The only way that I'm aware of to make a copy of an object, if you really have to, is to use Serialization as described in QDataStream Class. This would make a deep copy of the object.

Or have you considered wrapping the class as a QSharedPointer pointer that you can safely pass around. This would be a shadow or reference copy of the object though.