Solved 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);
insideForm
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 { Q_OBEJCT public: 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(); form1.copy(form2);
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.
Sinceoperator=
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; form1->ui->labelFilename->setText(form->ui->labelFilename->text()); form1->ui->labelSize->setText(form->ui->labelSize->text()); form1->ui->progressBar->setValue(form->ui->progressBar->value()); form1->ui->labelSpeed->setText(form->ui->labelSpeed->text()); form1->ui->labelURL->setText(form->ui->labelURL->text()); form1->ui->labelElapse->setText(form->ui->labelElapse->text()); form1->ui->labelTimeCreate->setText(form->ui->labelTimeCreate->text()); form1->ui->labelPath->setText(form->ui->labelPath->text());
-
@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?