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 Basic Tools 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 Basic Tools Example</h1>
23
<li><a href="tools-plugandpaintplugins-basictools-basictoolsplugin-cpp.html">tools/plugandpaintplugins/basictools/basictoolsplugin.cpp</a></li>
24
<li><a href="tools-plugandpaintplugins-basictools-basictoolsplugin-h.html">tools/plugandpaintplugins/basictools/basictoolsplugin.h</a></li>
26
<p>The Basic Tools example is a plugin for the <a href="tools-plugandpaint.html">Plug & Paint</a> example. It provides a set of basic brushes, shapes, and filters. Through the Basic Tools example, we will review the four steps involved in writing a Qt plugin:</p>
28
<li>Declare a plugin class.</li>
29
<li>Implement the interfaces provided by the plugin.</li>
30
<li>Export the plugin using the <tt>Q_EXPORT_PLUGIN()</tt> macro.</li>
31
<li>Build the plugin using an adequate <tt>.pro</tt> file.</li>
33
<a name="declaration-of-the-plugin-class"></a>
34
<h2>Declaration of the Plugin Class</h2>
35
<pre> #include <plugandpaint/interfaces.h>
37
class BasicToolsPlugin : public QObject,
38
public BrushInterface,
39
public ShapeInterface,
40
public FilterInterface
43
Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)</pre>
44
<p>We start by including <tt>interfaces.h</tt>, which defines the plugin interfaces for the <a href="tools-plugandpaint.html">Plug & Paint</a> application. For the <tt>#include</tt> to work, we need to add a <tt>INCLUDEPATH</tt> entry to the <tt>.pro</tt> file with the path to Qt's <tt>examples/tools</tt> directory.</p>
45
<p>The <tt>BasicToolsPlugin</tt> class is a <a href="qobject.html">QObject</a> subclass that implements the <tt>BrushInterface</tt>, the <tt>ShapeInterface</tt>, and the <tt>FilterInterface</tt>. This is done through multiple inheritance. The <tt>Q_INTERFACES()</tt> macro is necessary to tell <a href="moc.html#moc">moc</a>, Qt's meta-object compiler, that the base classes are plugin interfaces. Without the <tt>Q_INTERFACES()</tt> macro, we couldn't use <a href="qobject.html#qobject_cast">qobject_cast</a>() in the <a href="tools-plugandpaint.html">Plug & Paint</a> application to detect interfaces.</p>
48
QStringList brushes() const;
49
QRect mousePress(const QString &brush, QPainter &painter,
50
const QPoint &pos);
51
QRect mouseMove(const QString &brush, QPainter &painter,
52
const QPoint &oldPos, const QPoint &newPos);
53
QRect mouseRelease(const QString &brush, QPainter &painter,
54
const QPoint &pos);
57
QStringList shapes() const;
58
QPainterPath generateShape(const QString &shape, QWidget *parent);
61
QStringList filters() const;
62
QImage filterImage(const QString &filter, const QImage &image,
65
<p>In the <tt>public</tt> section of the class, we declare all the functions from the three interfaces.</p>
66
<a name="implementation-of-the-brush-interface"></a>
67
<h2>Implementation of the Brush Interface</h2>
68
<p>Let's now review the implementation of the <tt>BasicToolsPlugin</tt> member functions inherited from <tt>BrushInterface</tt>.</p>
69
<pre> QStringList BasicToolsPlugin::brushes() const
71
return QStringList() << tr("Pencil") << tr("Air Brush")
72
<< tr("Random Letters");
74
<p>The <tt>brushes()</tt> function returns a list of brushes provided by this plugin. We provide three brushes: <b>Pencil</b>, <b>Air Brush</b>, and <b>Random Letters</b>.</p>
75
<pre> QRect BasicToolsPlugin::mousePress(const QString &brush, QPainter &painter,
76
const QPoint &pos)
78
return mouseMove(brush, painter, pos, pos);
80
<p>On a mouse press event, we just call <tt>mouseMove()</tt> to draw the spot where the event occurred.</p>
81
<pre> QRect BasicToolsPlugin::mouseMove(const QString &brush, QPainter &painter,
82
const QPoint &oldPos, const QPoint &newPos)
86
int rad = painter.pen().width() / 2;
87
QRect boundingRect = QRect(oldPos, newPos).normalized()
88
.adjusted(-rad, -rad, +rad, +rad);
89
QColor color = painter.pen().color();
90
int thickness = painter.pen().width();
91
QColor transparentColor(color.red(), color.green(), color.blue(), 0);</pre>
92
<p>In <tt>mouseMove()</tt>, we start by saving the state of the <a href="qpainter.html">QPainter</a> and we compute a few variables that we'll need later.</p>
93
<pre> if (brush == tr("Pencil")) {
94
painter.drawLine(oldPos, newPos);
95
} else if (brush == tr("Air Brush")) {
96
int numSteps = 2 + (newPos - oldPos).manhattanLength() / 2;
98
painter.setBrush(QBrush(color, Qt::Dense6Pattern));
99
painter.setPen(Qt::NoPen);
101
for (int i = 0; i < numSteps; ++i) {
102
int x = oldPos.x() + i * (newPos.x() - oldPos.x()) / (numSteps - 1);
103
int y = oldPos.y() + i * (newPos.y() - oldPos.y()) / (numSteps - 1);
105
painter.drawEllipse(x - (thickness / 2), y - (thickness / 2),
106
thickness, thickness);
108
} else if (brush == tr("Random Letters")) {
109
QChar ch('A' + (rand() % 26));
111
QFont biggerFont = painter.font();
112
biggerFont.setBold(true);
113
biggerFont.setPointSize(biggerFont.pointSize() + thickness);
114
painter.setFont(biggerFont);
116
painter.drawText(newPos, QString(ch));
118
QFontMetrics metrics(painter.font());
119
boundingRect = metrics.boundingRect(ch);
120
boundingRect.translate(newPos);
121
boundingRect.adjust(-10, -10, +10, +10);
126
<p>Then comes the brush-dependent part of the code:</p>
128
<li>If the brush is <b>Pencil</b>, we just call <a href="qpainter.html#drawLine">QPainter::drawLine</a>() with the current <a href="qpen.html">QPen</a>.</li>
129
<li>If the brush is <b>Air Brush</b>, we start by setting the painter's <a href="qbrush.html">QBrush</a> to <a href="qt.html#BrushStyle-enum">Qt::Dense6Pattern</a> to obtain a dotted pattern. Then we draw a circle filled with that <a href="qbrush.html">QBrush</a> several times, resulting in a thick line.</li>
130
<li>If the brush is <b>Random Letters</b>, we draw a random letter at the new cursor position. Most of the code is for setting the font to be bold and larger than the default font and for computing an appropriate bounding rect.</li>
132
<p>At the end, we restore the painter state to what it was upon entering the function and we return the bounding rectangle.</p>
133
<pre> QRect BasicToolsPlugin::mouseRelease(const QString & /* brush */,
134
QPainter & /* painter */,
135
const QPoint & /* pos */)
137
return QRect(0, 0, 0, 0);
139
<p>When the user releases the mouse, we do nothing and return an empty <a href="qrect.html">QRect</a>.</p>
140
<a name="implementation-of-the-shape-interface"></a>
141
<h2>Implementation of the Shape Interface</h2>
142
<pre> QStringList BasicToolsPlugin::shapes() const
144
return QStringList() << tr("Circle") << tr("Star") << tr("Text...");
146
<p>The plugin provides three shapes: <b>Circle</b>, <b>Star</b>, and <b>Text...</b>. The three dots after <b>Text</b> are there because the shape pops up a dialog asking for more information. We know that the shape names will end up in a menu, so we include the three dots in the shape name.</p>
147
<p>A cleaner but more complicated design would have been to distinguish between the internal shape name and the name used in the user interface.</p>
148
<pre> QPainterPath BasicToolsPlugin::generateShape(const QString &shape,
153
if (shape == tr("Circle")) {
154
path.addEllipse(0, 0, 50, 50);
155
} else if (shape == tr("Star")) {
157
for (int i = 1; i < 5; ++i) {
158
path.lineTo(50 + 40 * cos(0.8 * i * Pi),
159
50 + 40 * sin(0.8 * i * Pi));
162
} else if (shape == tr("Text...")) {
163
QString text = QInputDialog::getText(parent, tr("Text Shape"),
164
tr("Enter text:"),
165
QLineEdit::Normal, tr("Qt"));
166
if (!text.isEmpty()) {
167
QFont timesFont("Times", 50);
168
timesFont.setStyleStrategy(QFont::ForceOutline);
169
path.addText(0, 0, timesFont, text);
175
<p>The <tt>generateShape()</tt> creates a <a href="qpainterpath.html">QPainterPath</a> for the specified shape. If the shape is <b>Text</b>, we pop up a <a href="qinputdialog.html">QInputDialog</a> to let the user enter a text.</p>
176
<a name="implementation-of-the-filter-interface"></a>
177
<h2>Implementation of the Filter Interface</h2>
178
<pre> QStringList BasicToolsPlugin::filters() const
180
return QStringList() << tr("Invert Pixels") << tr("Swap RGB")
181
<< tr("Grayscale");
183
<p>The plugin provides three filters: <b>Invert Pixels</b>, <b>Swap RGB</b>, and <b>Grayscale</b>.</p>
184
<pre> QImage BasicToolsPlugin::filterImage(const QString &filter, const QImage &image,
185
QWidget * /* parent */)
187
QImage result = image.convertToFormat(QImage::Format_RGB32);
189
if (filter == tr("Invert Pixels")) {
190
result.invertPixels();
191
} else if (filter == tr("Swap RGB")) {
192
result = result.rgbSwapped();
193
} else if (filter == tr("Grayscale")) {
194
for (int y = 0; y < result.height(); ++y) {
195
for (int x = 0; x < result.width(); ++x) {
196
int pixel = result.pixel(x, y);
197
int gray = qGray(pixel);
198
int alpha = qAlpha(pixel);
199
result.setPixel(x, y, qRgba(gray, gray, gray, alpha));
205
<p>The <tt>filterImage()</tt> function takes a filter name and a <a href="qimage.html">QImage</a> as parameters and returns an altered <a href="qimage.html">QImage</a>. The first thing we do is to convert the image to a 32-bit RGB format, to ensure that the algorithms will work as expected. For example, <a href="qimage.html#invertPixels">QImage::invertPixels</a>(), which is used to implement the <b>Invert Pixels</b> filter, gives counterintuitive results for 8-bit images, because they invert the indices into the color table instead of inverting the color table's entries.</p>
206
<a name="exporting-the-plugin"></a>
207
<h2>Exporting the Plugin</h2>
208
<p>Whereas applications have a <tt>main()</tt> function as their entry point, plugins need to contain exactly one occurrence of the <tt>Q_EXPORT_PLUGIN()</tt> macro to specify which class provides the plugin:</p>
209
<pre> Q_EXPORT_PLUGIN(BasicToolsPlugin)</pre>
210
<p>This line may appear in any <tt>.cpp</tt> file that is part of the plugin's source code.</p>
211
<a name="the-pro-file"></a>
212
<h2>The .pro File</h2>
213
<p>Here's the project file for building the Basic Tools plugin:</p>
214
<pre> TEMPLATE = lib
217
HEADERS = basictoolsplugin.h
218
SOURCES = basictoolsplugin.cpp
219
TARGET = pnp_basictools
220
DESTDIR = ../../plugandpaint/plugins
222
contains(TEMPLATE,lib) {
223
CONFIG(debug, debug|release) {
224
unix:TARGET = $$member(TARGET, 0)_debug
225
else:TARGET = $$member(TARGET, 0)d
230
target.path = $$[QT_INSTALL_EXAMPLES]/tools/plugandpaint/plugins
231
sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS basictools.pro
232
sources.path = $$[QT_INSTALL_EXAMPLES]/tools/plugandpaintplugins/basictools
233
INSTALLS += target sources</pre>
234
<p>The <tt>.pro</tt> file differs from typical <tt>.pro</tt> files in many respects. First, it starts with a <tt>TEMPLATE</tt> entry specifying <tt>lib</tt>. (The default template is <tt>app</tt>.) It also adds <tt>plugin</tt> to the <tt>CONFIG</tt> variable. This is necessary on some platforms to avoid generating symbolic links with version numbers in the file name, which is appropriate for most dynamic libraries but not for plugins.</p>
235
<p>The <tt>INCLUDEPATH</tt> variable sets the search paths for global headers (i.e., header files included using <tt>#include <...></tt>). We add Qt's <tt>examples/tools</tt> directory (strictly speaking, <tt>examples/tools/plugandpaintplugins/basictools/../..</tt>) to the list, so that we can include <tt><plugandpaint/interfaces.h></tt>.</p>
236
<p>The <tt>TARGET</tt> variable specifies which name we want to give the target library. We use <tt>pnp_</tt> as the prefix to show that the plugin is designed to work with Plug & Paint. On Unix, <tt>lib</tt> is also prepended to that name. On all platforms, a platform-specific suffix is appended (e.g., <tt>.dll</tt> on Windows).</p>
237
<p>Finally, the <tt>DESTDIR</tt> variable specifies where we want to install the plugin. We put it in Plug & Paint's <tt>plugins</tt> subdirectory, since that's where the application looks for plugins.</p>
238
<p /><address><hr /><div align="center">
239
<table width="100%" cellspacing="0" border="0"><tr class="address">
240
<td width="30%">Copyright © 2005 <a href="trolltech.html">Trolltech</a></td>
241
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
242
<td width="30%" align="right"><div align="right">Qt 4.0.0</div></td>
243
</tr></table></div></address></body>