1
<?xml version="1.0" encoding="iso-8859-1"?>
3
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
4
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5
<!-- /tmp/qt-4.0.0-espenr-1119621036935/qt-x11-opensource-desktop-4.0.0/doc/src/examples/plugandpaint.qdoc -->
7
<title>Qt 4.0: Plug & Paint Example</title>
8
<style>h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
9
a:link { color: #004faf; text-decoration: none }
10
a:visited { color: #672967; text-decoration: none }
11
td.postheader { font-family: sans-serif }
12
tr.address { font-family: sans-serif }
13
body { background: #ffffff; color: black; }</style>
16
<table border="0" cellpadding="0" cellspacing="0" width="100%">
18
<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></td>
19
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="annotated.html"><font color="#004faf">Annotated</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
20
<td align="right" valign="top" width="230"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></td></tr></table><h1 align="center">Plug & Paint Example</h1>
23
<li><a href="tools-plugandpaint-interfaces-h.html">tools/plugandpaint/interfaces.h</a></li>
24
<li><a href="tools-plugandpaint-mainwindow-cpp.html">tools/plugandpaint/mainwindow.cpp</a></li>
25
<li><a href="tools-plugandpaint-mainwindow-h.html">tools/plugandpaint/mainwindow.h</a></li>
26
<li><a href="tools-plugandpaint-paintarea-cpp.html">tools/plugandpaint/paintarea.cpp</a></li>
27
<li><a href="tools-plugandpaint-paintarea-h.html">tools/plugandpaint/paintarea.h</a></li>
28
<li><a href="tools-plugandpaint-plugindialog-cpp.html">tools/plugandpaint/plugindialog.cpp</a></li>
29
<li><a href="tools-plugandpaint-plugindialog-h.html">tools/plugandpaint/plugindialog.h</a></li>
30
<li><a href="tools-plugandpaint-main-cpp.html">tools/plugandpaint/main.cpp</a></li>
32
<p>The Plug & Paint example demonstrates how to write Qt applications that can be extended through plugins.</p>
33
<center><img src="images/plugandpaint.png" alt="Screenshot of the Plug & Paint example" /></center><p>A plugin is a dynamic library that can be loaded at run-time to extend an application. Qt makes it possible to create custom plugins and to load them using <a href="qpluginloader.html">QPluginLoader</a>. The Plug & Paint example uses plugins to support custom brushes, shapes, and image filters. A single plugin can provide multiple brushes, shapes, and/or filters.</p>
34
<p>If you want to learn how to make your own application extensible through plugins, we recommend that you start by reading this overview, which explains how to make an application use plugins. Afterward, you can read the <a href="tools-plugandpaintplugins-basictools.html">Basic Tools</a> and <a href="tools-plugandpaintplugins-extrafilters.html">Extra Filters</a> overviews, which show how to implement plugins.</p>
35
<p>Plug & Paint consists of the following classes:</p>
37
<li><tt>MainWindow</tt> is a <a href="qmainwindow.html">QMainWindow</a> subclass that provides the menu system and that contains a <tt>PaintArea</tt> as the central widget.</li>
38
<li><tt>PaintArea</tt> is a <a href="qwidget.html">QWidget</a> that allows the user to draw using a brush and to insert shapes.</li>
39
<li><tt>PluginDialog</tt> is a dialog that shows information about the plugins detected by the application.</li>
40
<li><tt>BrushInterface</tt>, <tt>ShapeInterface</tt>, and <tt>FilterInterface</tt> are abstract base classes that can be implemented by plugins to provide custom brushes, shapes, and image filters.</li>
42
<a name="the-plugin-interfaces"></a>
43
<h2>The Plugin Interfaces</h2>
44
<p>We will start by reviewing the interfaces defined in <tt>interfaces.h</tt>. These interfaces are used by the Plug & Paint application to access extra functionality. They are implemented in the plugins.</p>
45
<pre> class BrushInterface
48
virtual ~BrushInterface() {}
50
virtual QStringList brushes() const = 0;
51
virtual QRect mousePress(const QString &brush, QPainter &painter,
52
const QPoint &pos) = 0;
53
virtual QRect mouseMove(const QString &brush, QPainter &painter,
54
const QPoint &oldPos, const QPoint &newPos) = 0;
55
virtual QRect mouseRelease(const QString &brush, QPainter &painter,
56
const QPoint &pos) = 0;
58
<p>The <tt>BrushInterface</tt> class declares four pure virtual functions. The first pure virtual function, <tt>brushes()</tt>, returns a list of strings that identify the brushes provided by the plugin. By returning a <a href="qstringlist.html">QStringList</a> instead of a <a href="qstring.html">QString</a>, we make it possible for a single plugin to provide multiple brushes. The other functions have a <tt>brush</tt> parameter to identify which brush (among those returned by <tt>brushes()</tt>) is used.</p>
59
<p><tt>mousePress()</tt>, <tt>mouseMove()</tt>, and <tt>mouseRelease()</tt> take a <a href="qpainter.html">QPainter</a> and one or two <a href="qpoint.html">QPoint</a>s, and return a <a href="qrect.html">QRect</a> identifying which portion of the image was altered by the brush.</p>
60
<p>The class also has a virtual destructor. Interface classes usually don't need such a destructor (because it would make little sense to <tt>delete</tt> the object that implements the interface through a pointer to the interface), but some compilers emit a warning for classes that declare virtual functions but no virtual destructor. We provide the destructor to keep these compilers happy.</p>
61
<pre> class ShapeInterface
64
virtual ~ShapeInterface() {}
66
virtual QStringList shapes() const = 0;
67
virtual QPainterPath generateShape(const QString &shape,
70
<p>The <tt>ShapeInterface</tt> class declares a <tt>shapes()</tt> function that works the same as <tt>BrushInterface</tt>'s <tt>brushes()</tt> function, and a <tt>generateShape()</tt> function that has a <tt>shape</tt> parameter. Shapes are represented by a <a href="qpainterpath.html">QPainterPath</a>, a data type that can represent arbitrary 2D shapes or combination of shapes. The <tt>parent</tt> parameter can be used by the plugin to pop up a dialog asking the user to specify more information.</p>
71
<pre> class FilterInterface
74
virtual ~FilterInterface() {}
76
virtual QStringList filters() const = 0;
77
virtual QImage filterImage(const QString &filter, const QImage &image,
80
<p>The <tt>FilterInterface</tt> class declares a <tt>filters()</tt> function that returns a list of filter names, and a <tt>filterImage()</tt> function that applies a filter to an image.</p>
81
<pre> Q_DECLARE_INTERFACE(BrushInterface,
82
"com.trolltech.PlugAndPaint.BrushInterface/1.0")
83
Q_DECLARE_INTERFACE(ShapeInterface,
84
"com.trolltech.PlugAndPaint.ShapeInterface/1.0")
85
Q_DECLARE_INTERFACE(FilterInterface,</pre>
86
<p>To make it possible to query at run-time whether a plugin implements a given interface, we must use the <tt>Q_DECLARE_INTERFACE()</tt> macro. The first argument is the name of the interface. The second argument is a string identifying the interface in a unique way. By convention, we use a "Java package name" syntax to identify interfaces. If we later change the interfaces, we must use a different string to identify the new interface; otherwise, the application might crash. It is therefore a good idea to include a version number in the string, as we did above.</p>
87
<p>The <a href="tools-plugandpaintplugins-basictools.html">Basic Tools</a> plugin and the <a href="tools-plugandpaintplugins-extrafilters.html">Extra Filters</a> plugin shows how to derive from <tt>BrushInterface</tt>, <tt>ShapeInterface</tt>, and <tt>FilterInterface</tt>.</p>
88
<p>A note on naming: It might have been tempting to give the <tt>brushes()</tt>, <tt>shapes()</tt>, and <tt>filters()</tt> functions a more generic name, such as <tt>keys()</tt> or <tt>features()</tt>. However, that would have made multiple inheritance impracticable. When creating interfaces, we should always try to give unique names to the pure virtual functions.</p>
89
<a name="the-mainwindow-class"></a>
90
<h2>The MainWindow Class</h2>
91
<p>The <tt>MainWindow</tt> class is a standard <a href="qmainwindow.html">QMainWindow</a> subclass, as found in many of the other examples (notably <a href="mainwindows-application.html">Application</a>). Here, we'll concentrate on the parts of the code that are related to plugins.</p>
92
<pre> void MainWindow::loadPlugins()
94
pluginsDir = QDir(qApp->applicationDirPath());
96
if (pluginsDir.dirName() == "debug" || pluginsDir.dirName() == "release")
98
#elif defined(Q_OS_MAC)
99
if (pluginsDir.dirName() == "MacOS") {
105
pluginsDir.cd("plugins");</pre>
106
<p>The <tt>loadPlugins()</tt> function is called from the <tt>MainWindow</tt> constructor to detect plugins and update the <b>Brush</b>, <b>Shapes</b>, and <b>Filters</b> menus. We start by initializing the <tt>pluginsDir</tt> member variable to refer to the <tt>plugins</tt> directory of the Plug & Paint example. On Unix, this is just a matter of initializing the <a href="qdir.html">QDir</a> variable with <a href="qcoreapplication.html#applicationDirPath">QApplication::applicationDirPath</a>(), the path of the executable file, and to do a <a href="qdir.html#cd">cd()</a>. On Windows and Mac OS X, this file is usually located in a subdirectory, so we need to take this into account.</p>
107
<pre> foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
108
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
109
QObject *plugin = loader.instance();
111
BrushInterface *iBrush = qobject_cast<BrushInterface *>(plugin);
113
addToMenu(plugin, iBrush->brushes(), brushMenu,
114
SLOT(changeBrush()), brushActionGroup);
116
ShapeInterface *iShape = qobject_cast<ShapeInterface *>(plugin);
118
addToMenu(plugin, iShape->shapes(), shapesMenu,
119
SLOT(insertShape()));
121
FilterInterface *iFilter = qobject_cast<FilterInterface *>(plugin);
123
addToMenu(plugin, iFilter->filters(), filterMenu,
124
SLOT(applyFilter()));
126
pluginFileNames += fileName;
129
<p>We use <a href="qdir.html#entryList">QDir::entryList</a>() to get a list of all files in that directory. Then we iterate over the result using <a href="containers.html#foreach">foreach</a> and try to load the plugin using <a href="qpluginloader.html">QPluginLoader</a>.</p>
130
<p>To the application that loads the plugin, a Qt plugin is simply a <a href="qobject.html">QObject</a>. That <a href="qobject.html">QObject</a> may implement extra interfaces using multiple inheritance. The object is accessible through <a href="qpluginloader.html#instance">QPluginLoader::instance</a>(). If the dynamic library isn't a Qt plugin, or if it was compiled against an incompatible version of the Qt library, <a href="qpluginloader.html#instance">QPluginLoader::instance</a>() returns a null pointer.</p>
131
<p>If <a href="qpluginloader.html#instance">QPluginLoader::instance</a>() is non-null, we check which interfaces it implements using <a href="qobject.html#qobject_cast">qobject_cast</a>(). First, we try to cast the plugin instance to a <tt>BrushInterface</tt>; if it works, we call the private function <tt>addToMenu()</tt> with the list of brushes returned by <tt>brushes()</tt>. Then we do the same with the <tt>ShapeInterface</tt> and the <tt>FilterInterface</tt>.</p>
132
<pre> brushMenu->setEnabled(!brushActionGroup->actions().isEmpty());
133
shapesMenu->setEnabled(!shapesMenu->actions().isEmpty());
134
filterMenu->setEnabled(!filterMenu->actions().isEmpty());
136
<p>At the end, we enable or disable the <b>Brush</b>, <b>Shapes</b>, and <b>Filters</b> menus based on whether they contain any items.</p>
137
<pre> void MainWindow::aboutPlugins()
139
PluginDialog dialog(pluginsDir.path(), pluginFileNames, this);
142
<p>The <tt>aboutPlugins()</tt> slot is called on startup and can be invoked at any time through the <b>About Plugins</b> action. It pops up a <tt>PluginDialog</tt>, providing information about the loaded plugins.</p>
143
<center><img src="images/plugandpaint-plugindialog.png" alt="Screenshot of the Plugin dialog" /></center><p>The <tt>addToMenu()</tt> function is called from <tt>loadPlugin()</tt> to create <a href="qaction.html">QAction</a>s for custom brushes, shapes, or filters and add them to the relevant menu. The <a href="qaction.html">QAction</a> is created with the plugin from which it comes from as the parent; this is a trick to get access to the plugin later.</p>
144
<pre> void MainWindow::changeBrush()
146
QAction *action = qobject_cast<QAction *>(sender());
147
BrushInterface *iBrush = qobject_cast<BrushInterface *>(action->parent());
148
QString brush = action->text();
150
paintArea->setBrush(iBrush, brush);
152
<p>The <tt>changeBrush()</tt> slot is invoked when the user chooses one of the brushes from the <b>Brush</b> menu. We start by finding out which action invoked the slot using <a href="qobject.html#sender">QObject::sender</a>(). Then we get the <tt>BrushInterface</tt> out of the plugin (which we conveniently passed as the <a href="qaction.html">QAction</a>'s parent) and we call <tt>PaintArea::setBrush()</tt> with the <tt>BrushInterface</tt> and the string identifying the brush. Next time the user draws on the paint area, <tt>PaintArea</tt> will use this brush.</p>
153
<pre> void MainWindow::insertShape()
155
QAction *action = qobject_cast<QAction *>(sender());
156
ShapeInterface *iShape = qobject_cast<ShapeInterface *>(action->parent());
158
QPainterPath path = iShape->generateShape(action->text(), this);
160
paintArea->insertShape(path);
162
<p>The <tt>insertShape()</tt> is invoked when the use chooses one of the shapes from the <b>Shapes</b> menu. We retrieve the <a href="qaction.html">QAction</a> that invoked the slot, then the <tt>ShapeInterface</tt> associated with that <a href="qaction.html">QAction</a>, and finally we call <tt>ShapeInterface::generateShape()</tt> to obtain a <a href="qpainterpath.html">QPainterPath</a>.</p>
163
<pre> void MainWindow::applyFilter()
165
QAction *action = qobject_cast<QAction *>(sender());
166
FilterInterface *iFilter =
167
qobject_cast<FilterInterface *>(action->parent());
169
QImage image = iFilter->filterImage(action->text(), paintArea->image(),
171
paintArea->setImage(image);
173
<p>The <tt>applyFilter()</tt> slot is similar: We retrieve the <a href="qaction.html">QAction</a> that invoked the slot, then the <tt>FilterInterface</tt> associated to that <a href="qaction.html">QAction</a>, and finally we call <tt>FilterInterface::filterImage()</tt> to apply the filter onto the current image.</p>
174
<a name="the-paintarea-class"></a>
175
<h2>The PaintArea Class</h2>
176
<p>The <tt>PaintArea</tt> class contains some code that deals with <tt>BrushInterface</tt>, so we'll review it briefly.</p>
177
<pre> void PaintArea::setBrush(BrushInterface *brushInterface, const QString &brush)
179
this->brushInterface = brushInterface;
180
this->brush = brush;
182
<p>In <tt>setBrush()</tt>, we simply store the <tt>BrushInterface</tt> and the brush that are given to us by <tt>MainWindow</tt>.</p>
183
<pre> void PaintArea::mouseMoveEvent(QMouseEvent *event)
185
if ((event->buttons() & Qt::LeftButton) && lastPos != QPoint(-1, -1)) {
186
if (brushInterface) {
187
QPainter painter(&theImage);
188
setupPainter(painter);
189
QRect rect = brushInterface->mouseMove(brush, painter, lastPos,
194
lastPos = event->pos();
197
<p>In the <a href="qwidget.html#mouseMoveEvent">mouse move event handler</a>, we call the <tt>BrushInterface::mouseMove()</tt> function on the current <tt>BrushInterface</tt>, with the current brush. The mouse press and mouse release handlers are very similar.</p>
198
<a name="the-plugindialog-class"></a>
199
<h2>The PluginDialog Class</h2>
200
<p>The <tt>PluginDialog</tt> class provides information about the loaded plugins to the user. Its constructor takes a path to the plugins and a list of plugin file names. It calls <tt>populateTreeWidget()</tt> to fill the QTreeWdiget with information about the plugins:</p>
201
<pre> void PluginDialog::populateTreeWidget(const QString &path,
202
const QStringList &fileNames)
204
if (fileNames.isEmpty()) {
205
label->setText(tr("Plug & Paint couldn't find any plugins in the %1 "
206
"directory.")
207
.arg(QDir::convertSeparators(path)));
208
treeWidget->hide();
210
label->setText(tr("Plug & Paint found the following plugins in the %1 "
211
"directory:")
212
.arg(QDir::convertSeparators(path)));
216
foreach (QString fileName, fileNames) {
217
QPluginLoader loader(dir.absoluteFilePath(fileName));
218
QObject *plugin = loader.instance();
220
QTreeWidgetItem *pluginItem = new QTreeWidgetItem(treeWidget);
221
pluginItem->setText(0, fileName);
222
treeWidget->setItemExpanded(pluginItem, true);
224
QFont boldFont = pluginItem->font(0);
225
boldFont.setBold(true);
226
pluginItem->setFont(0, boldFont);
229
BrushInterface *iBrush = qobject_cast<BrushInterface *>(plugin);
231
addItems(pluginItem, "BrushInterface", iBrush->brushes());
233
ShapeInterface *iShape = qobject_cast<ShapeInterface *>(plugin);
235
addItems(pluginItem, "ShapeInterface", iShape->shapes());
237
FilterInterface *iFilter =
238
qobject_cast<FilterInterface *>(plugin);
240
addItems(pluginItem, "FilterInterface", iFilter->filters());
245
<p>The <tt>populateTreeWidget()</tt> is very similar to <tt>MainWindow::loadPlugins()</tt>. It uses <a href="qpluginloader.html">QPluginLoader</a> to load the plugins and uses <a href="qobject.html#qobject_cast">qobject_cast</a>() to find out which interfaces are implemented by the plugins.</p>
246
<p>This completes our review of the Plug & Paint application. At this point, you might want to take a look at the <a href="tools-plugandpaintplugins-basictools.html">Basic Tools</a> example plugin.</p>
247
<p /><address><hr /><div align="center">
248
<table width="100%" cellspacing="0" border="0"><tr class="address">
249
<td width="30%">Copyright © 2005 <a href="trolltech.html">Trolltech</a></td>
250
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
251
<td width="30%" align="right"><div align="right">Qt 4.0.0</div></td>
252
</tr></table></div></address></body>