How do I instantiate many object instance with QPluginLoader?
-
In Qt documentation(http://doc.qt.io/qt-5/qpluginloader.html):
Returns the root component object of the plugin. The plugin is loaded if necessary. The function returns 0 if the plugin could not be loaded or if the root component object could not be instantiated.
If the root component object was destroyed, calling this function creates a new instance.Is it means that each
QPluginLoader
can only instantiate one object? How do I create lots of instance fromQPluginLoader
?In source code, implementation of instance() :
QObject *QPluginLoader::instance() { if (!isLoaded() && !load()) return 0; if (!d->inst && d->instance) d->inst = d->instance(); return d->inst.data(); }
d
is a pointer point toQLibraryPrivate
, which keep aQPointer<QObject> inst;
point to the object that create frominstance()
, so I think the object create fromQPluginLoader
is always singleton, how can I create many different objects from it?The only solution I figure out:
class Foo : public QObject { Object* creator() { return new Foo(); } }
and I can do this:
QPluginLoader loader("PATH/TO/LOADER"); QObject* object = loader.instance(); Foo* foo = qobject_cast<Foo*>(object); Foo *foo1 = foo->creator();
I don't know whether the solution is a good solution or not.
-
@FloatFlower.Huang Your root object (Foo in the example) should create the instances you need.
See here http://doc.qt.io/qt-5/plugins-howto.htmlclass MyStylePlugin : public QStylePlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QStyleFactoryInterface" FILE "mystyleplugin.json") public: QStyle *create(const QString &key); };
-
@jsulm Thanks a lot!
Sorry, I didn't read the documentation carefully.