Chapter 21. Creating Plugins

Creating Plugins

Dynamic libraries (also called shared libraries or DLLs) are independent modules that are stored in a separate file on disk and can be accessed by multiple applications. Programs usually specify which dynamic libraries they need at link time, in which case the libraries are automatically loaded when the application starts. This approach usually involves adding the library and possibly its include path to the application’s .pro file and including the relevant headers in the source files. For example:

LIBS        += -ldb_cxx
INCLUDEPATH += /usr/local/BerkeleyDB.4.2/include

The alternative is to dynamically load the library when it is required, and then resolve the symbols that we want to use from it. Qt provides the QLibrary class to achieve this in a platform-independent manner. Given the stem of a library’s name, QLibrary searches the platform’s standard locations for the library, looking for an appropriate file. For example, given the name mimetype, it will look for mimetype.dll on Windows, mimetype.so on Linux, and mimetype.dylib on Mac OS X.

Modern GUI applications can often be extended by the use of plugins. A plugin is a dynamic library that implements a particular interface to provide optional extra functionality. For example, in Chapter 5, we created a plugin to integrate a custom widget with Qt Designer (p. 117).

Qt recognizes its own set of plugin interfaces for various domains, including image formats, database drivers, widget styles, text encodings, and accessibility. This chapter’s first section explains how to extend Qt with Qt plugins.

It is also possible to create application-specific plugins for particular Qt applications. Qt makes writing such plugins easy through its plugin framework, which adds crash safety and convenience to QLibrary. In the last two sections of this chapter, we show how to make an application support plugins and how to create a custom plugin for an application.

Extending Qt with Plugins

Qt can be extended with a variety of plugin types, the most common being database drivers, image formats, styles, and text codecs. For each type of plugin, we normally need at least two classes: a plugin wrapper class that implements the generic plugin API functions, and one or more handler classes that each implement the API for a particular type of plugin. The handlers are accessed through the wrapper class. These classes are shown in Figure 21.1.

Table 21.1. Qt plugin and handler classes

Plugin Class

Handler Base Class

QAccessibleBridgePlugin

QAccessibleBridge

QAccessiblePlugin

QAccessibleInterface

QDecorationPlugin[*]

QDecoration[*]

QFontEnginePlugin

QAbstractFontEngine

QIconEnginePluginV2

QIconEngineV2

QImageIOPlugin

QImageIOHandler

QInputContextPlugin

QInputContext

QKbdDriverPlugin[*]

QWSKeyboardHandler[*]

QMouseDriverPlugin[*]

QWSMouseHandler[*]

QPictureFormatPlugin

N/A

QScreenDriverPlugin[*]

QScreen[*]

QScriptExtensionPlugin

N/A

QSqlDriverPlugin

QSqlDriver

QStylePlugin

QStyle

QTextCodecPlugin

QTextCodec

[*] Available only in Qt/Embedded Linux.

To demonstrate how to extend Qt with plugins, we will implement two plugins in this section. The first is a very simple QStyle plugin for the Bronze style we developed in Chapter 19. The second is a plugin that can read monochrome Windows cursor files.

Creating a QStyle plugin is very easy, provided we have already developed the style itself. All we need are three files: a .pro file that is rather different from the ones we have seen before, and small .h and .cpp files to provide a QStylePlugin subclass that acts as a wrapper for the style. We will begin with the .h file:

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

All plugins at least provide a keys() function and a create() function. The keys() function returns a list of the objects that the plugin can create. For style plugins, the keys are case-insensitive, so “mystyle” and “MyStyle” are treated the same. The create() function returns an object given a key; the key must be the same as one of those in the list returned by keys().

The .cpp file is almost as small and simple as the .h file.

QStringList BronzeStylePlugin::keys() const
{
    return QStringList() << "Bronze";
}

The keys() function returns a list of styles provided by the plugin. Here, we offer only one style, called “Bronze”.

QStyle *BronzeStylePlugin::create(const QString &key)
{
    if (key.toLower() == "bronze")
        return new BronzeStyle;
    return 0;
}

If the key is “Bronze” (regardless of case), we create a BronzeStyle object and return it.

At the end of the .cpp file, we must add the following macro to export the style properly:

Q_EXPORT_PLUGIN2(bronzestyleplugin, BronzeStylePlugin)

The first argument to Q_EXPORT_PLUGIN2() is the base name of the target library, excluding any extension, prefix, or version number. By default, qmake uses the name of the current directory as the base name; this can be overriden using the TARGET entry in the .pro file. The second argument to Q_EXPORT_PLUGIN2() is the plugin’s class name.

The .pro file is different for plugins than for applications, so we will finish by looking at the Bronze style’s .pro file:

TEMPLATE      = lib
CONFIG       += plugin
HEADERS       = ../bronze/bronzestyle.h 
                bronzestyleplugin.h
SOURCES       = ../bronze/bronzestyle.cpp 
                bronzestyleplugin.cpp
RESOURCES     = ../bronze/bronze.qrc
DESTDIR       = $$[QT_INSTALL_PLUGINS]/styles

By default, .pro files use the app template, but here we must specify the lib template because a plugin is a library, not a stand-alone application. The CONFIG line is used to tell Qt that the library is not just a plain library, but a plugin library. The DESTDIR specifies the directory where the plugin should go. All Qt plugins must go in the appropriate plugins subdirectory where Qt was installed; this path is built into qmake and available from the $$[QT_INSTALL_PLUGINS] variable. Since our plugin provides a new style, we put it in Qt’s plugins/styles directory. The list of directory names and plugin types is available at http://doc.trolltech.com/4.3/plugins-howto.html.

Plugins built for Qt in release mode and debug mode are different, so if both versions of Qt are installed, it is wise to specify which one to use in the .pro file—for example, by adding the line

CONFIG += release

Once the Bronze style plugin is built, it is ready for use. Applications can use the style by specifying it in code. For example:

QApplication::setStyle("Bronze");

We can also use the style without changing the application’s source code at all, simply by running the application with the -style option. For example:

./spreadsheet -style bronze

When Qt Designer is run, it automatically looks for plugins. If it finds a style plugin, it will offer the option to preview using the style in its Form|Preview in submenu.

Applications that use Qt plugins must be deployed with the plugins they are intended to use. Qt plugins must be placed in specific subdirectories (e.g., plugins/styles for custom styles). Qt applications search for plugins in the plugins directory in the directory where the application’s executable resides. If we want to deploy Qt plugins in a different directory, the plugins search path can be augmented by calling QCoreApplication::addLibraryPath() at startup or by setting the QT_PLUGIN_PATH environment variable before launching the application.

Now that we have seen a very simple plugin, we will tackle one that is a bit more challenging: an image format plugin for Windows cursor (.cur) files. (The format is shown in Figure 21.2.) Windows cursor files can hold several images of the same cursor at different sizes. Once the cursor plugin is built and installed, Qt will be able to read .cur files and access individual cursors (e.g., through QImage, QImageReader, or QMovie), and will be able to write the cursors out in any of Qt’s other image file formats, such as BMP, JPEG, and PNG.

The .cur file format

Figure 21.2. The .cur file format

New image format plugin wrappers must subclass QImageIOPlugin and reimplement a few virtual functions:

class CursorPlugin : public QImageIOPlugin
{
public:
    QStringList keys() const;
    Capabilities capabilities(QIODevice *device,
                              const QByteArray &format) const;
    QImageIOHandler *create(QIODevice *device,
                            const QByteArray &format) const;
};

The keys() function returns a list of the image formats the plugin supports. The format parameter of the capabilities() and create() functions can be assumed to have a value from that list.

QStringList CursorPlugin::keys() const
{
    return QStringList() << "cur";
}

Our plugin supports only one image format, so it returns a list with just one name. Ideally, the name should be the file extension used by the format. When dealing with formats with several extensions (such as .jpg and .jpeg for JPEG), we can return a list with several entries for the same format, one for each extension.

QImageIOPlugin::Capabilities
CursorPlugin::capabilities(QIODevice *device,
                           const QByteArray &format) const
{
    if (format == "cur")
        return CanRead;

    if (format.isEmpty()) {
        CursorHandler handler;
        handler.setDevice(device);
        if (handler.canRead())
            return CanRead;
    }

    return 0;
}

The capabilities() function returns what the image handler is capable of doing with the given image format. There are three capabilities (CanRead, CanWrite, and CanReadIncremental), and the return value is a bitwise OR of those that apply.

If the format is “cur”, our implementation returns CanRead. If no format is given, we create a cursor handler and check whether it is capable of reading the data from the given device. The canRead() function only peeks at the data, seeing whether it recognizes the file, without changing the file pointer. A capability of 0 means that the file cannot be read or written by this handler.

QImageIOHandler *CursorPlugin::create(QIODevice *device,
                                      const QByteArray &format) const
{
    CursorHandler *handler = new CursorHandler;
    handler->setDevice(device);
    handler->setFormat(format);
    return handler;
}

When a cursor file is opened (e.g., by QImageReader), the plugin wrapper’s create() function will be called with the device pointer and with “cur” as the format. We create a CursorHandler instance and set it up with the specified device and format. The caller takes ownership of the handler and will delete it when it is no longer required. If multiple files are to be read, a fresh handler will be created for each one.

Q_EXPORT_PLUGIN2(cursorplugin, CursorPlugin)

At the end of the .cpp file, we use the Q_EXPORT_PLUGIN2() macro to ensure that Qt recognizes the plugin. The first parameter is an arbitrary name that we want to give to the plugin. The second parameter is the plugin class name.

Subclassing QImageIOPlugin is straightforward. The real work of the plugin is done in the handler. Image format handlers must subclass QImageIOHandler and reimplement some or all of its public functions. Let’s start with the header:

class CursorHandler : public QImageIOHandler
{
public:
    CursorHandler();

    bool canRead() const;
    bool read(QImage *image);
    bool jumpToNextImage();
    int currentImageNumber() const;
    int imageCount() const;

private:
    enum State { BeforeHeader, BeforeImage, AfterLastImage, Error };

    void readHeaderIfNecessary() const;
    QBitArray readBitmap(int width, int height, QDataStream &in) const;
    void enterErrorState() const;

    mutable State state;
    mutable int currentImageNo;
    mutable int numImages;
};

The signatures of all the public functions are fixed. We have omitted several functions that we don’t need to reimplement for a read-only handler, in particular write(). The member variables are declared with the mutable keyword because they are modified inside const functions.

CursorHandler::CursorHandler()
{
    state = BeforeHeader;
    currentImageNo = 0;
    numImages = 0;
}

When the handler is constructed, we begin by setting its state. We set the current cursor image number to the first cursor, but since we set numImages to 0 it is clear that we have no images yet.

bool CursorHandler::canRead() const
{
    if (state == BeforeHeader) {
        return device()->peek(4) == QByteArray("2", 4);
    } else {
        return state != Error;
    }
}

The canRead() function can be called at any time to determine whether the image handler can read more data from the device. If the function is called before we have read any data, while we are still in the BeforeHeader state, we check for the particular signature that identifies Windows cursor files. The QIODevice::peek() call reads the first four bytes without changing the device’s file pointer. If canRead() is called later on, we return true unless an error has occurred.

int CursorHandler::currentImageNumber() const
{
    return currentImageNo;
}

This trivial function returns the number of the cursor at which the device file pointer is positioned.

Once the handler is constructed, it is possible for the user to call any of its public functions, in any order. This is a potential problem since we must assume that we can only read serially, so we need to read the file header once before doing anything else. We solve the problem by calling the readHeaderIfNecessary() function in those functions that depend on the header having been read.

int CursorHandler::imageCount() const
{
    readHeaderIfNecessary();
    return numImages;
}

This function returns the number of images in the file. For a valid file where no reading errors have occurred, it will return a count of at least 1.

The next function is quite involved, so we will review it in pieces:

bool CursorHandler::read(QImage *image)
{
    readHeaderIfNecessary();

    if (state != BeforeImage)
        return false;

The read() function reads the data for whichever image begins at the current device pointer position. If the file’s header is read successfully, or after an image has been read and the device pointer is at the start of another image, we can read the next image.

    quint32 size;
    quint32 width;
    quint32 height;
    quint16 numPlanes;
    quint16 bitsPerPixel;
    quint32 compression;

    QDataStream in(device());
    in.setByteOrder(QDataStream::LittleEndian);
    in >> size;
    if (size != 40) {
        enterErrorState();
        return false;
    }
    in >> width >> height >> numPlanes >> bitsPerPixel >> compression;
    height /= 2;

    if (numPlanes != 1 || bitsPerPixel != 1 || compression != 0) {
        enterErrorState();
        return false;
    }

    in.skipRawData((size - 20) + 8);

We create a QDataStream to read the device. We must set the byte order to match that specified by the .cur file format specification. There is no need to set a QDataStream version number since the format of integers and floating-point numbers does not vary between data stream versions. Next, we read in various items of cursor header data, and we skip the irrelevant parts of the header and the 8-byte color table using QDataStream::skipRawData().

We must account for all the format’s idiosyncrasies—for example, halving the height because the .cur format gives a height that is twice as high as the actual image’s height. The bitsPerPixel and compression values are always 1 and 0 in a monochrome .cur file. If we have any problems, we call enterErrorState() and return false.

    QBitArray xorBitmap = readBitmap(width, height, in);
    QBitArray andBitmap = readBitmap(width, height, in);

    if (in.status() != QDataStream::Ok) {
        enterErrorState();
        return false;
    }

The next items in the file are two bitmaps, one an XOR mask and the other an AND mask. We read these into QBitArrays rather than into QBitmaps. A QBitmap is a class designed to be drawn on and painted on-screen, but what we need here is a plain array of bits.

When we are done with reading the file, we check the QDataStream’s status. This works because if a QDataStream enters an error state, it stays in that state and can only return zeros. For example, if reading fails on the first bit array, the attempt to read the second will result in an empty QBitArray.

    *image = QImage(width, height, QImage::Format_ARGB32);

    for (int i = 0; i < int(height); ++i) {
        for (int j = 0; j < int(width); ++j) {
            QRgb color;
            int bit = (i * width) + j;

            if (andBitmap.testBit(bit)) {
                if (xorBitmap.testBit(bit)) {
                    color = 0x7F7F7F7F;
                } else {
                    color = 0x00FFFFFF;
                }
            } else {
                if (xorBitmap.testBit(bit)) {
                    color = 0xFFFFFFFF;
                } else {
                    color = 0xFF000000;
                }
            }
            image->setPixel(j, i, color);
        }
    }

We construct a new QImage of the correct size and assign it to *image. Then we iterate over every pixel in the XOR and AND bit arrays and convert them into 32-bit ARGB color specifications. The AND and XOR bit arrays are used as shown in the following table to obtain the color of each cursor pixel:

AND

XOR

Result

1

1

Inverted background pixel

1

0

Transparent pixel

0

1

White pixel

0

0

Black pixel

Black, white, and transparent pixels are no problem, but there is no way to obtain an inverted background pixel using an ARGB color specification without knowing the color of the original background pixel. As a substitute, we use a semi-transparent gray color (0x7F7F7F7F).

    ++currentImageNo;
    if (currentImageNo == numImages)
        state = AfterLastImage;
    return true;
}

Once we have finished reading the image, we update the current image number and update the state if we have reached the last image. At that point, the device will be positioned at the next image or at the end of the file.

bool CursorHandler::jumpToNextImage()
{
    QImage image;
    return read(&image);
}

The jumpToNextImage() function is used to skip an image. For simplicity, we simply call read() and ignore the resulting QImage. A more efficient implementation would use the information stored in the .cur file header to skip directly to the appropriate offset in the file.

void CursorHandler::readHeaderIfNecessary() const
{
    if (state != BeforeHeader)
        return;

    quint16 reserved;
    quint16 type;
    quint16 count;

    QDataStream in(device());
    in.setByteOrder(QDataStream::LittleEndian);

    in >> reserved >> type >> count;
    in.skipRawData(16 * count);

    if (in.status() != QDataStream::Ok || reserved != 0
            || type != 2 || count == 0) {
        enterErrorState();
        return;
    }
        state = BeforeImage;
        currentImageNo = 0;
        numImages = int(count);
    }

The readHeaderIfNecessary() private function is called from imageCount() and read(). If the file’s header has already been read, the state is not BeforeHeader and we return immediately. Otherwise, we open a data stream on the device, read in some generic data (including the number of cursors in the file), and set the state to BeforeImage. At the end, the device’s file pointer is positioned before the first image.

void CursorHandler::enterErrorState() const
{
    state = Error;
    currentImageNo = 0;
    numImages = 0;
}

If an error occurs, we assume that there are no valid images and set the state to Error. Once in the Error state, the handler’s state cannot change.

QBitArray CursorHandler::readBitmap(int width, int height,
                                    QDataStream &in) const
{
    QBitArray bitmap(width * height);
    quint32 word = 0;
    quint8 byte;

    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j) {
            if ((j % 32) == 0) {
                word = 0;
                for (int k = 0; k < 4; ++k) {
                    in >> byte;
                    word = (word << 8) | byte;
                }
            }

            bitmap.setBit(((height - i - 1) * width) + j,
                          word & 0x80000000);
            word <<= 1;
        }
    }
    return bitmap;
}

The readBitmap() function is used to read a cursor’s AND and XOR masks. These masks have two unusual features. First, they store the rows from bottom to top, instead of the more common top-to-bottom approach. Second, the endianness of the data appears to be reversed from that used everywhere else in .cur files. In view of this, we must invert the y-coordinate in the setBit() call, and we read in the mask values one byte at a time, bit-shifting and masking to extract their correct values.

To build the plugin, we must use a .pro file that is very similar to the one we used for the Bronze style plugin shown earlier (p. 493):

TEMPLATE      = lib
CONFIG       += plugin
HEADERS       = cursorhandler.h 
                cursorplugin.h
SOURCES       = cursorhandler.cpp 
                cursorplugin.cpp
DESTDIR       = $$[QT_INSTALL_PLUGINS]/imageformats

This completes the Windows cursor plugin. Plugins for other image formats would follow the same pattern, although some might implement more of the QImageIOHandler API, in particular the functions used for writing images. Plugins of other kinds follow the pattern of having a plugin wrapper that exports one or several handlers that provide the underlying functionality.

Making Applications Plugin-Aware

An application plugin is a dynamic library that implements one or more interfaces. An interface is a class that consists exclusively of pure virtual functions. The communication between the application and the plugins is done through the interface’s virtual table. In this section, we will focus on how to use a plugin in a Qt application through its interfaces, and in the next section we will show how to implement a plugin.

To provide a concrete example, we will create the simple Text Art application shown in Figure 21.3. The text effects are provided by plugins; the application retrieves the list of text effects provided by each plugin and iterates over them to show each one as an item in a QListWidget.

The Text Art application

Figure 21.3. The Text Art application

The Text Art application defines one interface:

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

    virtual QStringList effects() const = 0;
    virtual QPixmap applyEffect(const QString &effect,
                                const QString &text,
                                const QFont &font, const QSize &size,
                                const QPen &pen,
                                const QBrush &brush) = 0;
};

Q_DECLARE_INTERFACE(TextArtInterface,
                    "com.software-inc.TextArt.TextArtInterface/1.0")

An interface class normally declares a virtual destructor, a virtual function that returns a QStringList, and one or more other virtual functions. The destructor is there primarily to silence the compiler, which might otherwise complain about the lack of a virtual destructor in a class that has virtual functions. In this example, the effects() function returns a list of the text effects the plugin can provide. We can think of this list as a list of keys. Every time we call one of the other functions, we pass one of these keys as first argument, making it possible to implement multiple effects in one plugin.

At the end, we use the Q_DECLARE_INTERFACE() macro to associate an identifier to the interface. The identifier normally has four components: an inverted domain name specifying the creator of the interface, the name of the application, the name of the interface, and a version number. Whenever we alter the interface (e.g., by adding a virtual function or changing the signature of an existing function), we must remember to increase the version number; otherwise, the application might crash trying to access an outdated plugin.

The application is implemented in a class called TextArtDialog. We will show only the code that is relevant to making it plugin-aware. Let’s start with the constructor:

TextArtDialog::TextArtDialog(const QString &text, QWidget *parent)
    : QDialog(parent)
{
    listWidget = new QListWidget;
    listWidget->setViewMode(QListWidget::IconMode);
    listWidget->setMovement(QListWidget::Static);
    listWidget->setIconSize(QSize(260, 80));
    ...
    loadPlugins();
    populateListWidget(text);
    ...
}

The constructor creates a QListWidget to list the available effects. It calls the private function loadPlugins() to find and load any plugins that implement the TextArtInterface and populates the list widget accordingly by calling another private function, populateListWidget().

void TextArtDialog::loadPlugins()
{
    QDir pluginsDir = directoryOf("plugins");
    foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
        QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
        if (TextArtInterface *interface =
                    qobject_cast<TextArtInterface *>(loader.instance()))
            interfaces.append(interface);
    }
}

In loadPlugins(), we start by retrieving the application’s plugins directory. Then we attempt to load all the files in the plugins directory. The directoryOf() function is the same as the one we first used in Chapter 17 (p. 410).

If the file we try to load is a Qt plugin that uses the same version of Qt as the application, QPluginLoader::instance() will return a QObject * that points to a Qt plugin. We use qobject_cast<T>() to check whether the plugin implements the TextArtInterface. Each time the cast is successful, we add the interface to the TextArtDialog’s list of interfaces (of type QList<TextArtInterface *>).

Some applications may want to load two or more different interfaces. In such cases, the code for obtaining the interfaces would look more like this:

QObject *plugin = loader.instance();
if (TextArtInterface *i = qobject_cast<TextArtInterface *>(plugin))
    textArtInterfaces.append(i);
if (BorderArtInterface *i = qobject_cast<BorderArtInterface *>(plugin))
    borderArtInterfaces.append(i);
if (TextureInterface *i = qobject_cast<TextureInterface *>(plugin))
    textureInterfaces.append(i);

The same plugin may successfully cast to more than one interface pointer if it uses multiple inheritance.

void TextArtDialog::populateListWidget(const QString &text)
{
    QFont font("Helvetica", iconSize.height(), QFont::Bold);
    QSize iconSize = listWidget->iconSize();
    QPen pen(QColor("darkseagreen"));

    QLinearGradient gradient(0, 0, iconSize.width() / 2,
                             iconSize.height() / 2);
    gradient.setColorAt(0.0, QColor("darkolivegreen"));
    gradient.setColorAt(0.8, QColor("darkgreen"));
    gradient.setColorAt(1.0, QColor("lightgreen"));

    foreach (TextArtInterface *interface, interfaces) {
        foreach (QString effect, interface->effects()) {
            QListWidgetItem *item = new QListWidgetItem(effect,
                                                        listWidget);
            QPixmap pixmap = interface->applyEffect(effect, text, font,
                                                       iconSize, pen,
                                                       gradient);
            item->setData(Qt::DecorationRole, pixmap);
        }
    }
    listWidget->setCurrentRow(0);
}

The populateListWidget() function begins by creating some variables to pass to the applyEffect() function, in particular a font, a pen, and a linear gradient. It then iterates over every TextArtInterface that was found by loadPlugins(). For each effect provided by each interface, a new QListWidgetItem is created with its text set to the name of the effect, and with a QPixmap created using applyEffect().

In this section, we have seen how to load plugins by calling loadPlugins() in the constructor, and how to make use of them in populateListWidget(). The code copes gracefully whether there are no plugins providing TextArtInterfaces, just one, or more than one. Furthermore, additional plugins could be added later: Every time the application starts up, it loads whatever plugins it finds that provide the interfaces it wants. This makes it easy to extend the application’s functionality without changing the application itself.

Writing Application Plugins

An application plugin is a subclass of QObject and of the interfaces it wants to provide. The examples that accompany this book includes two plugins for the Text Art application presented in the preceding section, to show that the application correctly handles multiple plugins.

Here, we will review the code for only one of them, the Basic Effects plugin. We will assume that the plugin’s source code is located in a directory called basiceffectsplugin and that the Text Art application is located in a parallel directory called textart. Here’s the declaration of the plugin class:

class BasicEffectsPlugin : public QObject, public TextArtInterface
{
    Q_OBJECT
    Q_INTERFACES(TextArtInterface)

public:
    QStringList effects() const;
    QPixmap applyEffect(const QString &effect, const QString &text,
                        const QFont &font, const QSize &size,
                        const QPen &pen, const QBrush &brush);
};

The plugin implements only one interface, TextArtInterface. In addition to Q_OBJECT, we must use the Q_INTERFACES() macro for each interface that is subclassed to ensure smooth cooperation between moc and qobject_cast<T>().

QStringList BasicEffectsPlugin::effects() const
{
    return QStringList() << "Plain" << "Outline" << "Shadow";
}

The effects() function returns a list of text effects supported by the plugin. This plugin supports three effects, so we just return a list containing the name of each one.

The applyEffect() function provides the plugin’s functionality and is slightly involved, so we will review it in pieces.

QPixmap BasicEffectsPlugin::applyEffect(const QString &effect,
        const QString &text, const QFont &font, const QSize &size,
        const QPen &pen, const QBrush &brush)
{
    QFont myFont = font;
    QFontMetrics metrics(myFont);
    while ((metrics.width(text) > size.width()
            || metrics.height() > size.height())
           && myFont.pointSize() > 9) {
        myFont.setPointSize(myFont.pointSize() - 1);
        metrics = QFontMetrics(myFont);
    }

We want to ensure that the given text will fit in the specified size, if possible. For this reason, we use the font’s metrics to see whether the text is too large to fit, and if it is, we enter a loop where we reduce the point size until we find a size that will fit, or until we reach 9 points, our fixed minimum size.

    QPixmap pixmap(size);

    QPainter painter(&pixmap);
    painter.setFont(myFont);
    painter.setPen(pen);
    painter.setBrush(brush);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
    painter.eraseRect(pixmap.rect());

We create a pixmap of the required size and a painter to paint onto the pixmap. We also set some render hints to ensure the smoothest possible results. The call to eraseRect() clears the pixmap with the background color.

    if (effect == "Plain") {
        painter.setPen(Qt::NoPen);
    } else if (effect == "Outline") {
        QPen pen(Qt::black);
        pen.setWidthF(2.5);
        painter.setPen(pen);
    } else if (effect == "Shadow") {
        QPainterPath path;
        painter.setBrush(Qt::darkGray);
        path.addText(((size.width() - metrics.width(text)) / 2) + 3,
                     (size.height() - metrics.descent()) + 3, myFont,
                     text);
        painter.drawPath(path);
        painter.setBrush(brush);
    }

For the “Plain” effect, no outline is required. For the “Outline” effect, we ignore the original pen and create our own black pen with a 2.5-pixel width. For the “Shadow” effect, we need to draw the shadow first so that the text can be painted on top of it.

    QPainterPath path;
    path.addText((size.width() - metrics.width(text)) / 2,
                 size.height() - metrics.descent(), myFont, text);
    painter.drawPath(path);

    return pixmap;
}

We now have the pen and brushes set appropriately for each text effect, and in the “Shadow” effect case we have drawn the shadow. We are now ready to render the text. The text is horizontally centered and drawn far enough above the bottom of the pixmap to allow room for descenders.

Q_EXPORT_PLUGIN2(basiceffectsplugin, BasicEffectsPlugin)

At the end of the .cpp file, we use the Q_EXPORT_PLUGIN2() macro to make the plugin available to Qt.

The .pro file is similar to the one we used for the Bronze style plugin earlier in this chapter (p. 493):

TEMPLATE      = lib
CONFIG       += plugin
HEADERS       = ../textart/textartinterface.h 
                basiceffectsplugin.h
SOURCES       = basiceffectsplugin.cpp
DESTDIR       = ../textart/plugins

If this chapter has whetted your appetite for application plugins, you might like to study the more advanced Plug & Paint example provided with Qt. The application supports three different interfaces and includes a useful Plugin Information dialog that lists the plugins and interfaces that are available to the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset