Important: Please read the Qt Code of Conduct -

How to clone QWidget ?

  • Form *form = new Form;
    Form *form1 = new Form;
    form1 = form;

  • In general. You can't. There is no one-size-fit-all copy solution for QObjects. You are free however to define a public: void clone(Form* other); inside Form and implement your custom clone operation

  • @VRonin How to write clone operation inside QWidget ? It seems have to return a QWidget point in QWidget of itself.

  • Hi, Sonichy, before you write "clone" or "copy" for a QObject, maybe take a look at QObject document section "No Copy Constructor or Assignment Operator" and "Qt Objects: Identity vs Value" on the Qt Object Model page.

  • @sonichy create a class inherit QWidget.

    class Form : public QWidget
      Form(QObject* parent = 0) {
        // Constructor
      // ... whatever
      void clone(Form* other) {
        // clone data of "other" to "this"

    And you can do this:

    Form form1 = new Form();
    Form form2 = new Form();

    Further more, you can free to call functions of QWidget, and you can use QWidget pointer point to Form objects because of polymorphism.

    As the comment above, Qt design objects as identity. Although the two objects we copy have same value, they have different identities, so just implement a copy function to copy the value, and just copy the value to wherever you want.

  • @FloatFlower.Huang said in How to clone QWidget ?:

    form1 = form2; // with operator overloaded.

    Wrong, that's a pointer assignment.
    Since operator= for const reference is deleted I would not make it confusing defining one for a const pointer. the clone method is more than enough

  • @VRonin That my fault, sorry, I will remove the code.
    Thanks for your reminder.

  • There is no way to be lazy, I have to set the data one by one...

    Form *form1 = new Form;

  • @sonichy Is that a question or a statement? Yes, to copy/clone you will have to do so member-by-member. Which would likely be a lot for a whole form/error-prone/unmaintainable/not possible for some widgets.... You really need to make a complete copy of a whole "form", do you?

Log in to reply