13

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);
}
Alison R.
  • 4,204
  • 28
  • 33
Martin
  • 1,675
  • 11
  • 34
  • 46

3 Answers3

26

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.

Kleist
  • 7,785
  • 1
  • 26
  • 30
NG.
  • 22,560
  • 5
  • 55
  • 61
  • 1
    I'd like to clarify that nothing prevents you from using Q_DISABLE_COPY macro even if your class doesn't derive from QObject, as it has nothing to do with QObject at all. – rightaway717 Jan 27 '15 at 09:51
5

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.

photo_tom
  • 7,292
  • 14
  • 68
  • 116
0

if you want to transfer data and want to use the very simplest way, just create a signal and slot between both widgets. Connect them in the main widget, and pass data while calling the slot.

Sherif O.
  • 506
  • 4
  • 15