Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Tous les espaces de nom  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

How to Create Qt Plugins

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-lever 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
QAccessibleBridgePluginaccessiblebridgeCase Sensitive
QAccessiblePluginaccessibleCase Sensitive
QDecorationPlugindecorationsCase Sensitive
QIconEnginePluginiconenginesCase Insensitive
QImageIOPluginimageformatsCase Sensitive
QInputContextPlugininputmethodsCase Sensitive
QKbdDriverPluginkbddriversCase Sensitive
QMouseDriverPluginmousedriversCase Sensitive
QPictureFormatPluginpictureformatsCase Sensitive
QScreenDriverPlugingfxdriversCase Sensitive
QScriptExtensionPluginscriptCase Sensitive
QSqlDriverPluginsqldriversCase Sensitive
QStylePluginstylesCase Insensitive
QTextCodecPlugincodecsCase Sensitive

But where is the plugins directory? When the application is run, Qt will first treat the application's executable directory as the pluginsbase. For example if the application is in C:\Program Files\MyApp and has a style plugin, Qt will look in C:\Program Files\MyApp\styles. (See QCoreApplication::applicationDirPath() for how to find out where the application's executable is.) Qt will also look in the directory specified by QLibraryInfo::location(QLibraryInfo::PluginsPath), which typically is located in QTDIR/plugins (where QTDIR is the directory where Qt is installed). If you want Qt to look in additional places you can add as many paths as you need with calls to QCoreApplication::addLibraryPath(). And if you want to set your own path or paths you can use QCoreApplication::setLibraryPaths(). You can also use a qt.conf file to override the hard-coded paths that are compiled into the Qt library. For more information, see the Using qt.conf documentation. Yet another possibility is to set the QT_PLUGIN_PATH environment variable before running the application. If set, Qt will look for plugins in the paths (separated by the system path separator) specified in the variable.

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):

 class MyStylePlugin : public QStylePlugin
 {
 public:
     QStringList keys() const;
     QStyle *create(const QString &key);
 };

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

 #include "mystyleplugin.h"

 QStringList MyStylePlugin::keys() const
 {
     return QStringList() << "MyStyle";
 }

 QStyle *MyStylePlugin::create(const QString &key)
 {
     if (key.toLower() == "mystyle")
         return new MyStyle;
     return 0;
 }

 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:

 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.

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.

The default 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.

The normal way to include a plugin with an application is either to compile it in with the application or to compile it into a dynamic library and use it like any other library. 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. For more information about deployment, see the Deploying Qt Applications documentation.

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 an suitable .pro file.

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

 class FilterInterface
 {
 public:
     virtual ~FilterInterface() {}

     virtual QStringList filters() const = 0;
     virtual QImage filterImage(const QString &filter, const QImage &image,
                                QWidget *parent) = 0;
 };

 Q_DECLARE_INTERFACE(FilterInterface,
                     "com.trolltech.PlugAndPaint.FilterInterface/1.0")

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

 #include <QObject>
 #include <QStringList>
 #include <QImage>

 #include <plugandpaint/interfaces.h>

 class ExtraFiltersPlugin : public QObject, public FilterInterface
 {
     Q_OBJECT
     Q_INTERFACES(FilterInterface)

 public:
     QStringList filters() const;
     QImage filterImage(const QString &filter, const QImage &image,
                        QWidget *parent);
 };

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.

Loading and Verifying Plugins Dynamically

When loading plugins, the Qt library does some sanity checking to determine whether or not the plugin can be loaded and used. This provides the ability to have multiple versions and configurations of the Qt library installed side by side.

  • Plugins linked with a Qt library that has a higher version number will not be loaded by a library with a lower version number.

    Example: Qt 4.3.0 will not load a plugin built with Qt 4.3.1.

  • Plugins linked with a Qt library that has a lower major version number will not be loaded by a library with a higher major version number.

    Example: Qt 4.3.1 will not load a plugin built with Qt 3.3.1.
    Example: Qt 4.3.1 will load plugins built with Qt 4.3.0 and Qt 4.2.3.

  • The Qt library and all plugins are built using a build key. The build key in the Qt library is examined against the build key in the plugin, and if they match, the plugin is loaded. If the build keys do not match, then the Qt library refuses to load the plugin.

    Rationale: See the The Build Key section below.

When building plugins to extend an application, it is important to ensure that the plugin is configured in the same way as the application. This means that if the application was built in release mode, plugins should be built in release mode, too.

If you configure Qt to be built in both debug and release modes, but only build applications in release mode, you need to ensure that your plugins are also built in release mode. By default, if a debug build of Qt is available, plugins will only be built in debug mode. To force the plugins to be built in release mode, add the following line to the plugin's project file:

 CONFIG += release

This will ensure that the plugin is compatible with the version of the library used in the application.

The Build Key

When loading plugins, Qt checks the build key of each plugin against its own configuration to ensure that only compatible plugins are loaded; any plugins that are configured differently are not loaded.

The build key contains the following information:

  • Architecture, operating system and compiler.

    Rationale: In cases where different versions of the same compiler do not produce binary compatible code, the version of the compiler is also present in the build key.

  • Configuration of the Qt library. The configuration is a list of the missing features that affect the available API in the library.

    Rationale: Two different configurations of the same version of the Qt library are not binary compatible. The Qt library that loads the plugin uses the list of (missing) features to determine if the plugin is binary compatible.

    Note: There are cases where a plugin can use features that are available in two different configurations. However, the developer writing plugins would need to know which features are in use, both in their plugin and internally by the utility classes in Qt. The Qt library would require complex feature and dependency queries and verification when loading plugins. Requiring this would place an unnecessary burden on the developer, and increase the overhead of loading a plugin. To reduce both development time and application runtime costs, a simple string comparision of the build keys is used.

  • Optionally, an extra string may be specified on the configure script command line.

    Rationale: When distributing binaries of the Qt library with an application, this provides a way for developers to write plugins that can only be loaded by the library with which the plugins were linked.

For debugging purposes, it is possible to override the run-time build key checks by setting the QT_NO_PLUGIN_CHECK environment variable to a non-zero value in the environment from which your application is launched.

Static Plugins

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.

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 (Qtopia)Default style
qdecorationwindowsDecorations (Qtopia)Windows style
qgifImage formatsGIF
qjpegImage formatsJPEG
qmngImage formatsMNG
qimsw_multiInput methods (Qtopia)Input Method Switcher
qwstslibmousehandlerMouse drivers (Qtopia)tslib mouse
qgfxtransformedGraphic drivers (Qtopia)Transformed screen
qgfxvncGraphic drivers (Qtopia)VNC
qscreenvfbGraphic drivers (Qtopia)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:

 #include <QApplication>
 #include <QtPlugin>

 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qgif)
 Q_IMPORT_PLUGIN(qkrcodecs)

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     ...
     return app.exec();
 }

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

 QTPLUGIN     += qjpeg \
                 qgif \
                 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.

The Plugin Cache

In order to speed up loading and validation of plugins, some of the information that is collected when plugins are loaded is cached through QSettings. This includes information about whether or not a plugin was successfully loaded, so that subsequent load operations don't try to load an invalid plugin. However, if the "last modified" timestamp of a plugin has changed, the plugin's cache entry is invalidated and the plugin is reloaded regardless of the values in the cache entry, and the cache entry itself is updated with the new result.

This also means that the timestamp must be updated each time the plugin or any dependent resources (such as a shared library) is updated, since the dependent resources might influence the result of loading a plugin.

Sometimes, when developing plugins, it is necessary to remove entries from the plugin cache. Since Qt uses QSettings to manage the plugin cache, the locations of plugins are platform-dependent; see the QSettings documentation for more information about each platform.

For example, on Windows the entries are stored in the registry, and the paths for each plugin will typically begin with either of these two strings:

 HKEY_CURRENT_USER\Software\Trolltech\OrganizationDefaults\Qt Plugin Cache 4.2.debug
 HKEY_CURRENT_USER\Software\Trolltech\OrganizationDefaults\Qt Plugin Cache 4.2.false

Debugging Plugins

There are a number of issues that may prevent correctly-written plugins from working with the applications that are designed to use them. Many of these are related to differences in the way that plugins and applications have been built, often arising from separate build systems and processes.

The following table contains descriptions of the common causes of problems developers experience when creating plugins:

ProblemCauseSolution
Plugins sliently fail to load even when opened directly by the application. Qt Designer shows the plugin libraries in its Help|About Plugins dialog, but no plugins are listed under each of them.The application and its plugins are built in different modes.Either share the same build information or build the plugins in both debug and release modes by appending the debug_and_release to the CONFIG variable in each of their project files.
A valid plugin that replaces an invalid (or broken) plugin fails to load.The entry for the plugin in the plugin cache indicates that the original plugin could not be loaded, causing Qt to ignore the replacement.Either ensure that the plugin's timestamp is updated, or delete the entry in the plugin cache.

You can also use the QT_DEBUG_PLUGINS environment variable to obtain diagnostic information from Qt about each plugin it tries to load. Set this variable to a non-zero value in the environment from which your application is launched.

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

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 64
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le blog Digia au hasard

Logo

Créer des applications avec un style Metro avec Qt, exemples en QML et C++, un article de Digia Qt traduit par Thibaut Cuvelier

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.3
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web