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  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

Qt Plugins HOWTO

Qt provides a simple plugin interface which makes it easy to create custom database drivers, image formats, text codecs, styles and widgets as stand-alone components. (1)

Writing a plugin is achieved by subclassing the appropriate plugin base clase, implementing a few functions, and adding a macro.

There are five plugin base classes. Derived plugins are stored by default in the standard plugin directory.

Base Class Default Path
QImageFormatPlugin pluginsbase/imageformats *
QSqlDriverPlugin pluginsbase/sqldrivers *
QStylePlugin pluginsbase/styles *
QTextCodecPlugin pluginsbase/codecs *
QWidgetPlugin pluginsbase/designer *

But where is the pluginsbase 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 QApplication::applicationDirPath() for how to find out where the application's executable is.) Qt will also look in the directory given by qInstallPathPlugins(). If you want Qt to look in additional places you can add as many paths as you need with calls to QApplication::addLibraryPath(). And if you want to set your own path or paths you can use QApplication::setLibraryPaths().

Suppose that you have a new style class called 'MyStyle' that you want to make available as a plugin. The required code is straightforward:

    class MyStylePlugin : public QStylePlugin
    {
    public:
        MyStylePlugin() {}
        ~MyStylePlugin() {}

        QStringList keys() const { 
            return QStringList() << "mystyle"; 
        }

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

    Q_EXPORT_PLUGIN( MyStylePlugin )

(Note that QStyleFactory is case-insensitive, and the lower case version of the key is used; other factories, e.g. QWidgetFactory, are case sensitive.)

The constructor and destructor do not need to do anything, so are left empty. There are only two virtual functions that must be implemented. The first is keys() which returns a string list of the classes implemented in the plugin. (We've just implemented one class in the example above.) The second is a function that returns an object of the required class (or 0 if the plugin is asked to create an object of a class that it doesn't implement). For QStylePlugin, this second function is called create().

It is possible to implement any number of plugin subclasses in a single plugin, providing they are all derived from the same base class, e.g. QStylePlugin.

For database drivers, image formats, custom widgets and text codecs, 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 Qt Designer manual's, 'Creating Custom Widgets' section in the 'Creating Custom Widgets' chapter, for a complete example of a QWidgetPlugin, which implements extra functions to integrate the plugin into Qt Designer. The QWidgetFactory class provides additional information on QWidgetPlugins.

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*, 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 QApplication::addLibraryPath() with this path and your plugins will be available to the application. Note that the final part of the path, i.e. styles, widgets, etc., 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 DLL (or so or other platform specific library type) 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, e.g. appdir/plugins/designer, and place the plugin in that directory.

For Qt Designer, you may need to call QApplication::addLibraryPath("QTDIR/plugins/designer") to load your Qt Designer plugins.

* All references to QTDIR refer to the path where Qt was installed.

Loading and Verifying Plugins

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 major and/or minor version number will not be loaded by a library with a lower major and/or minor version number.

    Rationale:

    A plugin linked against a newer Qt library may use new features that are not available in older versions. Trolltech has a policy of adding new features and APIs only between minor releases, which is why this test only looks at the major and minor version numbers, and not at the patchlevel version number.

  • Plugins linked against a Qt library with thread support can only be loaded by libraries that are built with thread support.

    Rationale:

    The threaded and non-threaded Qt libraries have different names. A library with thread support that loads a plugin linked against a Qt library without thread support will cause two versions of the same library to be in memory at the same time. On UNIX systems, this causes the non-threaded Qt library to be loaded. When this happens, the constructors for all static objects in the Qt library will be called a second time, but they will operate on the objects already in memory. There is no way to work around this, as this is a feature of the object binary format: the static symbols already defined by the threaded Qt library cannot be replaced or copied when the non-threaded Qt library is loaded.

  • Plugins linked against a Qt library without thread support can only be loaded by libraries that are built without thread support.

    Rationale:

    See the Rationale above.

  • Starting with Qt 3.0.5, both 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 Rationale for the build key below.

The Build Key

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.

Plugins and Threaded Applications

If you want to build a plugin which you want to use with a threaded Qt library (whether or not the plugin itself uses threads) you must use a threaded environment. Specifically, you must link the plugin with a threaded Qt library, and you must build Qt Designer with that library. Your .pro file for your plugin must include the line:

    CONFIG += thread

Warning: Do not mix the normal Qt library and the threaded Qt library in an application. If your application uses the threaded Qt library, you should not link your plugin with the normal Qt library. Nor should you dynamically load the normal Qt library or dynamically load another library, e.g. a plugin, that depends on the normal Qt library. On some systems, mixing threaded and non-threaded libraries or plugins will corrupt the static data used in the Qt library.


  1. Qt 3.0.5 introduces changes into some aspects of plugins, in particular regarding loading, path handling and library versions. As a result of this change, no plugins compiled with Qt 3.0.4 and earlier will work with Qt 3.0.5 and later: they must be recompiled. Back...

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 59
  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 Qt Labs au hasard

Logo

Construire l'avenir : (ré-)introduction aux composants de Qt Quick

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. 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 3.2
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