简体   繁体   中英

Create a widget from another as prototype

I need to create a widget with the same type and text from another. My first try will be create a method that check type for multiple cases and return a pointer to it. Something like this:

QWidget* createFromAnother(const QWidget* prototype)
{
    QWidget* wOutput = 0;
    if(prototype->metaObject()->className() == "QTextEdit")
    {
       wOutput = new QTextEdit();
    }else if(prototype->metaObject()->className() == "QLineEdit")
    {
       wOutput = QLineEdit();
    }else if(...){ }
         // -- > The rest of bad-designed code


    QString temp = prototype->property("text");
    wOutput->setProperty("text", temp);

    return wOutput;
}

Yes... it isn't a good idea. So, before start it. Is there any other ways to solve it?

My Qt version is 4.6.2.

Thanks in advance.

You should be able to use QMetaObject::newInstance() for this:

QWidget* createFromAnother(const QWidget* prototype)
{
    QWidget* wOutput = qobject_cast<QWidget*>(prototype->metaObject()->newInstance());

    QString temp = prototype->property("text");
    wOutput->setProperty("text", temp);

    return wOutput;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM