Create a class from QString (Run time)
-
Please explain what you mean by "create a class from a QString". QString already is a class. If you want to make a QObject-based QString, it should be possible by creating a child class. But I simply don't know what you mean.
-
Hi sorry for not explaining my problem well.
Using QMetaObject::invokeMethod, you can call a method by a string.
I am wondering if there is a way to create a class object identifying it by a string.I hope this explains my issue.
Thanks
-
Yes, you can use "QMetaObject::newInstance()":http://qt-project.org/doc/qt-5.0/qtcore/qmetaobject.html#newInstance.
-
[quote author="sierdzio" date="1389605503"]Yes, you can use "QMetaObject::newInstance()":http://qt-project.org/doc/qt-5.0/qtcore/qmetaobject.html#newInstance.[/quote]
I don't think it supports specifying the class as a string, only the method as string. It still involves specifying the class as a "class" not a string.
Example:
@
...
Person::Person(QString name)
{
_name = name;
}
...
Person *person = (Person *)metaObject.newInstance(Q_ARG(QString, QString("Sanderson")));
QString name = person->getName();@ -
Hm, you are right, this is not ideal for your use case. I'm sure I've seen a solution to a similar problem, let me search a bit.
-
-
[quote author="sierdzio" date="1389606830"]See "this":http://stackoverflow.com/questions/2501909/how-can-i-find-a-qt-metaobject-instance-from-a-class-name, and "this":http://kunalmaemo.blogspot.de/2010/07/creating-class-dynamically-from-its.html.[/quote]
they both don't work in Qt5
see my other post
http://qt-project.org/forums/viewthread/36763/#156664 -
It seems that the method you are looking for has been renamed to "create()":http://qt-project.org/doc/qt-5/qmetatype.html#create.
-
C++ does not have a runtime reflection mechanism like some managed languages so you will need to build it yourself.
You would have to create some sort of a map<name, MetaObject instance> (via eg. classname::staticMetaObject) and then at runtime call that map[name].newInstance(...).
Adding classes to that map might be hidden behind a macro of some sort that would be required for all "invokable" classes. Speaking of invokable - as the doc says, your classes, apart from being QObjects, would have to have a constructor marked with Q_INVOKABLE for this to work.Edit Yeah, what sierdzio suggested basically does exactly that for you :)
-
I have solved my issue, this worked for me
@
class Parser
{
public:
virtual void parse() = 0;
};class Parser1 : public Parser
{
public:
Parser1(){}
void parse()
{
qDebug() << "Parser1::parse()";
}
};
Q_DECLARE_METATYPE(Parser1)int main ( int argc, char* argv[] )
{
qRegisterMetaType<Parser1>("Parser1*");
int id = QMetaType::type("Parser1");
if (id != QMetaType::UnknownType) {
Parser parser = static_cast< Parser >
( QMetaType::create( id ) );
parser->parse();
} else {
qDebug() << "QMetaType::UnknownType";
}
}
@