简体   繁体   English

创建另一个作为原型的小部件

[英]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. 我的Qt版本是4.6.2。

Thanks in advance. 提前致谢。

You should be able to use QMetaObject::newInstance() for this: 您应该能够为此使用QMetaObject::newInstance()

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

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

    return wOutput;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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