Important: Please read the Qt Code of Conduct -

How do I instantiate many object instance with QPluginLoader?

  • In Qt documentation(

    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 from QPluginLoader?

    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->;

    d is a pointer point to QLibraryPrivate, which keep a QPointer<QObject> inst; point to the object that create from instance(), so I think the object create from QPluginLoader 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.

  • Qt Champions 2019

    @FloatFlower.Huang Your root object (Foo in the example) should create the instances you need.
    See here

    class MyStylePlugin : public QStylePlugin
        Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QStyleFactoryInterface" FILE "mystyleplugin.json")
        QStyle *create(const QString &key);

  • @jsulm Thanks a lot!
    Sorry, I didn't read the documentation carefully.

Log in to reply