Duplicate a QWidget

Geore Shg picture Geore Shg · Jul 24, 2011 · Viewed 8.1k times · Source

I need to be able to copy a Qwidget so I can duplicate a window because it will change during runtime. is this possible?

void Duplicate(QWidget * Show)
{
 //I tried...
 Qwidget Shw = *Show; //but operator= is private
 //and the copy constructor (I think), which is also private
 Qwidget Shw(*Show);
 //

 Shw.Show();
}

Answer

Stu Mackellar picture Stu Mackellar · Jul 24, 2011

This is by design. The usual way to solve it is to implement a method (typically called clone()) that allows you to specify the exact semantics that should apply when copying instances of your class. This approach also prevents unintentional copies from being made implicitly, e.g by container classes.

From the Qt docs:

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.