How to Create Qt Plugins

A guide to creating plugins to extend Qt applications and functionality provided by Qt.

Qt provides two APIs for creating plugins:

  • A higher-level API for writing extensions to Qt itself: custom database drivers, image formats, text codecs, custom styles, etc.
  • A lower-level API for extending Qt applications.

For example, if you want to write a custom QStyle subclass and have Qt applications load it dynamically, you would use the higher-level API.

Since the higher-level API is built on top of the lower-level API, some issues are common to both.

If you want to provide plugins for use with Qt Designer, see the QtDesigner module documentation.

Topics:

The Higher-Level API: Writing Qt Extensions

Writing a plugin that extends Qt itself is achieved by subclassing the appropriate plugin base class, implementing a few functions, and adding a macro.

There are several plugin base classes. Derived plugins are stored by default in sub-directories of the standard plugin directory. Qt will not find plugins if they are not stored in the right directory.

Base ClassDirectory NameKey Case Sensitivity
QAccessibleBridgePlugin accessiblebridgeCase Sensitive
QAccessiblePlugin accessibleCase Sensitive
QDecorationPlugin decorationsCase Insensitive
QFontEnginePlugin fontenginesCase Insensitive
QIconEnginePlugin iconenginesCase Insensitive
QImageIOPlugin imageformatsCase Sensitive
QInputContextPlugin inputmethodsCase Sensitive
QKbdDriverPlugin kbddriversCase Insensitive
QMouseDriverPlugin mousedriversCase Insensitive
QScreenDriverPlugin gfxdriversCase Insensitive
QScriptExtensionPlugin scriptCase Sensitive
QSqlDriverPlugin sqldriversCase Sensitive
QStylePlugin stylesCase Insensitive
QTextCodecPlugin codecsCase Sensitive

Suppose that you have a new style class called MyStyle that you want to make available as a plugin. The required code is straightforward, here is the class definition (mystyleplugin.h):

  1. class MyStylePlugin : public QStylePlugin
  2.  {
  3. public:
  4.     QStringList keys() const;
  5.     QStyle *create(const QString &key);
  6. };

Ensure that the class implementation is located in a .cpp file (including the class definition):

  1. #include "mystyleplugin.h"
  2.  
  3. QStringList MyStylePlugin::keys() const
  4.  {
  5.     return QStringList() << "MyStyle";
  6. }
  7.  
  8. QStyle *MyStylePlugin::create(const QString &key)
  9.  {
  10.     if (key.toLower() == "mystyle")
  11.         return new MyStyle;
  12.     return 0;
  13. }
  14.  
  15. Q_EXPORT_PLUGIN2(pnp_mystyleplugin, MyStylePlugin)

(Note that QStylePlugin is case insensitive, and the lower-case version of the key is used in our create() implementation; most other plugins are case sensitive.)

For database drivers, image formats, text codecs, and most other plugin types, no explicit object creation is required. Qt will find and create them as required. Styles are an exception, since you might want to set a style explicitly in code. To apply a style, use code like this:

  1.                 QApplication::setStyle(QStyleFactory::create("MyStyle"));

Some plugin classes require additional functions to be implemented. See the class documentation for details of the virtual functions that must be reimplemented for each type of plugin.

The Style Plugin Example shows how to implement a plugin that extends the QStylePlugin base class.

The Lower-Level API: Extending Qt Applications

Not only Qt itself but also Qt application can be extended through plugins. This requires the application to detect and load plugins using QPluginLoader. In that context, plugins may provide arbitrary functionality and are not limited to database drivers, image formats, text codecs, styles, and the other types of plugin that extend Qt's functionality.

Making an application extensible through plugins involves the following steps:

  1. Define a set of interfaces (classes with only pure virtual functions) used to talk to the plugins.
  2. Use the Q_DECLARE_INTERFACE() macro to tell Qt's meta-object system about the interface.
  3. Use QPluginLoader in the application to load the plugins.
  4. Use qobject_cast() to test whether a plugin implements a given interface.

Writing a plugin involves these steps:

  1. Declare a plugin class that inherits from QObject and from the interfaces that the plugin wants to provide.
  2. Use the Q_INTERFACES() macro to tell Qt's meta-object system about the interfaces.
  3. Export the plugin using the Q_EXPORT_PLUGIN2() macro.
  4. Build the plugin using a suitable .pro file.

For example, here's the definition of an interface class:

  1. class FilterInterface
  2.  {
  3. public:
  4.     virtual ~FilterInterface()  {}
  5.  
  6.     virtual QStringList filters() const = 0;
  7.     virtual QImage filterImage(const QString &filter, const QImage &image,
  8.                                QWidget *parent) = 0;
  9. };

Here's the definition of a plugin class that implements that interface:

  1. #include <QObject>
  2. #include <QStringList>
  3. #include <QImage>
  4.  
  5. #include <plugandpaint/interfaces.h>
  6.  
  7. class ExtraFiltersPlugin : public QObject, public FilterInterface
  8.  {
  9.     Q_OBJECT
  10.     Q_INTERFACES(FilterInterface)
  11.  
  12. public:
  13.     QStringList filters() const;
  14.     QImage filterImage(const QString &filter, const QImage &image,
  15.                        QWidget *parent);
  16. };

The Plug & Paint example documentation explains this process in detail. See also Creating Custom Widgets for Qt Designer for information about issues that are specific to Qt Designer. You can also take a look at the Echo Plugin Example is a more trivial example on how to implement a plugin that extends Qt applications. Please note that a QCoreApplication must have been initialized before plugins can be loaded.

Locating Plugins

Qt applications automatically know which plugins are available, because plugins are stored in the standard plugin subdirectories. Because of this applications don't require any code to find and load plugins, since Qt handles them automatically.

During development, the directory for plugins is QTDIR/plugins (where QTDIR is the directory where Qt is installed), with each type of plugin in a subdirectory for that type, e.g. styles. If you want your applications to use plugins and you don't want to use the standard plugins path, have your installation process determine the path you want to use for the plugins, and save the path, e.g. using QSettings, for the application to read when it runs. The application can then call QCoreApplication::addLibraryPath() with this path and your plugins will be available to the application. Note that the final part of the path (e.g., styles) cannot be changed.

If you want the plugin to be loadable then one approach is to create a subdirectory under the application and place the plugin in that directory. If you distribute any of the plugins that come with Qt (the ones located in the plugins directory), you must copy the sub-directory under plugins where the plugin is located to your applications root folder (i.e., do not include the plugins directory).

Note: In Symbian all binaries must be located in the directory \sys\bin, so each Qt plugin has a stub with the same basename as the plugin dll and suffix ".qtplugin" to make Qt extension plugins work similarly to other platforms. When trying to locate the plugin, Qt actually looks for the stub instead of the plugin binary. While plugin stub files have the suffix ".qtplugin", they can still be loaded also by specifying a filename with the normal library suffix ".dll" for QPluginLoader, so normally application developer doesn't need to care about the different suffix of the stub. Because of the way applications can be installed on ROM or various other drives in Symbian, Qt looks for the stub from the same directory on all available drives if it is not located in the given directory when loading a plugin.

For more information about deployment, see the Deploying Qt Applications and Deploying Plugins documentation.

Static Plugins

The normal and most flexible way to include a plugin with an application is to compile it into a dynamic library that is shipped separately, and detected and loaded at runtime.

Plugins can be linked statically against your application. If you build the static version of Qt, this is the only option for including Qt's predefined plugins. Using static plugins makes the deployment less error-prone, but has the disadvantage that no functionality from plugins can be added without a complete rebuild and redistribution of the application.

When compiled as a static library, Qt provides the following static plugins:

Plugin nameTypeDescription
qtaccessiblecompatwidgetsAccessibilityAccessibility for Qt 3 support widgets
qtaccessiblewidgetsAccessibilityAccessibility for Qt widgets
qdecorationdefaultDecorations (Qt Extended)Default style
qdecorationwindowsDecorations (Qt Extended)Windows style
qgifImage formatsGIF
qjpegImage formatsJPEG
qmngImage formatsMNG
qicoImage formatsICO
qsvgImage formatsSVG
qtiffImage formatsTIFF
qimsw_multiInput methods (Qt Extended)Input Method Switcher
qwstslibmousehandlerMouse drivers (Qt Extended) tslib mouse
qgfxtransformedGraphic drivers (Qt Extended)Transformed screen
qgfxvncGraphic drivers (Qt Extended)VNC
qscreenvfbGraphic drivers (Qt Extended)Virtual frame buffer
qsqldb2SQL driverIBM DB2
qsqlibaseSQL driverBorland InterBase
qsqliteSQL driverSQLite version 3
qsqlite2SQL driverSQLite version 2
qsqlmysqlSQL driverMySQL
qsqlociSQL driverOracle (OCI)
qsqlodbcSQL driverOpen Database Connectivity (ODBC)
qsqlpsqlSQL driverPostgreSQL
qsqltdsSQL driverSybase Adaptive Server (TDS)
qcncodecsText codecsSimplified Chinese (People's Republic of China)
qjpcodecsText codecsJapanese
qkrcodecsText codecsKorean
qtwcodecsText codecsTraditional Chinese (Taiwan)

To link statically against those plugins, you need to use the Q_IMPORT_PLUGIN() macro in your application and you need to add the required plugins to your build using QTPLUGIN. For example, in your main.cpp:

  1. #include <QApplication>
  2. #include <QtPlugin>
  3.  
  4. Q_IMPORT_PLUGIN(qjpeg)
  5. Q_IMPORT_PLUGIN(qgif)
  6. Q_IMPORT_PLUGIN(qkrcodecs)
  7.  
  8. int main(int argc, char *argv[])
  9.  {
  10.     QApplication app(argc, argv);
  11.     ...
  12.     return app.exec();
  13. }

In the .pro file for your application, you need the following entry:

  1. QTPLUGIN     += qjpeg \
  2.                 qgif \
  3.                 qkrcodecs

It is also possible to create your own static plugins, by following these steps:

  1. Add CONFIG += static to your plugin's .pro file.
  2. Use the Q_IMPORT_PLUGIN() macro in your application.
  3. Link your application with your plugin library using LIBS in the .pro file.

See the Plug & Paint example and the associated Basic Tools plugin for details on how to do this.

Note: If you are not using qmake to build your application you need to make sure that the QT_STATICPLUGIN preprocessor macro is defined.

Deploying and Debugging Plugins

The Deploying Plugins document covers the process of deploying plugins with applications and debugging them when problems arise.

See also QPluginLoader, QLibrary, and Plug & Paint Example.

Notes provided by the Qt Community

No notes