From cd621c201ca637385c6e3409d5c84ecec5fb5418 Mon Sep 17 00:00:00 2001 From: Casper van Donderen Date: Fri, 16 Sep 2011 14:14:43 +0200 Subject: Move the module qdoc files from qtdoc and split up doc/src. Change-Id: I7d992889379d78e07a0b7023facebd7421cf6d22 Reviewed-on: http://codereview.qt-project.org/5092 Reviewed-by: Qt Sanity Bot Reviewed-by: Jerome Pasion --- doc/src/core/objectmodel/metaobjects.qdoc | 137 + doc/src/core/objectmodel/object.qdoc | 124 + doc/src/core/objectmodel/objecttrees.qdoc | 102 + doc/src/core/objectmodel/properties.qdoc | 273 ++ doc/src/core/objectmodel/signalsandslots.qdoc | 451 +++ doc/src/core/threads.qdoc | 572 +++ doc/src/dbus/qtdbus.qdoc | 40 + doc/src/files-and-resources/datastreamformat.qdoc | 361 -- doc/src/files-and-resources/resources.qdoc | 214 -- doc/src/gui/coordsys.qdoc | 461 +++ doc/src/gui/paintsystem.qdoc | 560 +++ doc/src/gui/qtgui.qdoc | 12 + doc/src/network-programming/bearermanagement.qdoc | 271 -- doc/src/network-programming/qtnetwork.qdoc | 350 -- doc/src/network-programming/ssl.qdoc | 79 - .../files-and-resources/datastreamformat.qdoc | 361 ++ doc/src/network/files-and-resources/resources.qdoc | 214 ++ .../network-programming/bearermanagement.qdoc | 271 ++ doc/src/network/network-programming/qtnetwork.qdoc | 350 ++ doc/src/network/network-programming/ssl.qdoc | 79 + doc/src/network/qtnetwork.qdoc | 18 + doc/src/objectmodel/metaobjects.qdoc | 137 - doc/src/objectmodel/object.qdoc | 124 - doc/src/objectmodel/objecttrees.qdoc | 102 - doc/src/objectmodel/properties.qdoc | 273 -- doc/src/objectmodel/signalsandslots.qdoc | 451 --- doc/src/painting-and-printing/coordsys.qdoc | 461 --- doc/src/painting-and-printing/paintsystem.qdoc | 560 --- doc/src/painting-and-printing/printing.qdoc | 189 - doc/src/printsupport/printing.qdoc | 189 + doc/src/printsupport/qtprintsupport.qdoc | 19 + doc/src/sql-programming/qsqldatatype-table.qdoc | 570 --- doc/src/sql-programming/sql-driver.qdoc | 828 ---- doc/src/sql-programming/sql-programming.qdoc | 609 --- doc/src/sql/qtsql.qdoc | 18 + .../sql/sql-programming/qsqldatatype-table.qdoc | 570 +++ doc/src/sql/sql-programming/sql-driver.qdoc | 828 ++++ doc/src/sql/sql-programming/sql-programming.qdoc | 609 +++ doc/src/tutorials/addressbook-fr.qdoc | 1036 ----- doc/src/tutorials/addressbook.qdoc | 981 ----- doc/src/tutorials/modelview.qdoc | 897 ----- doc/src/tutorials/threads.qdoc | 572 --- doc/src/tutorials/widgets-tutorial.qdoc | 249 -- doc/src/widgets-and-layouts/focus.qdoc | 186 - doc/src/widgets-and-layouts/gallery-cde.qdoc | 133 - .../widgets-and-layouts/gallery-cleanlooks.qdoc | 138 - doc/src/widgets-and-layouts/gallery-gtk.qdoc | 141 - doc/src/widgets-and-layouts/gallery-macintosh.qdoc | 138 - doc/src/widgets-and-layouts/gallery-motif.qdoc | 138 - doc/src/widgets-and-layouts/gallery-plastique.qdoc | 138 - doc/src/widgets-and-layouts/gallery-windows.qdoc | 138 - .../widgets-and-layouts/gallery-windowsvista.qdoc | 138 - doc/src/widgets-and-layouts/gallery-windowsxp.qdoc | 138 - doc/src/widgets-and-layouts/gallery.qdoc | 84 - doc/src/widgets-and-layouts/layout.qdoc | 396 -- doc/src/widgets-and-layouts/styles.qdoc | 2102 ----------- doc/src/widgets-and-layouts/stylesheet.qdoc | 3963 -------------------- doc/src/widgets-and-layouts/widgets.qdoc | 162 - doc/src/widgets/addressbook-fr.qdoc | 1036 +++++ doc/src/widgets/addressbook.qdoc | 981 +++++ doc/src/widgets/modelview.qdoc | 897 +++++ doc/src/widgets/qtwidgets.qdoc | 18 + doc/src/widgets/widgets-and-layouts/focus.qdoc | 186 + .../widgets/widgets-and-layouts/gallery-cde.qdoc | 133 + .../widgets-and-layouts/gallery-cleanlooks.qdoc | 138 + .../widgets/widgets-and-layouts/gallery-gtk.qdoc | 141 + .../widgets-and-layouts/gallery-macintosh.qdoc | 138 + .../widgets/widgets-and-layouts/gallery-motif.qdoc | 138 + .../widgets-and-layouts/gallery-plastique.qdoc | 138 + .../widgets-and-layouts/gallery-windows.qdoc | 138 + .../widgets-and-layouts/gallery-windowsvista.qdoc | 138 + .../widgets-and-layouts/gallery-windowsxp.qdoc | 138 + doc/src/widgets/widgets-and-layouts/gallery.qdoc | 84 + doc/src/widgets/widgets-and-layouts/layout.qdoc | 396 ++ doc/src/widgets/widgets-and-layouts/styles.qdoc | 2102 +++++++++++ .../widgets/widgets-and-layouts/stylesheet.qdoc | 3963 ++++++++++++++++++++ doc/src/widgets/widgets-and-layouts/widgets.qdoc | 162 + doc/src/widgets/widgets-tutorial.qdoc | 249 ++ doc/src/widgets/windows-and-dialogs/dialogs.qdoc | 60 + .../widgets/windows-and-dialogs/mainwindow.qdoc | 261 ++ doc/src/windows-and-dialogs/dialogs.qdoc | 60 - doc/src/windows-and-dialogs/mainwindow.qdoc | 261 -- doc/src/xml/qtxml.qdoc | 23 + 83 files changed, 17916 insertions(+), 17768 deletions(-) create mode 100644 doc/src/core/objectmodel/metaobjects.qdoc create mode 100644 doc/src/core/objectmodel/object.qdoc create mode 100644 doc/src/core/objectmodel/objecttrees.qdoc create mode 100644 doc/src/core/objectmodel/properties.qdoc create mode 100644 doc/src/core/objectmodel/signalsandslots.qdoc create mode 100644 doc/src/core/threads.qdoc create mode 100644 doc/src/dbus/qtdbus.qdoc delete mode 100644 doc/src/files-and-resources/datastreamformat.qdoc delete mode 100644 doc/src/files-and-resources/resources.qdoc create mode 100644 doc/src/gui/coordsys.qdoc create mode 100644 doc/src/gui/paintsystem.qdoc create mode 100644 doc/src/gui/qtgui.qdoc delete mode 100644 doc/src/network-programming/bearermanagement.qdoc delete mode 100644 doc/src/network-programming/qtnetwork.qdoc delete mode 100644 doc/src/network-programming/ssl.qdoc create mode 100644 doc/src/network/files-and-resources/datastreamformat.qdoc create mode 100644 doc/src/network/files-and-resources/resources.qdoc create mode 100644 doc/src/network/network-programming/bearermanagement.qdoc create mode 100644 doc/src/network/network-programming/qtnetwork.qdoc create mode 100644 doc/src/network/network-programming/ssl.qdoc create mode 100644 doc/src/network/qtnetwork.qdoc delete mode 100644 doc/src/objectmodel/metaobjects.qdoc delete mode 100644 doc/src/objectmodel/object.qdoc delete mode 100644 doc/src/objectmodel/objecttrees.qdoc delete mode 100644 doc/src/objectmodel/properties.qdoc delete mode 100644 doc/src/objectmodel/signalsandslots.qdoc delete mode 100644 doc/src/painting-and-printing/coordsys.qdoc delete mode 100644 doc/src/painting-and-printing/paintsystem.qdoc delete mode 100644 doc/src/painting-and-printing/printing.qdoc create mode 100644 doc/src/printsupport/printing.qdoc create mode 100644 doc/src/printsupport/qtprintsupport.qdoc delete mode 100644 doc/src/sql-programming/qsqldatatype-table.qdoc delete mode 100644 doc/src/sql-programming/sql-driver.qdoc delete mode 100644 doc/src/sql-programming/sql-programming.qdoc create mode 100644 doc/src/sql/qtsql.qdoc create mode 100644 doc/src/sql/sql-programming/qsqldatatype-table.qdoc create mode 100644 doc/src/sql/sql-programming/sql-driver.qdoc create mode 100644 doc/src/sql/sql-programming/sql-programming.qdoc delete mode 100644 doc/src/tutorials/addressbook-fr.qdoc delete mode 100644 doc/src/tutorials/addressbook.qdoc delete mode 100644 doc/src/tutorials/modelview.qdoc delete mode 100644 doc/src/tutorials/threads.qdoc delete mode 100644 doc/src/tutorials/widgets-tutorial.qdoc delete mode 100644 doc/src/widgets-and-layouts/focus.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-cde.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-cleanlooks.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-gtk.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-macintosh.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-motif.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-plastique.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-windows.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-windowsvista.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery-windowsxp.qdoc delete mode 100644 doc/src/widgets-and-layouts/gallery.qdoc delete mode 100644 doc/src/widgets-and-layouts/layout.qdoc delete mode 100644 doc/src/widgets-and-layouts/styles.qdoc delete mode 100644 doc/src/widgets-and-layouts/stylesheet.qdoc delete mode 100644 doc/src/widgets-and-layouts/widgets.qdoc create mode 100644 doc/src/widgets/addressbook-fr.qdoc create mode 100644 doc/src/widgets/addressbook.qdoc create mode 100644 doc/src/widgets/modelview.qdoc create mode 100644 doc/src/widgets/qtwidgets.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/focus.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-cde.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-cleanlooks.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-gtk.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-macintosh.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-motif.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-plastique.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-windows.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-windowsvista.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery-windowsxp.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/gallery.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/layout.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/styles.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/stylesheet.qdoc create mode 100644 doc/src/widgets/widgets-and-layouts/widgets.qdoc create mode 100644 doc/src/widgets/widgets-tutorial.qdoc create mode 100644 doc/src/widgets/windows-and-dialogs/dialogs.qdoc create mode 100644 doc/src/widgets/windows-and-dialogs/mainwindow.qdoc delete mode 100644 doc/src/windows-and-dialogs/dialogs.qdoc delete mode 100644 doc/src/windows-and-dialogs/mainwindow.qdoc create mode 100644 doc/src/xml/qtxml.qdoc (limited to 'doc/src') diff --git a/doc/src/core/objectmodel/metaobjects.qdoc b/doc/src/core/objectmodel/metaobjects.qdoc new file mode 100644 index 0000000000..597210e789 --- /dev/null +++ b/doc/src/core/objectmodel/metaobjects.qdoc @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page metaobjects.html + \title The Meta-Object System + \brief An overview of Qt's meta-object system and introspection capabilities. + + \ingroup qt-basic-concepts + \keyword meta-object + \target Meta-Object System + + Qt's meta-object system provides the signals and slots mechanism for + inter-object communication, run-time type information, and the dynamic + property system. + + The meta-object system is based on three things: + + \list 1 + \o The \l QObject class provides a base class for objects that can + take advantage of the meta-object system. + \o The Q_OBJECT macro inside the private section of the class + declaration is used to enable meta-object features, such as + dynamic properties, signals, and slots. + \o The \l{moc}{Meta-Object Compiler} (\c moc) supplies each + QObject subclass with the necessary code to implement + meta-object features. + \endlist + + The \c moc tool reads a C++ source file. If it finds one or more + class declarations that contain the Q_OBJECT macro, it + produces another C++ source file which contains the meta-object + code for each of those classes. This generated source file is + either \c{#include}'d into the class's source file or, more + usually, compiled and linked with the class's implementation. + + In addition to providing the \l{signals and slots} mechanism for + communication between objects (the main reason for introducing + the system), the meta-object code provides the following + additional features: + + \list + \o QObject::metaObject() returns the associated + \l{QMetaObject}{meta-object} for the class. + \o QMetaObject::className() returns the class name as a + string at run-time, without requiring native run-time type information + (RTTI) support through the C++ compiler. + \o QObject::inherits() function returns whether an object is an + instance of a class that inherits a specified class within the + QObject inheritance tree. + \o QObject::tr() and QObject::trUtf8() translate strings for + \l{Internationalization with Qt}{internationalization}. + \o QObject::setProperty() and QObject::property() + dynamically set and get properties by name. + \o QMetaObject::newInstance() constructs a new instance of the class. + \endlist + + \target qobjectcast + It is also possible to perform dynamic casts using qobject_cast() + on QObject classes. The qobject_cast() function behaves similarly + to the standard C++ \c dynamic_cast(), with the advantages + that it doesn't require RTTI support and it works across dynamic + library boundaries. It attempts to cast its argument to the pointer + type specified in angle-brackets, returning a non-zero pointer if the + object is of the correct type (determined at run-time), or 0 + if the object's type is incompatible. + + For example, let's assume \c MyWidget inherits from QWidget and + is declared with the Q_OBJECT macro: + + \snippet doc/src/snippets/qtcast/qtcast.cpp 0 + + The \c obj variable, of type \c{QObject *}, actually refers to a + \c MyWidget object, so we can cast it appropriately: + + \snippet doc/src/snippets/qtcast/qtcast.cpp 1 + + The cast from QObject to QWidget is successful, because the + object is actually a \c MyWidget, which is a subclass of QWidget. + Since we know that \c obj is a \c MyWidget, we can also cast it to + \c{MyWidget *}: + + \snippet doc/src/snippets/qtcast/qtcast.cpp 2 + + The cast to \c MyWidget is successful because qobject_cast() + makes no distinction between built-in Qt types and custom types. + + \snippet doc/src/snippets/qtcast/qtcast.cpp 3 + \snippet doc/src/snippets/qtcast/qtcast.cpp 4 + + The cast to QLabel, on the other hand, fails. The pointer is then + set to 0. This makes it possible to handle objects of different + types differently at run-time, based on the type: + + \snippet doc/src/snippets/qtcast/qtcast.cpp 5 + \snippet doc/src/snippets/qtcast/qtcast.cpp 6 + + While it is possible to use QObject as a base class without the + Q_OBJECT macro and without meta-object code, neither signals + and slots nor the other features described here will be available + if the Q_OBJECT macro is not used. From the meta-object + system's point of view, a QObject subclass without meta code is + equivalent to its closest ancestor with meta-object code. This + means for example, that QMetaObject::className() will not return + the actual name of your class, but the class name of this + ancestor. + + Therefore, we strongly recommend that all subclasses of QObject + use the Q_OBJECT macro regardless of whether or not they + actually use signals, slots, and properties. + + \sa QMetaObject, {Qt's Property System}, {Signals and Slots} +*/ diff --git a/doc/src/core/objectmodel/object.qdoc b/doc/src/core/objectmodel/object.qdoc new file mode 100644 index 0000000000..d843f834a5 --- /dev/null +++ b/doc/src/core/objectmodel/object.qdoc @@ -0,0 +1,124 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page object.html + \title Object Model + \ingroup qt-basic-concepts + \brief A description of the powerful features made possible by Qt's dynamic object model. + + The standard C++ object model provides very efficient runtime + support for the object paradigm. But its static nature is + inflexibile in certain problem domains. Graphical user interface + programming is a domain that requires both runtime efficiency and + a high level of flexibility. Qt provides this, by combining the + speed of C++ with the flexibility of the Qt Object Model. + + Qt adds these features to C++: + + \list + \o a very powerful mechanism for seamless object + communication called \l{signals and slots} + \o queryable and designable \l{Qt's Property System}{object + properties} + \o powerful \l{The Event System}{events and event filters} + \o contextual \l{i18n}{string translation for internationalization} + \o sophisticated interval driven \l timers that make it possible + to elegantly integrate many tasks in an event-driven GUI + \o hierarchical and queryable \l{Object Trees & Ownership}{object + trees} that organize object ownership in a natural way + \o guarded pointers (QPointer) that are automatically + set to 0 when the referenced object is destroyed, unlike normal C++ + pointers which become dangling pointers when their objects are destroyed + \o a \l{metaobjects.html#qobjectcast}{dynamic cast} that works across + library boundaries. + \endlist + + Many of these Qt features are implemented with standard C++ + techniques, based on inheritance from QObject. Others, like the + object communication mechanism and the dynamic property system, + require the \l{Meta-Object System} provided + by Qt's own \l{moc}{Meta-Object Compiler (moc)}. + + The meta-object system is a C++ extension that makes the language + better suited to true component GUI programming. Although + templates can be used to extend C++, the meta-object system + provides benefits using standard C++ that cannot be achieved with + templates; see \l{Why Doesn't Qt Use Templates for Signals and + Slots?} + + \section1 Important Classes + + These classes form the basis of the Qt Object Model. + + \annotatedlist objectmodel + + \target Identity vs Value + \section1 Qt Objects: Identity vs Value + + Some of the added features listed above for the Qt Object Model, + require that we think of Qt Objects as identities, not values. + Values are copied or assigned; identities are cloned. Cloning + means to create a new identity, not an exact copy of the old + one. For example, twins have different identities. They may look + identical, but they have different names, different locations, and + may have completely different social networks. + + Then cloning an identity is a more complex operation than copying + or assigning a value. We can see what this means in the Qt Object + Model. + + \bold{A Qt Object...} + + \list + + \o might have a unique \l{QObject::objectName()}. If we copy a Qt + Object, what name should we give the copy? + + \o has a location in an \l{Object Trees & Ownership} + {object hierarchy}. If we copy a Qt Object, where should the copy + be located? + + \o can be connected to other Qt Objects to emit signals to them or + to receive signals emitted by them. If we copy a Qt Object, how + should we transfer these connections to the copy? + + \o can have \l{Qt's Property System} {new properties} added to it + at runtime that are not declared in the C++ class. If we copy a Qt + Object, should the copy include the properties that were added to + the original? + + \endlist + + For these reasons, Qt Objects should be treated as identities, not + as values. Identities are cloned, not copied or assigned, and + cloning an identity is a more complex operation than copying or + assigning a value. Therefore, QObject and all subclasses of + QObject (direct or indirect) have their \l{No copy constructor} + {copy constructor and assignment operator} disabled. + + */ diff --git a/doc/src/core/objectmodel/objecttrees.qdoc b/doc/src/core/objectmodel/objecttrees.qdoc new file mode 100644 index 0000000000..46921106b6 --- /dev/null +++ b/doc/src/core/objectmodel/objecttrees.qdoc @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page objecttrees.html + \title Object Trees & Ownership + \ingroup qt-basic-concepts + \brief Information about the parent-child pattern used to describe + object ownership in Qt. + + \section1 Overview + + \link QObject QObjects\endlink organize themselves in object trees. + When you create a QObject with another object as parent, it's added to + the parent's \link QObject::children() children() \endlink list, and + is deleted when the parent is. It turns out that this approach fits + the needs of GUI objects very well. For example, a \l QShortcut + (keyboard shortcut) is a child of the relevant window, so when the + user closes that window, the shorcut is deleted too. + + \l QWidget, the base class of everything that appears on the screen, + extends the parent-child relationship. A child normally also becomes a + child widget, i.e. it is displayed in its parent's coordinate system + and is graphically clipped by its parent's boundaries. For example, + when the application deletes a message box after it has been + closed, the message box's buttons and label are also deleted, just as + we'd want, because the buttons and label are children of the message + box. + + You can also delete child objects yourself, and they will remove + themselves from their parents. For example, when the user removes a + toolbar it may lead to the application deleting one of its \l QToolBar + objects, in which case the tool bar's \l QMainWindow parent would + detect the change and reconfigure its screen space accordingly. + + The debugging functions \l QObject::dumpObjectTree() and \l + QObject::dumpObjectInfo() are often useful when an application looks or + acts strangely. + + \target note on the order of construction/destruction of QObjects + \section1 Construction/Destruction Order of QObjects + + When \l {QObject} {QObjects} are created on the heap (i.e., created + with \e new), a tree can be constructed from them in any order, and + later, the objects in the tree can be destroyed in any order. When any + QObject in the tree is deleted, if the object has a parent, the + destructor automatically removes the object from its parent. If the + object has children, the destructor automatically deletes each + child. No QObject is deleted twice, regardless of the order of + destruction. + + When \l {QObject} {QObjects} are created on the stack, the same + behavior applies. Normally, the order of destruction still doesn't + present a problem. Consider the following snippet: + + \snippet doc/src/snippets/code/doc_src_objecttrees.cpp 0 + + The parent, \c window, and the child, \c quit, are both \l {QObject} + {QObjects} because QPushButton inherits QWidget, and QWidget inherits + QObject. This code is correct: the destructor of \c quit is \e not + called twice because the C++ language standard \e {(ISO/IEC 14882:2003)} + specifies that destructors of local objects are called in the reverse + order of their constructors. Therefore, the destructor of + the child, \c quit, is called first, and it removes itself from its + parent, \c window, before the destructor of \c window is called. + + But now consider what happens if we swap the order of construction, as + shown in this second snippet: + + \snippet doc/src/snippets/code/doc_src_objecttrees.cpp 1 + + In this case, the order of destruction causes a problem. The parent's + destructor is called first because it was created last. It then calls + the destructor of its child, \c quit, which is incorrect because \c + quit is a local variable. When \c quit subsequently goes out of scope, + its destructor is called again, this time correctly, but the damage has + already been done. +*/ diff --git a/doc/src/core/objectmodel/properties.qdoc b/doc/src/core/objectmodel/properties.qdoc new file mode 100644 index 0000000000..befbde190b --- /dev/null +++ b/doc/src/core/objectmodel/properties.qdoc @@ -0,0 +1,273 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page properties.html + \title The Property System + \brief An overview of Qt's property system. + + \ingroup qt-basic-concepts + \target Qt's Property System + + Qt provides a sophisticated property system similar to the ones + supplied by some compiler vendors. However, as a compiler- and + platform-independent library, Qt does not rely on non-standard + compiler features like \c __property or \c [property]. The Qt + solution works with \e any standard C++ compiler on every platform + Qt supports. It is based on the \l {Meta-Object System} that also + provides inter-object communication via \l{signals and slots}. + + \section1 Requirements for Declaring Properties + + To declare a property, use the \l {Q_PROPERTY()} {Q_PROPERTY()} + macro in a class that inherits QObject. + + \snippet doc/src/snippets/code/doc_src_properties.cpp 0 + + Here are some typical examples of property declarations taken from + class QWidget. + + \snippet doc/src/snippets/code/doc_src_properties.cpp 1 + + A property behaves like a class data member, but it has additional + features accessible through the \l {Meta-Object System}. + + \list + + \o A \c READ accessor function is required. It is for reading the + property value. Ideally, a const function is used for this purpose, + and it must return either the property's type or a pointer or + reference to that type. e.g., QWidget::focus is a read-only property + with \c READ function, QWidget::hasFocus(). + + \o A \c WRITE accessor function is optional. It is for setting the + property value. It must return void and must take exactly one + argument, either of the property's type or a pointer or reference + to that type. e.g., QWidget::enabled has the \c WRITE function + QWidget::setEnabled(). Read-only properties do not need \c WRITE + functions. e.g., QWidget::focus has no \c WRITE function. + + \o A \c RESET function is optional. It is for setting the property + back to its context specific default value. e.g., QWidget::cursor + has the typical \c READ and \c WRITE functions, QWidget::cursor() + and QWidget::setCursor(), and it also has a \c RESET function, + QWidget::unsetCursor(), since no call to QWidget::setCursor() can + mean \e {reset to the context specific cursor}. The \c RESET + function must return void and take no parameters. + + \o A \c NOTIFY signal is optional. If defined, it should specify one + existing signal in that class that is emitted whenever the value + of the property changes. + + \o A \c REVISION number is optional. If included, it defines the + the property and its notifier signal to be used in a particular + revision of the API that is exposed to QML. + + \o The \c DESIGNABLE attribute indicates whether the property + should be visible in the property editor of GUI design tool (e.g., + \l {Qt Designer}). Most properties are \c DESIGNABLE (default + true). Instead of true or false, you can specify a boolean + member function. + + \o The \c SCRIPTABLE attribute indicates whether this property + should be accessible by a scripting engine (default true). + Instead of true or false, you can specify a boolean member + function. + + \o The \c STORED attribute indicates whether the property should + be thought of as existing on its own or as depending on other + values. It also indicates whether the property value must be saved + when storing the object's state. Most properties are \c STORED + (default true), but e.g., QWidget::minimumWidth() has \c STORED + false, because its value is just taken from the width component + of property QWidget::minimumSize(), which is a QSize. + + \o The \c USER attribute indicates whether the property is + designated as the user-facing or user-editable property for the + class. Normally, there is only one \c USER property per class + (default false). e.g., QAbstractButton::checked is the user + editable property for (checkable) buttons. Note that QItemDelegate + gets and sets a widget's \c USER property. + + \o The presence of the \c CONSTANT attibute indicates that the property + value is constant. For a given object instance, the READ method of a + constant property must return the same value every time it is called. This + constant value may be different for different instances of the object. A + constant property cannot have a WRITE method or a NOTIFY signal. + + \o The presence of the \c FINAL attribute indicates that the property + will not be overridden by a derived class. This can be used for performance + optimizations in some cases, but is not enforced by moc. Care must be taken + never to override a \c FINAL property. + + \endlist + + The \c READ, \c WRITE, and \c RESET functions can be inherited. + They can also be virtual. When they are inherited in classes where + multiple inheritance is used, they must come from the first + inherited class. + + The property type can be any type supported by QVariant, or it can + be a user-defined type. In this example, class QDate is considered + to be a user-defined type. + + \snippet doc/src/snippets/code/doc_src_properties.cpp 2 + + Because QDate is user-defined, you must include the \c{} + header file with the property declaration. + + For QMap, QList, and QValueList properties, the property value is + a QVariant whose value is the entire list or map. Note that the + Q_PROPERTY string cannot contain commas, because commas separate + macro arguments. Therefore, you must use \c QMap as the property + type instead of \c QMap. For consistency, also + use \c QList and \c QValueList instead of \c QList and + \c QValueList. + + \section1 Reading and Writing Properties with the Meta-Object System + + A property can be read and written using the generic functions + QObject::property() and QObject::setProperty(), without knowing + anything about the owning class except the property's name. In + the code snippet below, the call to QAbstractButton::setDown() and + the call to QObject::setProperty() both set property "down". + + \snippet doc/src/snippets/code/doc_src_properties.cpp 3 + + Accessing a property through its \c WRITE accessor is the better + of the two, because it is faster and gives better diagnostics at + compile time, but setting the property this way requires that you + know about the class at compile time. Accessing properties by name + lets you access classes you don't know about at compile time. You + can \e discover a class's properties at run time by querying its + QObject, QMetaObject, and \l {QMetaProperty} {QMetaProperties}. + + \snippet doc/src/snippets/code/doc_src_properties.cpp 4 + + In the above snippet, QMetaObject::property() is used to get \l + {QMetaProperty} {metadata} about each property defined in some + unknown class. The property name is fetched from the metadata and + passed to QObject::property() to get the \l {QVariant} {value} of + the property in the current \l {QObject}{object}. + + \section1 A Simple Example + + Suppose we have a class MyClass, which is derived from QObject and + which uses the Q_OBJECT macro in its private section. We want to + declare a property in MyClass to keep track of a priorty + value. The name of the property will be \e priority, and its type + will be an enumeration type named \e Priority, which is defined in + MyClass. + + We declare the property with the Q_PROPERTY() macro in the private + section of the class. The required \c READ function is named \c + priority, and we include a \c WRITE function named \c setPriority. + The enumeration type must be registered with the \l {Meta-Object + System} using the Q_ENUMS() macro. Registering an enumeration type + makes the enumerator names available for use in calls to + QObject::setProperty(). We must also provide our own declarations + for the \c READ and \c WRITE functions. The declaration of MyClass + then might look like this: + + \snippet doc/src/snippets/code/doc_src_properties.cpp 5 + + The \c READ function is const and returns the property type. The + \c WRITE function returns void and has exactly one parameter of + the property type. The meta-object compiler enforces these + requirements. + + Given a pointer to an instance of MyClass or a pointer to a + QObject that is an instance of MyClass, we have two ways to set + its priority property: + + \snippet doc/src/snippets/code/doc_src_properties.cpp 6 + + In the example, the enumeration type that is the property type is + declared in MyClass and registered with the \l{Meta-Object System} + using the Q_ENUMS() macro. This makes the enumeration values + available as strings for use as in the call to setProperty(). Had + the enumeration type been declared in another class, its fully + qualified name (i.e., OtherClass::Priority) would be required, and + that other class would also have to inherit QObject and register + the enumeration type there using the Q_ENUMS() macro. + + A similar macro, Q_FLAGS(), is also available. Like Q_ENUMS(), it + registers an enumeration type, but it marks the type as being a + set of \e flags, i.e. values that can be OR'd together. An I/O + class might have enumeration values \c Read and \c Write and then + QObject::setProperty() could accept \c{Read | Write}. Q_FLAGS() + should be used to register this enumeration type. + + \section1 Dynamic Properties + + QObject::setProperty() can also be used to add \e new properties + to an instance of a class at runtime. When it is called with a + name and a value, if a property with the given name exists in the + QObject, and if the given value is compatible with the property's + type, the value is stored in the property, and true is returned. + If the value is \e not compatible with the property's type, the + property is \e not changed, and false is returned. But if the + property with the given name doesn't exist in the QObject (i.e., + if it wasn't declared with Q_PROPERTY(), a new property with the + given name and value is automatically added to the QObject, but + false is still returned. This means that a return of false can't + be used to determine whether a particular property was actually + set, unless you know in advance that the property already exists + in the QObject. + + Note that \e dynamic properties are added on a per instance basis, + i.e., they are added to QObject, not QMetaObject. A property can + be removed from an instance by passing the property name and an + invalid QVariant value to QObject::setProperty(). The default + constructor for QVariant constructs an invalid QVariant. + + Dynamic properties can be queried with QObject::property(), just + like properties declared at compile time with Q_PROPERTY(). + + \sa {Meta-Object System}, {Signals and Slots} + + \section1 Properties and Custom Types + + Custom types used by properties need to be registered using the + Q_DECLARE_METATYPE() macro so that their values can be stored in + QVariant objects. This makes them suitable for use with both + static properties declared using the Q_PROPERTY() macro in class + definitions and dynamic properties created at run-time. + + \sa Q_DECLARE_METATYPE(), QMetaType, QVariant + + \section1 Adding Additional Information to a Class + + Connected to the property system is an additional macro, + Q_CLASSINFO(), that can be used to attach additional + \e{name}--\e{value} pairs to a class's meta-object, for example: + + \snippet doc/src/snippets/code/doc_src_properties.cpp 7 + + Like other meta-data, class information is accessible at run-time + through the meta-object; see QMetaObject::classInfo() for details. +*/ diff --git a/doc/src/core/objectmodel/signalsandslots.qdoc b/doc/src/core/objectmodel/signalsandslots.qdoc new file mode 100644 index 0000000000..2f8646ea1c --- /dev/null +++ b/doc/src/core/objectmodel/signalsandslots.qdoc @@ -0,0 +1,451 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page signalsandslots.html + \title Signals & Slots + \ingroup qt-basic-concepts + \brief An overview of Qt's signals and slots inter-object + communication mechanism. + + Signals and slots are used for communication between objects. The + signals and slots mechanism is a central feature of Qt and + probably the part that differs most from the features provided by + other frameworks. + + \tableofcontents + + \section1 Introduction + + In GUI programming, when we change one widget, we often want + another widget to be notified. More generally, we want objects of + any kind to be able to communicate with one another. For example, + if a user clicks a \gui{Close} button, we probably want the + window's \l{QWidget::close()}{close()} function to be called. + + Older toolkits achieve this kind of communication using + callbacks. A callback is a pointer to a function, so if you want + a processing function to notify you about some event you pass a + pointer to another function (the callback) to the processing + function. The processing function then calls the callback when + appropriate. Callbacks have two fundamental flaws: Firstly, they + are not type-safe. We can never be certain that the processing + function will call the callback with the correct arguments. + Secondly, the callback is strongly coupled to the processing + function since the processing function must know which callback + to call. + + \section1 Signals and Slots + + In Qt, we have an alternative to the callback technique: We use + signals and slots. A signal is emitted when a particular event + occurs. Qt's widgets have many predefined signals, but we can + always subclass widgets to add our own signals to them. A slot + is a function that is called in response to a particular signal. + Qt's widgets have many pre-defined slots, but it is common + practice to subclass widgets and add your own slots so that you + can handle the signals that you are interested in. + + \img abstract-connections.png + \omit + \caption An abstract view of some signals and slots connections + \endomit + + The signals and slots mechanism is type safe: The signature of a + signal must match the signature of the receiving slot. (In fact a + slot may have a shorter signature than the signal it receives + because it can ignore extra arguments.) Since the signatures are + compatible, the compiler can help us detect type mismatches. + Signals and slots are loosely coupled: A class which emits a + signal neither knows nor cares which slots receive the signal. + Qt's signals and slots mechanism ensures that if you connect a + signal to a slot, the slot will be called with the signal's + parameters at the right time. Signals and slots can take any + number of arguments of any type. They are completely type safe. + + All classes that inherit from QObject or one of its subclasses + (e.g., QWidget) can contain signals and slots. Signals are emitted by + objects when they change their state in a way that may be interesting + to other objects. This is all the object does to communicate. It + does not know or care whether anything is receiving the signals it + emits. This is true information encapsulation, and ensures that the + object can be used as a software component. + + Slots can be used for receiving signals, but they are also normal + member functions. Just as an object does not know if anything receives + its signals, a slot does not know if it has any signals connected to + it. This ensures that truly independent components can be created with + Qt. + + You can connect as many signals as you want to a single slot, and a + signal can be connected to as many slots as you need. It is even + possible to connect a signal directly to another signal. (This will + emit the second signal immediately whenever the first is emitted.) + + Together, signals and slots make up a powerful component programming + mechanism. + + \section1 A Small Example + + A minimal C++ class declaration might read: + + \snippet doc/src/snippets/signalsandslots/signalsandslots.h 0 + + A small QObject-based class might read: + + \snippet doc/src/snippets/signalsandslots/signalsandslots.h 1 + \codeline + \snippet doc/src/snippets/signalsandslots/signalsandslots.h 2 + \snippet doc/src/snippets/signalsandslots/signalsandslots.h 3 + + The QObject-based version has the same internal state, and provides + public methods to access the state, but in addition it has support + for component programming using signals and slots. This class can + tell the outside world that its state has changed by emitting a + signal, \c{valueChanged()}, and it has a slot which other objects + can send signals to. + + All classes that contain signals or slots must mention + Q_OBJECT at the top of their declaration. They must also derive + (directly or indirectly) from QObject. + + Slots are implemented by the application programmer. + Here is a possible implementation of the \c{Counter::setValue()} + slot: + + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 0 + + The \c{emit} line emits the signal \c valueChanged() from the + object, with the new value as argument. + + In the following code snippet, we create two \c Counter objects + and connect the first object's \c valueChanged() signal to the + second object's \c setValue() slot using QObject::connect(): + + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 1 + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 2 + \codeline + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 3 + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 4 + + Calling \c{a.setValue(12)} makes \c{a} emit a + \c{valueChanged(12)} signal, which \c{b} will receive in its + \c{setValue()} slot, i.e. \c{b.setValue(12)} is called. Then + \c{b} emits the same \c{valueChanged()} signal, but since no slot + has been connected to \c{b}'s \c{valueChanged()} signal, the + signal is ignored. + + Note that the \c{setValue()} function sets the value and emits + the signal only if \c{value != m_value}. This prevents infinite + looping in the case of cyclic connections (e.g., if + \c{b.valueChanged()} were connected to \c{a.setValue()}). + + By default, for every connection you make, a signal is emitted; + two signals are emitted for duplicate connections. You can break + all of these connections with a single disconnect() call. + If you pass the Qt::UniqueConnection \a type, the connection will only + be made if it is not a duplicate. If there is already a duplicate + (exact same signal to the exact same slot on the same objects), + the connection will fail and connect will return false + + This example illustrates that objects can work together without needing to + know any information about each other. To enable this, the objects only + need to be connected together, and this can be achieved with some simple + QObject::connect() function calls, or with \c{uic}'s + \l{Using a Designer UI File in Your Application#Automatic Connections} + {automatic connections} feature. + + \section1 Building the Example + + The C++ preprocessor changes or removes the \c{signals}, + \c{slots}, and \c{emit} keywords so that the compiler is + presented with standard C++. + + By running the \l moc on class definitions that contain signals + or slots, a C++ source file is produced which should be compiled + and linked with the other object files for the application. If + you use \l qmake, the makefile rules to automatically invoke \c + moc will be added to your project's makefile. + + \section1 Signals + + Signals are emitted by an object when its internal state has changed + in some way that might be interesting to the object's client or owner. + Only the class that defines a signal and its subclasses can emit the + signal. + + When a signal is emitted, the slots connected to it are usually + executed immediately, just like a normal function call. When this + happens, the signals and slots mechanism is totally independent of + any GUI event loop. Execution of the code following the \c emit + statement will occur once all slots have returned. The situation is + slightly different when using \l{Qt::ConnectionType}{queued + connections}; in such a case, the code following the \c emit keyword + will continue immediately, and the slots will be executed later. + + If several slots are connected to one signal, the slots will be + executed one after the other, in the order they have been connected, + when the signal is emitted. + + Signals are automatically generated by the \l moc and must not be + implemented in the \c .cpp file. They can never have return types + (i.e. use \c void). + + A note about arguments: Our experience shows that signals and slots + are more reusable if they do not use special types. If + QScrollBar::valueChanged() were to use a special type such as the + hypothetical QScrollBar::Range, it could only be connected to + slots designed specifically for QScrollBar. Connecting different + input widgets together would be impossible. + + \section1 Slots + + A slot is called when a signal connected to it is emitted. Slots are + normal C++ functions and can be called normally; their only special + feature is that signals can be connected to them. + + Since slots are normal member functions, they follow the normal C++ + rules when called directly. However, as slots, they can be invoked + by any component, regardless of its access level, via a signal-slot + connection. This means that a signal emitted from an instance of an + arbitrary class can cause a private slot to be invoked in an instance + of an unrelated class. + + You can also define slots to be virtual, which we have found quite + useful in practice. + + Compared to callbacks, signals and slots are slightly slower + because of the increased flexibility they provide, although the + difference for real applications is insignificant. In general, + emitting a signal that is connected to some slots, is + approximately ten times slower than calling the receivers + directly, with non-virtual function calls. This is the overhead + required to locate the connection object, to safely iterate over + all connections (i.e. checking that subsequent receivers have not + been destroyed during the emission), and to marshall any + parameters in a generic fashion. While ten non-virtual function + calls may sound like a lot, it's much less overhead than any \c + new or \c delete operation, for example. As soon as you perform a + string, vector or list operation that behind the scene requires + \c new or \c delete, the signals and slots overhead is only + responsible for a very small proportion of the complete function + call costs. + + The same is true whenever you do a system call in a slot; or + indirectly call more than ten functions. On an i586-500, you can + emit around 2,000,000 signals per second connected to one + receiver, or around 1,200,000 per second connected to two + receivers. The simplicity and flexibility of the signals and + slots mechanism is well worth the overhead, which your users + won't even notice. + + Note that other libraries that define variables called \c signals + or \c slots may cause compiler warnings and errors when compiled + alongside a Qt-based application. To solve this problem, \c + #undef the offending preprocessor symbol. + + \section1 Meta-Object Information + + The meta-object compiler (\l moc) parses the class declaration in + a C++ file and generates C++ code that initializes the + meta-object. The meta-object contains the names of all the signal + and slot members, as well as pointers to these functions. + + The meta-object contains additional information such as the + object's \link QObject::className() class name\endlink. You can + also check if an object \link QObject::inherits() + inherits\endlink a specific class, for example: + + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 5 + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 6 + + The meta-object information is also used by qobject_cast(), which + is similar to QObject::inherits() but is less error-prone: + + \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 7 + + See \l{Meta-Object System} for more information. + + \section1 A Real Example + + Here is a simple commented example of a widget. + + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 0 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 1 + \codeline + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 2 + \codeline + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 3 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 4 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 5 + + \c LcdNumber inherits QObject, which has most of the signal-slot + knowledge, via QFrame and QWidget. It is somewhat similar to the + built-in QLCDNumber widget. + + The Q_OBJECT macro is expanded by the preprocessor to declare + several member functions that are implemented by the \c{moc}; if + you get compiler errors along the lines of "undefined reference + to vtable for \c{LcdNumber}", you have probably forgotten to + \l{moc}{run the moc} or to include the moc output in the link + command. + + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 6 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 7 + + It's not obviously relevant to the moc, but if you inherit + QWidget you almost certainly want to have the \c parent argument + in your constructor and pass it to the base class's constructor. + + Some destructors and member functions are omitted here; the \c + moc ignores member functions. + + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 8 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 9 + + \c LcdNumber emits a signal when it is asked to show an impossible + value. + + If you don't care about overflow, or you know that overflow + cannot occur, you can ignore the \c overflow() signal, i.e. don't + connect it to any slot. + + If on the other hand you want to call two different error + functions when the number overflows, simply connect the signal to + two different slots. Qt will call both (in the order they were connected). + + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 10 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 11 + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 12 + \codeline + \snippet doc/src/snippets/signalsandslots/lcdnumber.h 13 + + A slot is a receiving function used to get information about + state changes in other widgets. \c LcdNumber uses it, as the code + above indicates, to set the displayed number. Since \c{display()} + is part of the class's interface with the rest of the program, + the slot is public. + + Several of the example programs connect the + \l{QScrollBar::valueChanged()}{valueChanged()} signal of a + QScrollBar to the \c display() slot, so the LCD number + continuously shows the value of the scroll bar. + + Note that \c display() is overloaded; Qt will select the + appropriate version when you connect a signal to the slot. With + callbacks, you'd have to find five different names and keep track + of the types yourself. + + Some irrelevant member functions have been omitted from this + example. + + \section1 Signals And Slots With Default Arguments + + The signatures of signals and slots may contain arguments, and the + arguments can have default values. Consider QObject::destroyed(): + + \code + void destroyed(QObject* = 0); + \endcode + + When a QObject is deleted, it emits this QObject::destroyed() + signal. We want to catch this signal, wherever we might have a + dangling reference to the deleted QObject, so we can clean it up. + A suitable slot signature might be: + + \code + void objectDestroyed(QObject* obj = 0); + \endcode + + To connect the signal to the slot, we use QObject::connect() and + the \c{SIGNAL()} and \c{SLOT()} macros. The rule about whether to + include arguments or not in the \c{SIGNAL()} and \c{SLOT()} + macros, if the arguments have default values, is that the + signature passed to the \c{SIGNAL()} macro must \e not have fewer + arguments than the signature passed to the \c{SLOT()} macro. + + All of these would work: + \code + connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed(Qbject*))); + connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed())); + connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed())); + \endcode + But this one won't work: + \code + connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed(QObject*))); + \endcode + + ...because the slot will be expecting a QObject that the signal + will not send. This connection will report a runtime error. + + \section1 Advanced Signals and Slots Usage + + For cases where you may require information on the sender of the + signal, Qt provides the QObject::sender() function, which returns + a pointer to the object that sent the signal. + + The QSignalMapper class is provided for situations where many + signals are connected to the same slot and the slot needs to + handle each signal differently. + + Suppose you have three push buttons that determine which file you + will open: "Tax File", "Accounts File", or "Report File". + + In order to open the correct file, you use QSignalMapper::setMapping() to + map all the clicked() signals to a QSignalMapper object. Then you connect + the file's QPushButton::clicked() signal to the QSignalMapper::map() slot. + + \snippet doc/src/snippets/signalmapper/filereader.cpp 0 + + Then, you connect the \l{QSignalMapper::}{mapped()} signal to + \c{readFile()} where a different file will be opened, depending on + which push button is pressed. + + \snippet doc/src/snippets/signalmapper/filereader.cpp 1 + + \note The following code will compile and run, but due to signature normalization, the code will be slower. + + \snippet doc/src/snippets/signalmapper/filereader.cpp 2 + + \sa {Meta-Object System}, {Qt's Property System} + + \target 3rd Party Signals and Slots + \section2 Using Qt with 3rd Party Signals and Slots + + It is possible to use Qt with a 3rd party signal/slot mechanism. + You can even use both mechanisms in the same project. Just add the + following line to your qmake project (.pro) file. + + \snippet doc/src/snippets/code/doc_src_containers.cpp 22 + + It tells Qt not to define the moc keywords \c{signals}, \c{slots}, + and \c{emit}, because these names will be used by a 3rd party + library, e.g. Boost. Then to continue using Qt signals and slots + with the \c{no_keywords} flag, simply replace all uses of the Qt + moc keywords in your sources with the corresponding Qt macros + Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), and Q_EMIT. +*/ diff --git a/doc/src/core/threads.qdoc b/doc/src/core/threads.qdoc new file mode 100644 index 0000000000..09707f5dfc --- /dev/null +++ b/doc/src/core/threads.qdoc @@ -0,0 +1,572 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page thread-basics.html + \ingroup tutorials + \startpage {index.html}{Qt Reference Documentation} + + \title Threading Basics + \brief An introduction to threads + + \section1 What Are Threads? + + Threads are about doing things in parallel, just like processes. So how do + threads differ from processes? While you are making calculations on a + spreadsheet, there may also be a media player running on the same desktop + playing your favorite song. Here is an example of two processes working in + parallel: one running the spreadsheet program; one running a media player. + Multitasking is a well known term for this. A closer look at the media + player reveals that there are again things going on in parallel within one + single process. While the media player is sending music to the audio driver, + the user interface with all its bells and whistles is being constantly + updated. This is what threads are for \mdash concurrency within one single + process. + + So how is concurrency implemented? Parallel work on single core CPUs is an + illusion which is somewhat similar to the illusion of moving images in + cinema. + For processes, the illusion is produced by interrupting the processor's + work on one process after a very short time. Then the processor moves on to + the next process. In order to switch between processes, the current program + counter is saved and the next processor's program counter is loaded. This + is not sufficient because the same needs to be done with registers and + certain architecture and OS specific data. + + Just as one CPU can power two or more processes, it is also possible to let + the CPU run on two different code segments of one single process. When a + process starts, it always executes one code segment and therefore the + process is said to have one thread. However, the program may decide to + start a second thread. Then, two different code sequences are processed + simultaneously inside one process. Concurrency is achieved on single core + CPUs by repeatedly saving program counters and registers then loading the + next thread's program counters and registers. No cooperation from the + program is required to cycle between the active threads. A thread may be in + any state when the switch to the next thread occurs. + + The current trend in CPU design is to have several cores. A typical + single-threaded application can make use of only one core. However, a + program with multiple threads can be assigned to multiple cores, making + things happen in a truly concurrent way. As a result, distributing work + to more than one thread can make a program run much faster on multicore + CPUs because additional cores can be used. + + \section2 GUI Thread and Worker Thread + + As mentioned, each program has one thread when it is started. This thread + is called the "main thread" (also known as the "GUI thread" in Qt + applications). The Qt GUI must run in this thread. All widgets and several + related classes, for example QPixmap, don't work in secondary threads. + A secondary thread is commonly referred to as a "worker thread" because it + is used to offload processing work from the main thread. + + \section2 Simultaneous Access to Data + + Each thread has its own stack, which means each thread has its own call + history and local variables. Unlike processes, threads share the same + address space. The following diagram shows how the building blocks of + threads are located in memory. Program counter and registers of inactive + threads are typically kept in kernel space. There is a shared copy of the + code and a separate stack for each thread. + + \image threadvisual-example.png "Thread visualization" + + If two threads have a pointer to the same object, it is possible that both + threads will access that object at the same time and this can potentially + destroy the object's integrity. It's easy to imagine the many things that + can go wrong when two methods of the same object are executed + simultaneously. + + Sometimes it is necessary to access one object from different threads; + for example, when objects living in different threads need to communicate. + Since threads use the same address space, it is easier and faster for + threads to exchange data than it is for processes. Data does not have to be + serialized and copied. Passing pointers is possible, but there must be a + strict coordination of what thread touches which object. Simultaneous + execution of operations on one object must be prevented. There are several + ways of achieving this and some of them are described below. + + So what can be done safely? All objects created in a thread can be used + safely within that thread provided that other threads don't have references + to them and objects don't have implicit coupling with other threads. Such + implicit coupling may happen when data is shared between instances as with + static members, singletons or global data. Familiarize yourself with the + concept of \l{Reentrancy and Thread-Safety}{thread safe and reentrant} + classes and functions. + + \section1 Using Threads + + There are basically two use cases for threads: + + \list + \o Make processing faster by making use of multicore processors. + \o Keep the GUI thread or other time critical threads responsive by + offloading long lasting processing or blocking calls to other threads. + \endlist + + \section2 When to Use Alternatives to Threads + + Developers need to be very careful with threads. It is easy to start other + threads, but very hard to ensure that all shared data remains consistent. + Problems are often hard to find because they may only show up once in a + while or only on specific hardware configurations. Before creating threads + to solve certain problems, possible alternatives should be considered. + + \table + \header + \o Alternative + \o Comment + \row + \o QEventLoop::processEvents() + \o Calling QEventLoop::processEvents() repeatedly during a + time-consuming calculation prevents GUI blocking. However, this + solution doesn't scale well because the call to processEvents() may + occur too often, or not often enough, depending on hardware. + \row + \o QTimer + \o Background processing can sometimes be done conveniently using a + timer to schedule execution of a slot at some point in the future. + A timer with an interval of 0 will time out as soon as there are no + more events to process. + \row + \o QSocketNotifier QNetworkAccessManager QIODevice::readyRead() + \o This is an alternative to having one or multiple threads, each with + a blocking read on a slow network connection. As long as the + calculation in response to a chunk of network data can be executed + quickly, this reactive design is better than synchronous waiting in + threads. Reactive design is less error prone and energy efficient + than threading. In many cases there are also performance benefits. + \endtable + + In general, it is recommended to only use safe and tested paths and to + avoid introducing ad-hoc threading concepts. QtConcurrent provides an easy + interface for distributing work to all of the processor's cores. The + threading code is completely hidden in the QtConcurrent framework, so you + don't have to take care of the details. However, QtConcurrent can't be used + when communication with the running thread is needed, and it shouldn't be + used to handle blocking operations. + + \section2 Which Qt Thread Technology Should You Use? + + Sometimes you want to do more than just running a method in the context of + another thread. You may want to have an object which lives in another + thread that provides a service to the GUI thread. Maybe you want another + thread to stay alive forever to poll hardware ports and send a signal to + the GUI thread when something noteworthy has happened. Qt provides + different solutions for developing threaded applications. The right + solution depends on the purpose of the new thread as well as on the + thread's lifetime. + + \table + \header + \o Lifetime of thread + \o Development task + \o Solution + \row + \o One call + \o Run one method within another thread and quit the thread when the + method is finished. + \o Qt provides different solutions: + \list + \o Write a function and run it with QtConcurrent::run() + \o Derive a class from QRunnable and run it in the global thread + pool with QThreadPool::globalInstance()->start() + \o Derive a class from QThread, reimplement the QThread::run() + method and use QThread::start() to run it. + \endlist + + \row + \o One call + \o Operations are to be performed on all items of a container. + Processing should be performed using all available cores. A common + example is to produce thumbnails from a list of images. + \o QtConcurrent provides the \l{QtConcurrent::}{map()} function for + applying operations on every container element, + \l{QtConcurrent::}{filter()} for selecting container elements, and + the option of specifying a reduce function for combining the + remaining elements. + \row + \o One call + \o A long running operation has to be put in another thread. During the + course of processing, status information should be sent to the GUI + thread. + \o Use QThread, reimplement run and emit signals as needed. Connect the + signals to the GUI thread's slots using queued signal/slot + connections. + + \row + \o Permanent + \o Have an object living in another thread and let it perform different + tasks upon request. + This means communication to and from the worker thread is required. + \o Derive a class from QObject and implement the necessary slots and + signals, move the object to a thread with a running event loop and + communicate with the object over queued signal/slot connections. + \row + \o Permanent + \o Have an object living in another thread, let the object perform + repeated tasks such as polling a port and enable communication with + the GUI thread. + \o Same as above but also use a timer in the worker thread to implement + polling. However, the best solution for polling is to avoid it + completely. Sometimes using QSocketNotifier is an alternative. + \endtable + + + \section1 Qt Thread Basics + + QThread is a very convenient cross platform abstraction of native platform + threads. Starting a thread is very simple. Let us look at a short piece of + code that generates another thread which says hello in that thread and then + exits. + + \snippet examples/tutorials/threads/hellothread/hellothread.h 1 + + We derive a class from QThread and reimplement the \l{QThread::}{run()} + method. + + \snippet examples/tutorials/threads/hellothread/hellothread.cpp 1 + + The run method contains the code that will be run in a separate thread. In + this example, a message containing the thread ID will be printed. + QThread::start() will call the method in another thread. + + \snippet examples/tutorials/threads/hellothread/main.cpp 1 + + To start the thread, our thread object needs to be instantiated. The + \l{QThread::}{start()} method creates a new thread and calls the + reimplemented \l{QThread::}{run()} method in this new thread. Right after + \l{QThread::}{start()} is called, two program counters walk through the + program code. The main function starts with only the GUI thread running and + it should terminate with only the GUI thread running. Exiting the program + when another thread is still busy is a programming error, and therefore, + wait is called which blocks the calling thread until the + \l{QThread::}{run()} method has completed. + + This is the result of running the code: + + \badcode + hello from GUI thread 3079423696 + hello from worker thread 3076111216 + \endcode + + + \section2 QObject and Threads + + A QObject is said to have a \e{thread affinity} or, in other words, that it + lives in a certain thread. This means that, at creation time, QObject saves + a pointer to the current thread. This information becomes relevant when an + event is posted with \l{QCoreApplication::}{postEvent()}. The event will be + put in the corresponding thread's event loop. If the thread where the + QObject lives doesn't have an event loop, the event will never be delivered. + + To start an event loop, \l{QThread::}{exec()} must be called inside + \l{QThread::}{run()}. Thread affinity can be changed using + \l{QObject::}{moveToThread()}. + + As mentioned above, developers must always be careful when calling objects' + methods from other threads. Thread affinity does not change this situation. + Qt documentation marks several methods as thread-safe. + \l{QCoreApplication::}{postEvent()} is a noteworthy example. A thread-safe + method may be called from different threads simultaneously. + + In cases where there is usually no concurrent access to methods, calling + non-thread-safe methods of objects in other threads may work thousands + of times before a concurrent access occurs, causing unexpected behavior. + Writing test code does not entirely ensure thread correctness, but it is + still important. + On Linux, Valgrind and Helgrind can help detect threading errors. + + The anatomy of QThread is quite interesting: + + \list + \o QThread does not live in the new thread where \l{QThread::}{run()} is + executed. It lives in the old thread. + \o Most QThread methods are the thread's control interface and are meant to + be called from the old thread. Do not move this interface to the newly + created thread using \l{QObject::}{moveToThread()}; i.e., calling + \l{QObject::moveToThread()}{moveToThread(this)} is regarded as bad + practice. + \o \l{QThread::}{exec()} and the static methods + \l{QThread::}{usleep()}, \l{QThread::}{msleep()}, + \l{QThread::}{sleep()} are meant to be called from the newly created + thread. + \o Additional members defined in the QThread subclass are + accessible by both threads. The developer is responsible for + coordinating access. A typical strategy is to set the members before + \l{QThread::}{start()} is called. Once the worker thread is running, + the main thread should not touch the additional members anymore. After + the worker has terminated, the main thread can access the additional + members again. This is a convenient strategy for passing parameters to a + thread before it is started as well as for collecting the result once it + has terminated. + \endlist + + A QObject's parent must always be in the same thread. This has a surprising + consequence for objects generated within the \l{QThread::}{run()} method: + + \code + void HelloThread::run() + { + QObject *object1 = new QObject(this); //error, parent must be in the same thread + QObject object2; // OK + QSharedPointer object3(new QObject); // OK + } + \endcode + + \section2 Using a Mutex to Protect the Integrity of Data + + A mutex is an object that has \l{QMutex::}{lock()} and \l{QMutex::}{unlock()} + methods and remembers if it is already locked. A mutex is designed to be + called from multiple threads. \l{QMutex::}{lock()} returns immediately if + the mutex is not locked. The next call from another thread will find the + mutex in a locked state and then \l{QMutex::}{lock()} will block the thread + until the other thread calls \l{QMutex::}{unlock()}. This functionality can + make sure that a code section will be executed by only one thread at a time. + + The following line sketches how a mutex can be used to make a method + thread-safe: + + \code + void Worker::work() + { + this->mutex.lock(); // first thread can pass, other threads will be blocked here + doWork(); + this->mutex.unlock(); + } + \endcode + + What happens if one thread does not unlock a mutex? The result can be a + frozen application. In the example above, an exception might be thrown and + \c{mutex.unlock()} will never be reached. To prevent problems like this, + QMutexLocker should be used. + + \code + void Worker::work() + { + QMutexLocker locker(&mutex); // Locks the mutex and unlocks when locker exits the scope + doWork(); + } + \endcode + + This looks easy, but mutexes introduce a new class of problems: deadlocks. + A deadlock happens when a thread waits for a mutex to become unlocked, but + the mutex remains locked because the owning thread is waiting for the first + thread to unlock it. The result is a frozen application. Mutexes can be + used to make a method thread safe. Most Qt methods aren't thread safe + because there is always a performance penalty when using mutexes. + + It isn't always possible to lock and unlock a mutex in a method. Sometimes + the need to lock spans several calls. For example, modifying a container + with an iterator requires a sequence of several calls which should not be + interrupted by other threads. In such a scenario, locking can be achieved + with a mutex that is kept outside of the object to be manipulated. With an + external mutex, the duration of locking can be adjusted to the needs of the + operation. One disadvantage is that external mutexes aid locking, but do + not enforce it because users of the object may forget to use it. + + \section2 Using the Event Loop to Prevent Data Corruption + + The event loops of Qt are a very valuable tool for inter-thread + communication. Every thread may have its own event loop. A safe way of + calling a slot in another thread is by placing that call in another + thread's event loop. This ensures that the target object finishes the + method that is currently running before another method is started. + + So how is it possible to put a method invocation in an event loop? Qt has + two ways of doing this. One way is via queued signal-slot connections; the + other way is to post an event with QCoreApplication::postEvent(). A queued + signal-slot connection is a signal slot connection that is executed + asynchronously. The internal implementation is based on posted events. The + arguments of the signal are put into the event loop and the signal method + returns immediately. + + The connected slot will be executed at a time which depends on what else is + in the event loop. + + Communication via the event loop eliminates the deadlock problem we face + when using mutexes. This is why we recommend using the event loop rather + than locking an object using a mutex. + + \section2 Dealing with Asynchronous Execution + + One way to obtain a worker thread's result is by waiting for the thread + to terminate. In many cases, however, a blocking wait isn't acceptable. The + alternative to a blocking wait are asynchronous result deliveries with + either posted events or queued signals and slots. This generates a certain + overhead because an operation's result does not appear on the next source + line, but in a slot located somewhere else in the source file. Qt + developers are used to working with this kind of asynchronous behavior + because it is much similar to the kind of event-driven programming used in + GUI applications. + + \section1 Examples + + This tutorial comes with examples for Qt's three basic ways of working with + threads. Two more examples show how to communicate with a running thread + and how a QObject can be placed in another thread, providing service to the + main thread. + + \list + \o Using QThread as shown \l{Qt thread basics}{above} + \o \l{Example 1: Using the Thread Pool}{Using the global QThreadPool} + \o \l{Example 2: Using QtConcurrent}{Using QtConcurrent} + \o \l{Example 3: Clock}{Communication with the GUI thread} + \o \l{Example 4: A Permanent Thread}{A permanent QObject in another thread + provides service to the main thread} + \endlist + + The following examples can all be compiled and run independently. The source can + be found in the examples directory: examples/tutorials/threads/ + + \section2 Example 1: Using the Thread Pool + + Creating and destroying threads frequently can be expensive. To avoid the + cost of thread creation, a thread pool can be used. A thread pool is a + place where threads can be parked and fetched. We can write the same + "hello thread" program as \l{Qt Thread Basics}{above} using the global + thread pool. We derive a class from QRunnable. The code we want to run in + another thread needs to be placed in the reimplemented QRunnable::run() + method. + + \snippet examples/tutorials/threads/hellothreadpool/hellothreadpool.cpp 1 + + We instantiate Work in main(), locate the global thread pool and use the + QThreadPool::start() method. Now the thread pool runs our worker in another + thread. Using the thread pool has a performance advantage because threads + are not destroyed after they have finished running. They are kept in a pool + and wait to be used again later. + + \section2 Example 2: Using QtConcurrent + + \snippet examples/tutorials/threads/helloconcurrent/helloconcurrent.cpp 1 + + We write a global function hello() to implement the work. QtConcurrent::run() + is used to run the function in another thread. The result is a QFuture. + QFuture provides a method called \l{QFuture::}{waitForFinished()}, which + blocks until the calculation is completed. The real power of QtConcurrent + becomes visible when data can be made available in a container. QtConcurrent + provides several functions that are able to process itemized data on all + available cores simultaneously. The use of QtConcurrent is very similar to + applying an STL algorithm to an STL container. + \l{examples-threadandconcurrent.html}{QtConcurrent Map} is a very short and + clear example about how a container of images can be scaled on all available + cores. The image scaling example uses the blocking variants of the functions + used. For every blocking function there is also a non-blocking, asynchronous + counterpart. Getting results asynchronously is implemented with QFuture and + QFutureWatcher. + + \section2 Example 3: Clock + + \image thread_clock.png "clock" + + We want to produce a clock application. The application has a GUI and a + worker thread. The worker thread checks every 10 milliseconds what time it + is. If the formatted time has changed, the result will be sent to the GUI + thread where it is displayed. + + Of course, this is an overly complicated way of designing a clock and, + actually, a separate thread is unnecessary. We would be better off placing + the timer in the main thread because the calculation made in the timer slot + is very short-lived. This example is purely for instructional use and shows + how to communicate from a worker thread to a GUI thread. Note that + communication in this direction is easy. We only need to add a signal + to QThread and make a queued signal/slot connection to the main thread. + Communication from the GUI to the worker thread is shown in the next + example. + + \snippet examples/tutorials/threads/clock/main.cpp 1 + + We've connected the \c clockThread with the label. The connection must be a + queued signal-slot connection because we want to put the call in the event + loop. + + \snippet examples/tutorials/threads/clock/clockthread.h 1 + + We have derived a class from QThread and declared the \c sendTime() signal. + + \snippet examples/tutorials/threads/clock/clockthread.cpp 1 + + The trickiest part of this example is that the timer is connected to its + slot via a direct connection. A default connection would produce a queued + signal-slot connection because the connected objects live in different + threads; remember that QThread does not live in the thread it creates. + + Still it is safe to access ClockThread::timerHit() from the worker thread + because ClockThread::timerHit() is private and only touches local variables + and a private member that isn't touched by public methods. + QDateTime::currentDateTime() isn't marked as thread-safe in Qt + documentation, however we can get away with using it in this small + example because we know that the QDateTime::currentDateTime() static + method isn't used in any other threads. + + \section2 Example 4: A Permanent Thread + + This example shows how it is possible to have a QObject in a worker thread + that accepts requests from the GUI thread, does polling using a timer and + continuously reports results back to the GUI thread. The actual work + including the polling must be implemented in a class derived from QObject. + We have called this class \c WorkerObject in the code shown below. The + thread-specific code is hidden in a class called \c Thread, derived from + QThread. + \c Thread has two additional public members. The \c launchWorker() member + takes the worker object and moves it to another thread with a started event + loop. + The call blocks for a very short moment until the thread creation operation + is completed, allowing the worker object to be used again on the next line. + The \c Thread class's code is short but somewhat involved, so we only show + how to use the class. + + \snippet examples/tutorials/threads/movedobject/main.cpp 1 + + QMetaObject::invokeMethod() calls a slot via the event loop. The worker + object's methods should not be called directly after the object has been + moved to another thread. We let the worker thread do some work and polling, + and use a timer to shut the application down after 3 seconds. Shutting the + worker down needs some care. We call \c{Thread::stop()} to exit the event + loop. We wait for the thread to terminate and, after this has occurred, we + delete the worker. + + \section1 Digging Deeper + + Threading is a very complicated subject. Qt offers more classes for + threading than we have presented in this tutorial. The following materials + can help you go into the subject in more depth: + + \list + \o Good video tutorials about threads with Qt can be found in the material + from the \l{Training Day at Qt Developer Days 2009}. + \o The \l{Thread Support in Qt} document is a good starting point into + the reference documentation. + \o Qt comes with several additional examples for + \l{Threading and Concurrent Programming Examples}{QThread and QtConcurrent}. + \o Several good books describe how to work with Qt threads. The most + extensive coverage can be found in \e{Advanced Qt Programming} by Mark + Summerfield, Prentice Hall - roughly 70 of 500 pages cover QThread and + QtConcurrent. + \endlist +*/ diff --git a/doc/src/dbus/qtdbus.qdoc b/doc/src/dbus/qtdbus.qdoc new file mode 100644 index 0000000000..fa91f67a85 --- /dev/null +++ b/doc/src/dbus/qtdbus.qdoc @@ -0,0 +1,40 @@ +/*! + \module QtDBus + \title QtDBus module + \ingroup modules + + \keyword QtDBus + \target The QDBus compiler + + \brief The QtDBus module is a Unix-only library that you can use + to perform Inter-Process Communication using the \l{D-Bus} protocol. + + Applications using the QtDBus module can provide services to + other, remote applications by exporting objects, as well as use + services exported by those applications by placing calls and + accessing properties. + + The QtDBus module provides an interface that extends the Qt \l + {signalsandslots.html}{Signals and Slots} mechanism, allowing one + to connect to a signal emitted remotely as well as to connect a + local signal to remote slot. + + To use this module, use the following code in your application: + + \snippet doc/src/snippets/code/doc_src_qtdbus.cpp 0 + + If you're using qmake to build your application, you can add this + line to your .pro file to make it link against the QtDBus + libraries: + + \snippet doc/src/snippets/code/doc_src_qtdbus.pro 1 + + \note The source code for this module is located in the \c{src/qdbus} + directory. When installing Qt from source, this module is built when Qt's + tools are built. + + See the \l {D-Bus} page for detailed information on + how to use this module. + + This module is part of all \l{Qt editions}. +*/ diff --git a/doc/src/files-and-resources/datastreamformat.qdoc b/doc/src/files-and-resources/datastreamformat.qdoc deleted file mode 100644 index 6fe888b52e..0000000000 --- a/doc/src/files-and-resources/datastreamformat.qdoc +++ /dev/null @@ -1,361 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page datastreamformat.html - \title Serializing Qt Data Types - \ingroup qt-network - \brief Representations of data types that can be serialized by QDataStream. - - The \l QDataStream allows you to serialize some of the Qt data types. - The table below lists the data types that QDataStream can serialize - and how they are represented. The format described below is - \l{QDataStream::setVersion()}{version 12}. - - It is always best to cast integers to a Qt integer type, such as - qint16 or quint32, when reading and writing. This ensures that - you always know exactly what size integers you are reading and - writing, no matter what the underlying platform and architecture - the application happens to be running on. - - \table - \row \o bool - \o \list - \o boolean - \endlist - \row \o qint8 - \o \list - \o signed byte - \endlist - \row \o qint16 - \o \list - \o signed 16-bit integer - \endlist - \row \o qint32 - \o \list - \o signed 32-bit integer - \endlist - \row \o qint64 - \o \list - \o signed 64-bit integer - \endlist - \row \o quint8 - \o \list - \o unsigned byte - \endlist - \row \o quint16 - \o \list - \o unsigned 16-bit integer - \endlist - \row \o quint32 - \o \list - \o unsigned 32-bit integer - \endlist - \row \o quint64 - \o \list - \o unsigned 64-bit integer - \endlist - \row \o \c float - \o \list - \o 32-bit floating point number using the standard IEEE 754 format - \endlist - \row \o \c double - \o \list - \o 64-bit floating point number using the standard IEEE 754 format - \endlist - \row \o \c {const char *} - \o \list - \o The string length (quint32) - \o The string bytes, excluding the terminating 0 - \endlist - \row \o QBitArray - \o \list - \o The array size (quint32) - \o The array bits, i.e. (size + 7)/8 bytes - \endlist - \row \o QBrush - \o \list - \o The brush style (quint8) - \o The brush color (QColor) - \o If style is CustomPattern, the brush pixmap (QPixmap) - \endlist - \row \o QByteArray - \o \list - \o If the byte array is null: 0xFFFFFFFF (quint32) - \o Otherwise: the array size (quint32) followed by the array bytes, i.e. size bytes - \endlist - \row \o \l QColor - \o \list - \o Color spec (qint8) - \o Alpha value (quint16) - \o Red value (quint16) - \o Green value (quint16) - \o Blue value (quint16) - \o Pad value (quint16) - \endlist - \row \o QCursor - \o \list - \o Shape ID (qint16) - \o If shape is BitmapCursor: The bitmap (QPixmap), mask (QPixmap), and hot spot (QPoint) - \endlist - \row \o QDate - \o \list - \o Julian day (quint32) - \endlist - \row \o QDateTime - \o \list - \o Date (QDate) - \o Time (QTime) - \o 0 for Qt::LocalTime, 1 for Qt::UTC (quint8) - \endlist - \row \o QEasingCurve - \o \list - \o type (quint8) - \o func (quint64) - \o hasConfig (bool) - \o If hasConfig is true then these fields follow: - \o list - \o period (double) - \o amplitude (double) - \o overshoot (double) - \endlist - \row \o QFont - \o \list - \o The family (QString) - \o The point size (qint16) - \o The style hint (quint8) - \o The char set (quint8) - \o The weight (quint8) - \o The font bits (quint8) - \endlist - \row \o QHash - \o \list - \o The number of items (quint32) - \o For all items, the key (Key) and value (T) - \endlist - \row \o QIcon - \o \list - \o The number of pixmap entries (quint32) - \o For all pixmap entries: - \list - \o The pixmap (QPixmap) - \o The file name (QString) - \o The pixmap size (QSize) - \o The \l{QIcon::Mode}{mode} (quint32) - \o The \l{QIcon::State}{state} (quint32) - \endlist - \endlist - \row \o QImage - \o \list - \o If the image is null a "null image" marker is saved; - otherwise the image is saved in PNG or BMP format (depending - on the stream version). If you want control of the format, - stream the image into a QBuffer (using QImageIO) and stream - that. - \endlist - \row \o QKeySequence - \o \list - \o A QList, where each integer is a key in the key sequence - \endlist - \row \o QLinkedList - \o \list - \o The number of items (quint32) - \o The items (T) - \endlist - \row \o QList - \o \list - \o The number of items (quint32) - \o The items (T) - \endlist - \row \o QMap - \o \list - \o The number of items (quint32) - \o For all items, the key (Key) and value (T) - \endlist - \row \o QMatrix - \o \list - \o m11 (double) - \o m12 (double) - \o m21 (double) - \o m22 (double) - \o dx (double) - \o dy (double) - \endlist - \row \o QMatrix4x4 - \o \list - \o m11 (double) - \o m12 (double) - \o m13 (double) - \o m14 (double) - \o m21 (double) - \o m22 (double) - \o m23 (double) - \o m24 (double) - \o m31 (double) - \o m32 (double) - \o m33 (double) - \o m34 (double) - \o m41 (double) - \o m42 (double) - \o m43 (double) - \o m44 (double) - \endlist - \row \o QPair - \o \list - \o first (T1) - \o second (T2) - \endlist - \row \o QPalette - \o The disabled, active, and inactive color groups, each of which consists - of the following: - \list - \o foreground (QBrush) - \o button (QBrush) - \o light (QBrush) - \o midlight (QBrush) - \o dark (QBrush) - \o mid (QBrush) - \o text (QBrush) - \o brightText (QBrush) - \o buttonText (QBrush) - \o base (QBrush) - \o background (QBrush) - \o shadow (QBrush) - \o highlight (QBrush) - \o highlightedText (QBrush) - \o link (QBrush) - \o linkVisited (QBrush) - \endlist - \row \o QPen - \o \list - \o The pen styles (quint8) - \o The pen width (quint16) - \o The pen color (QColor) - \endlist - \row \o QPicture - \o \list - \o The size of the picture data (quint32) - \o The raw bytes of picture data (char) - \endlist - \row \o QPixmap - \o \list - \o Save it as a PNG image. - \endlist - \row \o QPoint - \o \list - \o The x coordinate (qint32) - \o The y coordinate (qint32) - \endlist - \row \o QQuaternion - \o \list - \o The scalar component (double) - \o The x coordinate (double) - \o The y coordinate (double) - \o The z coordinate (double) - \endlist - \row \o QRect - \o \list - \o left (qint32) - \o top (qint32) - \o right (qint32) - \o bottom (qint32) - \endlist - \row \o QRegExp - \o \list - \o The regexp pattern (QString) - \o Case sensitivity (quint8) - \o Regular expression syntax (quint8) - \o Minimal matching (quint8) - \endlist - \row \o QRegion - \o \list - \o The size of the data, i.e. 8 + 16 * (number of rectangles) (quint32) - \o 10 (qint32) - \o The number of rectangles (quint32) - \o The rectangles in sequential order (QRect) - \endlist - \row \o QSize - \o \list - \o width (qint32) - \o height (qint32) - \endlist - \row \o QString - \o \list - \o If the string is null: 0xFFFFFFFF (quint32) - \o Otherwise: The string length in bytes (quint32) followed by the data in UTF-16 - \endlist - \row \o QTime - \o \list - \o Milliseconds since midnight (quint32) - \endlist - \row \o QTransform - \o \list - \o m11 (double) - \o m12 (double) - \o m13 (double) - \o m21 (double) - \o m22 (double) - \o m23 (double) - \o m31 (double) - \o m32 (double) - \o m33 (double) - \endlist - \row \o QUrl - \o \list - \o Holds an URL (QString) - \endlist - \row \o QVariant - \o \list - \o The type of the data (quint32) - \o The null flag (qint8) - \o The data of the specified type - \endlist - \row \o QVector2D - \o \list - \o the x coordinate (double) - \o the y coordinate (double) - \endlist - \row \o QVector3D - \o \list - \o the x coordinate (double) - \o the y coordinate (double) - \o the z coordinate (double) - \endlist - \row \o QVector4D - \o \list - \o the x coordinate (double) - \o the y coordinate (double) - \o the z coordinate (double) - \o the w coordinate (double) - \endlist - \row \o QVector - \o \list - \o The number of items (quint32) - \o The items (T) - \endlist - \endtable -*/ diff --git a/doc/src/files-and-resources/resources.qdoc b/doc/src/files-and-resources/resources.qdoc deleted file mode 100644 index d6e320bf04..0000000000 --- a/doc/src/files-and-resources/resources.qdoc +++ /dev/null @@ -1,214 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group io - \title Input/Output and Networking - \ingroup groups - - \brief Classes providing file input and output along with directory and - network handling. - - These classes are used to handle input and output to and from external - devices, processes, files etc. as well as manipulating files and directories. -*/ - -/*! - \page resources.html - \title The Qt Resource System - \ingroup qt-network - \brief A platform-independent mechanism for storing binary files in an application. - - \keyword resource system - - The Qt resource system is a platform-independent mechanism for - storing binary files in the application's executable. This is - useful if your application always needs a certain set of files - (icons, translation files, etc.) and you don't want to run the - risk of losing the files. - - The resource system is based on tight cooperation between \l qmake, - \l rcc (Qt's resource compiler), and QFile. It obsoletes Qt 3's - \c qembed tool and the - \l{http://qt.nokia.com/doc/qq/qq05-iconography.html#imagestorage}{image - collection} mechanism. - - \section1 Resource Collection Files (\c{.qrc}) - - The resources associated with an application are specified in a - \c .qrc file, an XML-based file format that lists files on the - disk and optionally assigns them a resource name that the - application must use to access the resource. - - Here's an example \c .qrc file: - - \quotefile mainwindows/application/application.qrc - - The resource files listed in the \c .qrc file are files that are - part of the application's source tree. The specified paths are - relative to the directory containing the \c .qrc file. Note that - the listed resource files must be located in the same directory as - the \c .qrc file, or one of its subdirectories. - - Resource data can either be compiled into the binary and thus accessed - immediately in application code, or a binary resource can be created - and at a later point in application code registered with the resource - system. - - By default, resources are accessible in the application under the - same file name as they have in the source tree, with a \c :/ prefix, - or by a \link QUrl URL\endlink with a \c qrc scheme. - - For example, the file path \c :/images/cut.png or the URL - \c qrc:///images/cut.png would give access to the - \c cut.png file, whose location in the application's source tree - is \c images/cut.png. This can be changed using the \c file tag's - \c alias attribute: - - \snippet doc/src/snippets/code/doc_src_resources.qdoc 0 - - The file is then accessible as \c :/cut-img.png from the - application. It is also possible to specify a path prefix for all - files in the \c .qrc file using the \c qresource tag's \c prefix - attribute: - - \snippet doc/src/snippets/code/doc_src_resources.qdoc 1 - - In this case, the file is accessible as \c - :/myresources/cut-img.png. - - Some resources, such as translation files and icons, many need to - change based on the user's locale. This is done by adding a \c lang - attribute to the \c qresource tag, specifying a suitable locale - string. For example: - - \snippet doc/src/snippets/code/doc_src_resources.qdoc 2 - - If the user's locale is French (i.e., QLocale::system().name() returns - "fr_FR"), \c :/cut.jpg becomes a reference to the \c cut_fr.jpg - image. For other locales, \c cut.jpg is used. - - See the QLocale documentation for a description of the format to use - for locale strings. - - - \section2 External Binary Resources - - For an external binary resource to be created you must create the resource - data (commonly given the \c .rcc extension) by passing the -binary switch to - \l rcc. Once the binary resource is created you can register the resource - with the QResource API. - - For example, a set of resource data specified in a \c .qrc file can be - compiled in the following way: - - \snippet doc/src/snippets/code/doc_src_resources.qdoc 3 - - In the application, this resource would be registered with code like this: - - \snippet doc/src/snippets/code/doc_src_resources.cpp 4 - - \section2 Compiled-In Resources - - For a resource to be compiled into the binary the \c .qrc file must be - mentioned in the application's \c .pro file so that \c qmake knows - about it. For example: - - \snippet examples/mainwindows/application/application.pro 0 - - \c qmake will produce make rules to generate a file called \c - qrc_application.cpp that is linked into the application. This - file contains all the data for the images and other resources as - static C++ arrays of compressed binary data. The \c - qrc_application.cpp file is automatically regenerated whenever - the \c .qrc file changes or one of the files that it refers to - changes. If you don't use \c .pro files, you can either invoke - \c rcc manually or add build rules to your build system. - - \image resources.png Building resources into an application - - Currently, Qt always stores the data directly in the executable, - even on Windows and Mac OS X, where the operating system provides - native support for resources. This might change in a future Qt - release. - - \section1 Compression - - Resources are compressed by default (in the \c ZIP format). It is - possible to turn off compression. This can be useful if your - resources already contain a compressed format, such as \c .png - files. You do this by giving the \c {-no-compress} command line - argument. - - \code - rcc -no-compress myresources.qrc - \endcode - - \c rcc also gives you some control over the compression. You can - specify the compression level and the threshold level to consider - while compressing files, for example: - - \code - rcc -compress 2 -threshold 3 myresources.qrc - \endcode - - \section1 Using Resources in the Application - - In the application, resource paths can be used in most places - instead of ordinary file system paths. In particular, you can - pass a resource path instead of a file name to the QIcon, QImage, - or QPixmap constructor: - - \snippet examples/mainwindows/application/mainwindow.cpp 21 - - See the \l{mainwindows/application}{Application} example for an - actual application that uses Qt's resource system to store its - icons. - - In memory, resources are represented by a tree of resource - objects. The tree is automatically built at startup and used by - QFile for resolving paths to resources. You can use a QDir initialized - with ":/" to navigate through the resource tree from the root. - - Qt's resources support the concept of a search path list. If you then - refer to a resource with \c : instead of \c :/ as the prefix, the - resource will be looked up using the search path list. The search - path list is empty at startup; call QDir::addSearchPath() to - add paths to it. - - If you have resources in a static library, you might need to - force initialization of your resources by calling \l - Q_INIT_RESOURCE() with the base name of the \c .qrc file. For - example: - - \snippet doc/src/snippets/code/doc_src_resources.cpp 5 - - Similarly, if you must unload a set of resources explicitly - (because a plugin is being unloaded or the resources are not valid - any longer), you can force removal of your resources by calling - Q_CLEANUP_RESOURCE() with the same base name as above. -*/ diff --git a/doc/src/gui/coordsys.qdoc b/doc/src/gui/coordsys.qdoc new file mode 100644 index 0000000000..96eebd01e0 --- /dev/null +++ b/doc/src/gui/coordsys.qdoc @@ -0,0 +1,461 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page coordsys.html + \title Coordinate System + \ingroup qt-graphics + \ingroup best-practices + \brief Information about the coordinate system used by the paint + system. + + The coordinate system is controlled by the QPainter + class. Together with the QPaintDevice and QPaintEngine classes, + QPainter form the basis of Qt's painting system, Arthur. QPainter + is used to perform drawing operations, QPaintDevice is an + abstraction of a two-dimensional space that can be painted on + using a QPainter, and QPaintEngine provides the interface that the + painter uses to draw onto different types of devices. + + The QPaintDevice class is the base class of objects that can be + painted: Its drawing capabilities are inherited by the QWidget, + QPixmap, QPicture, QImage, and QPrinter classes. The default + coordinate system of a paint device has its origin at the top-left + corner. The \e x values increase to the right and the \e y values + increase downwards. The default unit is one pixel on pixel-based + devices and one point (1/72 of an inch) on printers. + + The mapping of the logical QPainter coordinates to the physical + QPaintDevice coordinates are handled by QPainter's transformation + matrix, viewport and "window". The logical and physical coordinate + systems coincide by default. QPainter also supports coordinate + transformations (e.g. rotation and scaling). + + \tableofcontents + + \section1 Rendering + + \section2 Logical Representation + + The size (width and height) of a graphics primitive always + correspond to its mathematical model, ignoring the width of the + pen it is rendered with: + + \table + \row + \o \inlineimage coordinatesystem-rect.png + \o \inlineimage coordinatesystem-line.png + \row + \o QRect(1, 2, 6, 4) + \o QLine(2, 7, 6, 1) + \endtable + + \section2 Aliased Painting + + When drawing, the pixel rendering is controlled by the + QPainter::Antialiasing render hint. + + The \l {QPainter::RenderHint}{RenderHint} enum is used to specify + flags to QPainter that may or may not be respected by any given + engine. The QPainter::Antialiasing value indicates that the engine + should antialias edges of primitives if possible, i.e. smoothing + the edges by using different color intensities. + + But by default the painter is \e aliased and other rules apply: + When rendering with a one pixel wide pen the pixels will be + rendered to the \e {right and below the mathematically defined + points}. For example: + + \table + \row + \o \inlineimage coordinatesystem-rect-raster.png + \o \inlineimage coordinatesystem-line-raster.png + + \row + \o + \snippet doc/src/snippets/code/doc_src_coordsys.cpp 0 + + \o + \snippet doc/src/snippets/code/doc_src_coordsys.cpp 1 + \endtable + + When rendering with a pen with an even number of pixels, the + pixels will be rendered symetrically around the mathematical + defined points, while rendering with a pen with an odd number of + pixels, the spare pixel will be rendered to the right and below + the mathematical point as in the one pixel case. See the QRectF + diagrams below for concrete examples. + + \table + \header + \o {3,1} QRectF + \row + \o \inlineimage qrect-diagram-zero.png + \o \inlineimage qrectf-diagram-one.png + \row + \o Logical representation + \o One pixel wide pen + \row + \o \inlineimage qrectf-diagram-two.png + \o \inlineimage qrectf-diagram-three.png + \row + \o Two pixel wide pen + \o Three pixel wide pen + \endtable + + Note that for historical reasons the return value of the + QRect::right() and QRect::bottom() functions deviate from the true + bottom-right corner of the rectangle. + + QRect's \l {QRect::right()}{right()} function returns \l + {QRect::left()}{left()} + \l {QRect::width()}{width()} - 1 and the + \l {QRect::bottom()}{bottom()} function returns \l + {QRect::top()}{top()} + \l {QRect::height()}{height()} - 1. The + bottom-right green point in the diagrams shows the return + coordinates of these functions. + + We recommend that you simply use QRectF instead: The QRectF class + defines a rectangle in the plane using floating point coordinates + for accuracy (QRect uses integer coordinates), and the + QRectF::right() and QRectF::bottom() functions \e do return the + true bottom-right corner. + + Alternatively, using QRect, apply \l {QRect::x()}{x()} + \l + {QRect::width()}{width()} and \l {QRect::y()}{y()} + \l + {QRect::height()}{height()} to find the bottom-right corner, and + avoid the \l {QRect::right()}{right()} and \l + {QRect::bottom()}{bottom()} functions. + + \section2 Anti-aliased Painting + + If you set QPainter's \l {QPainter::Antialiasing}{anti-aliasing} + render hint, the pixels will be rendered symetrically on both + sides of the mathematically defined points: + + \table + \row + \o \inlineimage coordinatesystem-rect-antialias.png + \o \inlineimage coordinatesystem-line-antialias.png + \row + \o + + \snippet doc/src/snippets/code/doc_src_coordsys.cpp 2 + + \o + \snippet doc/src/snippets/code/doc_src_coordsys.cpp 3 + \endtable + + \section1 Transformations + + By default, the QPainter operates on the associated device's own + coordinate system, but it also has complete support for affine + coordinate transformations. + + You can scale the coordinate system by a given offset using the + QPainter::scale() function, you can rotate it clockwise using the + QPainter::rotate() function and you can translate it (i.e. adding + a given offset to the points) using the QPainter::translate() + function. + + \table + \row + \o \inlineimage qpainter-clock.png + \o \inlineimage qpainter-rotation.png + \o \inlineimage qpainter-scale.png + \o \inlineimage qpainter-translation.png + \row + \o nop + \o \l {QPainter::rotate()}{rotate()} + \o \l {QPainter::scale()}{scale()} + \o \l {QPainter::translate()}{translate()} + \endtable + + You can also twist the coordinate system around the origin using + the QPainter::shear() function. See the \l {painting/affine}{Affine + Transformations} example for a visualization of a sheared coordinate + system. All the transformation operations operate on QPainter's + transformation matrix that you can retrieve using the + QPainter::worldTransform() function. A matrix transforms a point + in the plane to another point. + + If you need the same transformations over and over, you can also + use QTransform objects and the QPainter::worldTransform() and + QPainter::setWorldTransform() functions. You can at any time save the + QPainter's transformation matrix by calling the QPainter::save() + function which saves the matrix on an internal stack. The + QPainter::restore() function pops it back. + + One frequent need for the transformation matrix is when reusing + the same drawing code on a variety of paint devices. Without + transformations, the results are tightly bound to the resolution + of the paint device. Printers have high resolution, e.g. 600 dots + per inch, whereas screens often have between 72 and 100 dots per + inch. + + \table 100% + \header + \o {2,1} Analog Clock Example + \row + \o \inlineimage coordinatesystem-analogclock.png + \o + The Analog Clock example shows how to draw the contents of a + custom widget using QPainter's transformation matrix. + + Qt's example directory provides a complete walk-through of the + example. Here, we will only review the example's \l + {QWidget::paintEvent()}{paintEvent()} function to see how we can + use the transformation matrix (i.e. QPainter's matrix functions) + to draw the clock's face. + + We recommend compiling and running this example before you read + any further. In particular, try resizing the window to different + sizes. + + \row + \o {2,1} + + \snippet examples/widgets/analogclock/analogclock.cpp 9 + + First, we set up the painter. We translate the coordinate system + so that point (0, 0) is in the widget's center, instead of being + at the top-left corner. We also scale the system by \c side / 100, + where \c side is either the widget's width or the height, + whichever is shortest. We want the clock to be square, even if the + device isn't. + + This will give us a 200 x 200 square area, with the origin (0, 0) + in the center, that we can draw on. What we draw will show up in + the largest possible square that will fit in the widget. + + See also the \l {Window-Viewport Conversion} section. + + \snippet examples/widgets/analogclock/analogclock.cpp 18 + + We draw the clock's hour hand by rotating the coordinate system + and calling QPainter::drawConvexPolygon(). Thank's to the + rotation, it's drawn pointed in the right direction. + + The polygon is specified as an array of alternating \e x, \e y + values, stored in the \c hourHand static variable (defined at the + beginning of the function), which corresponds to the four points + (2, 0), (0, 2), (-2, 0), and (0, -25). + + The calls to QPainter::save() and QPainter::restore() surrounding + the code guarantees that the code that follows won't be disturbed + by the transformations we've used. + + \snippet examples/widgets/analogclock/analogclock.cpp 24 + + We do the same for the clock's minute hand, which is defined by + the four points (1, 0), (0, 1), (-1, 0), and (0, -40). These + coordinates specify a hand that is thinner and longer than the + minute hand. + + \snippet examples/widgets/analogclock/analogclock.cpp 27 + + Finally, we draw the clock face, which consists of twelve short + lines at 30-degree intervals. At the end of that, the painter is + rotated in a way which isn't very useful, but we're done with + painting so that doesn't matter. + \endtable + + For a demonstation of Qt's ability to perform affine + transformations on painting operations, see the \l + {painting/affine}{Affine Transformations} example which allows the user + to experiment with the transformation operations. See also the \l + {painting/transformations}{Transformations} example which shows + how transformations influence the way that QPainter renders + graphics primitives. In particular, it shows how the order of + transformations affects the result. + + For more information about the transformation matrix, see the + QTransform documentation. + + \section1 Window-Viewport Conversion + + When drawing with QPainter, we specify points using logical + coordinates which then are converted into the physical coordinates + of the paint device. + + The mapping of the logical coordinates to the physical coordinates + are handled by QPainter's world transformation \l + {QPainter::worldTransform()}{worldTransform()} (described in the \l + Transformations section), and QPainter's \l + {QPainter::viewport()}{viewport()} and \l + {QPainter::window()}{window()}. The viewport represents the + physical coordinates specifying an arbitrary rectangle. The + "window" describes the same rectangle in logical coordinates. By + default the logical and physical coordinate systems coincide, and + are equivalent to the paint device's rectangle. + + Using window-viewport conversion you can make the logical + coordinate system fit your preferences. The mechanism can also be + used to make the drawing code independent of the paint device. You + can, for example, make the logical coordinates extend from (-50, + -50) to (50, 50) with (0, 0) in the center by calling the + QPainter::setWindow() function: + + \snippet doc/src/snippets/code/doc_src_coordsys.cpp 4 + + Now, the logical coordinates (-50,-50) correspond to the paint + device's physical coordinates (0, 0). Independent of the paint + device, your painting code will always operate on the specified + logical coordinates. + + By setting the "window" or viewport rectangle, you perform a + linear transformation of the coordinates. Note that each corner of + the "window" maps to the corresponding corner of the viewport, and + vice versa. For that reason it normally is a good idea to let the + viewport and "window" maintain the same aspect ratio to prevent + deformation: + + \snippet doc/src/snippets/code/doc_src_coordsys.cpp 5 + + If we make the logical coordinate system a square, we should also + make the viewport a square using the QPainter::setViewport() + function. In the example above we make it equivalent to the + largest square that fit into the paint device's rectangle. By + taking the paint device's size into consideration when setting the + window or viewport, it is possible to keep the drawing code + independent of the paint device. + + Note that the window-viewport conversion is only a linear + transformation, i.e. it does not perform clipping. This means that + if you paint outside the currently set "window", your painting is + still transformed to the viewport using the same linear algebraic + approach. + + \image coordinatesystem-transformations.png + + The viewport, "window" and transformation matrix determine how + logical QPainter coordinates map to the paint device's physical + coordinates. By default the world transformation matrix is the + identity matrix, and the "window" and viewport settings are + equivalent to the paint device's settings, i.e. the world, + "window" and device coordinate systems are equivalent, but as we + have seen, the systems can be manipulated using transformation + operations and window-viewport conversion. The illustration above + describes the process. + + \omit + \section1 Related Classes + + Qt's paint system, Arthur, is primarily based on the QPainter, + QPaintDevice, and QPaintEngine classes: + + \table + \header \o Class \o Description + \row + \o QPainter + \o + The QPainter class performs low-level painting on widgets and + other paint devices. QPainter can operate on any object that + inherits the QPaintDevice class, using the same code. + \row + \o QPaintDevice + \o + The QPaintDevice class is the base class of objects that can be + painted. Qt provides several devices: QWidget, QImage, QPixmap, + QPrinter and QPicture, and other devices can also be defined by + subclassing QPaintDevice. + \row + \o QPaintEngine + \o + The QPaintEngine class provides an abstract definition of how + QPainter draws to a given device on a given platform. Qt 4 + provides several premade implementations of QPaintEngine for the + different painter backends we support; it provides one paint + engine for each supported window system and painting + frameworkt. You normally don't need to use this class directly. + \endtable + + The 2D transformations of the coordinate system are specified + using the QTransform class: + + \table + \header \o Class \o Description + \row + \o QTransform + \o + A 3 x 3 transformation matrix. Use QTransform to rotate, shear, + scale, or translate the coordinate system. + \endtable + + In addition Qt provides several graphics primitive classes. Some + of these classes exist in two versions: an \c{int}-based version + and a \c{qreal}-based version. For these, the \c qreal version's + name is suffixed with an \c F. + + \table + \header \o Class \o Description + \row + \o \l{QPoint}(\l{QPointF}{F}) + \o + A single 2D point in the coordinate system. Most functions in Qt + that deal with points can accept either a QPoint, a QPointF, two + \c{int}s, or two \c{qreal}s. + \row + \o \l{QSize}(\l{QSizeF}{F}) + \o + A single 2D vector. Internally, QPoint and QSize are the same, but + a point is not the same as a size, so both classes exist. Again, + most functions accept either QSizeF, a QSize, two \c{int}s, or two + \c{qreal}s. + \row + \o \l{QRect}(\l{QRectF}{F}) + \o + A 2D rectangle. Most functions accept either a QRectF, a QRect, + four \c{int}s, or four \c {qreal}s. + \row + \o \l{QLine}(\l{QLineF}{F}) + \o + A 2D finite-length line, characterized by a start point and an end + point. + \row + \o \l{QPolygon}(\l{QPolygonF}{F}) + \o + A 2D polygon. A polygon is a vector of \c{QPoint(F)}s. If the + first and last points are the same, the polygon is closed. + \row + \o QPainterPath + \o + A vectorial specification of a 2D shape. Painter paths are the + ultimate painting primitive, in the sense that any shape + (rectange, ellipse, spline) or combination of shapes can be + expressed as a path. A path specifies both an outline and an area. + \row + \o QRegion + \o + An area in a paint device, expressed as a list of + \l{QRect}s. In general, we recommend using the vectorial + QPainterPath class instead of QRegion for specifying areas, + because QPainterPath handles painter transformations much better. + \endtable + \endomit + + \sa {Analog Clock Example}, {Transformations Example} +*/ diff --git a/doc/src/gui/paintsystem.qdoc b/doc/src/gui/paintsystem.qdoc new file mode 100644 index 0000000000..a567509186 --- /dev/null +++ b/doc/src/gui/paintsystem.qdoc @@ -0,0 +1,560 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group painting + \title Painting Classes + \ingroup groups + + \brief Classes that provide support for painting. + + See also this introduction to the \link coordsys.html Qt + coordinate system. \endlink +*/ + +/*! + \group painting-3D + \title Rendering in 3D + \ingroup groups + + \brief Classes that provide support for rendering in 3D. +*/ + +/*! + \page paintsystem.html + \title Paint System + \brief A system for painting on the screen or on print devices using the same API + \ingroup qt-graphics + \ingroup frameworks-technologies + \ingroup qt-basic-concepts + + + Qt's paint system enables painting on screen and print devices + using the same API, and is primarily based on the QPainter, + QPaintDevice, and QPaintEngine classes. + + QPainter is used to perform drawing operations, QPaintDevice is an + abstraction of a two-dimensional space that can be painted on + using a QPainter, and QPaintEngine provides the interface that the + painter uses to draw onto different types of devices. The + QPaintEngine class is used internally by QPainter and + QPaintDevice, and is hidden from application programmers unless + they create their own device type. + + \image paintsystem-core.png + + The main benefit of this approach is that all painting follows the + same painting pipeline making it easy to add support for new + features and providing default implementations for unsupported + ones. + + \section1 Topics + \list + \o \l{Classes for Painting} + \o \l{Paint Devices and Backends} + \o \l{Drawing and Filling} + \o \l{Coordinate System} + \o \l{Reading and Writing Image Files} + \o \l{Styling} + \o \l{Printing with Qt} + \endlist + + \section1 Classes for Painting + + These classes provide support for painting onto a paint device. + + \annotatedlist painting + + Alternatively, Qt provides the QtOpenGL module, offering classes + that makes it easy to use OpenGL in Qt applications. Among others, + the module provides an OpenGL widget class that can be used just + like any other Qt widget, except that it opens an OpenGL display + buffer where the OpenGL API can be used to render the contents. +*/ + + +/*! + \page paintsystem-devices.html + \title Paint Devices and Backends + + \contentspage The Paint System + \nextpage Drawing and Filling + + \section1 Creating a Paint Device + + The QPaintDevice class is the base class of objects that can be + painted, i.e. QPainter can draw on any QPaintDevice + subclass. QPaintDevice's drawing capabilities are currently + implemented by the QWidget, QImage, QPixmap, QGLWidget, + QGLPixelBuffer, QPicture and QPrinter subclasses. + + \image paintsystem-devices.png + + \table 100% + \row \o \bold Widget + + The QWidget class is the base class of all user interface + objects. The widget is the atom of the user interface: it receives + mouse, keyboard and other events from the window system, and + paints a representation of itself on the screen. + + \row \o \bold Image + + The QImage class provides a hardware-independent image + representation which is designed and optimized for I/O, and for + direct pixel access and manipulation. QImage supports several + image formats including monochrome, 8-bit, 32-bit and + alpha-blended images. + + One advantage of using QImage as a paint device is that it is + possible to guarantee the pixel exactness of any drawing operation + in a platform-independent way. Another benefit is that the + painting can be performed in another thread than the current GUI + thread. + + \row \o \bold Pixmap + + The QPixmap class is an off-screen image representation which is + designed and optimized for showing images on screen. Unlike + QImage, the pixel data in a pixmap is internal and is managed by + the underlying window system, i.e. pixels can only be accessed + through QPainter functions or by converting the QPixmap to a + QImage. + + To optimize drawing with QPixmap, Qt provides the QPixmapCache + class which can be used to store temporary pixmaps that are + expensive to generate without using more storage space than the + cache limit. + + Qt also provides the QBitmap convenience class, inheriting + QPixmap. QBitmap guarantees monochrome (1-bit depth) pixmaps, and + is mainly used for creating custom QCursor and QBrush objects, + constructing QRegion objects, and for setting masks for pixmaps + and widgets. + + \row \o \bold {OpenGL Widget} + + As mentioned previously, Qt provides the QtOpenGL module offering + classes that makes it easy to use OpenGL in Qt applications. For + example, the QGLWidget enables the OpenGL API for + rendering. + + But QGLWidget is also a QWidget subclass, and can be used by + QPainter as any other paint device. One huge benefit from this is + that it enables Qt to utilize the high performance of OpenGL for + most drawing operations, such as transformations and pixmap + drawing. + + \row \o \bold {Pixel Buffer} + + The QtOpenGL module also provides the QGLPixelBuffer class which + inherits QPaintDevice directly. + + QGLPixelBuffer encapsulates an OpenGL pbuffer. Rendering into a + pbuffer is normally done using full hardware acceleration which + can be significantly faster than rendering into a QPixmap. + + \row \o \bold {Framebuffer Object} + + The QtOpenGL module also provides the QGLFramebufferObject class + which inherits QPaintDevice directly. + + QGLFramebufferObject encapsulates an OpenGL framebuffer object. + Framebuffer objects can also be used for off-screen rendering, and + offer several advantages over pixel buffers for this purpose. + These are described in the QGLFramebufferObject class documentation. + + \row \o \bold {Picture} + + The QPicture class is a paint device that records and replays + QPainter commands. A picture serializes painter commands to an IO + device in a platform-independent format. QPicture is also + resolution independent, i.e. a QPicture can be displayed on + different devices (for example svg, pdf, ps, printer and screen) + looking the same. + + Qt provides the QPicture::load() and QPicture::save() functions + as well as streaming operators for loading and saving pictures. + + \row \o \bold {Printer} + + The QPrinter class is a paint device that paints on a printer. On + Windows or Mac OS X, QPrinter uses the built-in printer + drivers. On X11, QPrinter generates postscript and sends that to + lpr, lp, or another print program. QPrinter can also print to any + other QPrintEngine object. + + The QPrintEngine class defines an interface for how QPrinter + interacts with a given printing subsystem. The common case when + creating your own print engine, is to derive from both + QPaintEngine and QPrintEngine. + + The output format is by default determined by the platform the + printer is running on, but by explicitly setting the output format + to QPrinter::PdfFormat, QPrinter will generate its output as a PDF + file. + + \row \o \bold {Custom Backends} + + Support for a new backend can be implemented by deriving from the + QPaintDevice class and reimplementing the virtual + QPaintDevice::paintEngine() function to tell QPainter which paint + engine should be used to draw on this particular device. To + actually be able to draw on the device, this paint engine must be + a custom paint engine created by deriving from the QPaintEngine + class. + + \endtable + + \section1 Selecting the Painting Backend + + Since Qt 4.5, it is possible to replace the paint engines and paint + devices used for widgets, pixmaps and the offscreen double buffer. By + default the backends are: + + \table + \row + \o Windows + \o Software Rasterizer + \row + \o X11 + \o X11 + \row + \o Mac OS X + \o CoreGraphics + \row + \o Embedded + \o Software Rasterizer + \endtable + + Passing a command line parameter to the application, such as, + \c{-graphicssystem raster}, specifies that Qt should use the software + rasterizer for this application. The Software rasterizer is fully + supported on all platforms. + + \code + > analogclock -graphicssystem raster + \endcode + + There is also a \c{-graphicssystem opengl} mode that uses OpenGL for + all drawing. Currently, this engine is experimental as it does not draw + everything correctly. + + Qt also supports being configured using \c {-graphicssystem + raster|opengl} in which case all applications will use the + specified graphics system for its graphics. +*/ + +/*! + \page paintsystem-drawing.html + \title Drawing and Filling + + \previouspage Paint Devices and Backends + \contentspage The Paint System + \nextpage Coordinate System + + \section1 Drawing + + QPainter provides highly optimized functions to do most of the + drawing GUI programs require. It can draw everything from simple + graphical primitives (represented by the QPoint, QLine, QRect, + QRegion and QPolygon classes) to complex shapes like vector + paths. In Qt vector paths are represented by the QPainterPath + class. QPainterPath provides a container for painting operations, + enabling graphical shapes to be constructed and reused. + + \table 100% + \row + \o \image paintsystem-painterpath.png + \o \bold QPainterPath + + A painter path is an object composed of lines and curves. For + example, a rectangle is composed by lines and an ellipse is + composed by curves. + + The main advantage of painter paths over normal drawing operations + is that complex shapes only need to be created once; then they can + be drawn many times using only calls to the QPainter::drawPath() + function. + + A QPainterPath object can be used for filling, outlining, and + clipping. To generate fillable outlines for a given painter path, + use the QPainterPathStroker class. + + \endtable + + Lines and outlines are drawn using the QPen class. A pen is + defined by its style (i.e. its line-type), width, brush, how the + endpoints are drawn (cap-style) and how joins between two + connected lines are drawn (join-style). The pen's brush is a + QBrush object used to fill strokes generated with the pen, + i.e. the QBrush class defines the fill pattern. + + QPainter can also draw aligned text and pixmaps. + + When drawing text, the font is specified using the QFont class. Qt + will use the font with the specified attributes, or if no matching + font exists, Qt will use the closest matching installed font. The + attributes of the font that is actually used can be retrieved + using the QFontInfo class. In addition, the QFontMetrics class + provides the font measurements, and the QFontDatabase class + provides information about the fonts available in the underlying + window system. + + Normally, QPainter draws in a "natural" coordinate system, but it + is able to perform view and world transformations using the + QTransform class. For more information, see \l {Coordinate + System}, which also describes the rendering process, i.e. the + relation between the logical representation and the rendered + pixels, and the benefits of anti-aliased painting. + + \table 100% + \row \o + \bold {Anti-Aliased Painting} + + When drawing, the pixel rendering is controlled by the + QPainter::Antialiasing render hint. The QPainter::RenderHint enum + is used to specify flags to QPainter that may or may not be + respected by any given engine. + + The QPainter::Antialiasing value indicates that the engine should + antialias edges of primitives if possible, i.e. smoothing the + edges by using different color intensities. + + \o \image paintsystem-antialiasing.png + + \endtable + + \section1 Filling + + Shapes are filled using the QBrush class. A brush is defined + by its color and its style (i.e. its fill pattern). + + Any color in Qt is represented by the QColor class which supports + the RGB, HSV and CMYK color models. QColor also support + alpha-blended outlining and filling (specifying the transparency + effect), and the class is platform and device independent (the + colors are mapped to hardware using the QColormap class). For more + information, see the QColor class documentation. + + When creating a new widget, it is recommend to use the colors in + the widget's palette rather than hard-coding specific colors. All + widgets in Qt contain a palette and use their palette to draw + themselves. A widget's palette is represented by the QPalette + class which contains color groups for each widget state. + + The available fill patterns are described by the Qt::BrushStyle + enum. These include basic patterns spanning from uniform color to + very sparse pattern, various line combinations, gradient fills and + textures. Qt provides the QGradient class to define custom + gradient fills, while texture patterns are specified using the + QPixmap class. + + \table 100% + \row + \o \image paintsystem-fancygradient.png + \o \bold QGradient + + The QGradient class is used in combination with QBrush to specify + gradient fills. + + \image paintsystem-gradients.png + + Qt currently supports three types of gradient fills: Linear + gradients interpolate colors between start and end points, radial + gradients interpolate colors between a focal point and end points + on a circle surrounding it, and conical gradients interpolate + colors around a center point. + + \endtable +*/ + +/*! + \page paintsystem-images.html + \title Reading and Writing Image Files + + \previouspage Coordinate System + \contentspage The Paint System + \nextpage Styling + + The most common way to read images is through QImage and QPixmap's + constructors, or by calling the QImage::load() and QPixmap::load() + functions. In addition, Qt provides the QImageReader class which + gives more control over the process. Depending on the underlying + support in the image format, the functions provided by the class + can save memory and speed up loading of images. + + Likewise, Qt provides the QImageWriter class which supports + setting format specific options, such as the gamma level, + compression level and quality, prior to storing the image. If you + do not need such options, you can use QImage::save() or + QPixmap::save() instead. + + \table 100% + \row + \o \bold QMovie + + QMovie is a convenience class for displaying animations, using the + QImageReader class internally. Once created, the QMovie class + provides various functions for both running and controlling the + given animation. + + \o \image paintsystem-movie.png + \endtable + + The QImageReader and QImageWriter classes rely on the + QImageIOHandler class which is the common image I/O interface for + all image formats in Qt. QImageIOHandler objects are used + internally by QImageReader and QImageWriter to add support for + different image formats to Qt. + + A list of the supported file formats are available through the + QImageReader::supportedImageFormats() and + QImageWriter::supportedImageFormats() functions. Qt supports + several file formats by default, and in addition new formats can + be added as plugins. The currently supported formats are listed in + the QImageReader and QImageWriter class documentation. + + Qt's plugin mechanism can also be used to write a custom image + format handler. This is done by deriving from the QImageIOHandler + class, and creating a QImageIOPlugin object which is a factory for + creating QImageIOHandler objects. When the plugin is installed, + QImageReader and QImageWriter will automatically load the plugin + and start using it. + + \section1 Rendering SVG files + + \table 100% + \row + \o \image paintsystem-svg.png + \o \bold {SVG Rendering} + + Scalable Vector Graphics (SVG) is a language for describing two-dimensional + graphics and graphical applications in XML. SVG 1.1 is a W3C Recommendation + and forms the core of the current SVG developments in Qt. SVG 1.2 is the + specification currently being developed by the \l{SVG Working Group}, and it + is \l{http://www.w3.org/TR/SVG12/}{available in draft form}. + The \l{Mobile SVG Profiles} (SVG Basic and SVG Tiny) are aimed at + resource-limited devices and are part of the 3GPP platform for third generation + mobile phones. You can read more about SVG at \l{About SVG}. + + Qt supports the \l{SVG 1.2 Tiny Static Features}{static features} of + \l{SVG 1.2 Tiny}. ECMA scripts and DOM manipulation are currently not + supported. + + SVG drawings can be rendered onto any QPaintDevice subclass. This + approach gives developers the flexibility to experiment, in order + to find the best solution for each application. + + The easiest way to render SVG files is to construct a QSvgWidget and + load an SVG file using one of the QSvgWidget::load() functions. + + QSvgRenderer is the class responsible for rendering SVG files for + QSvgWidget, and it can be used directly to provide SVG support for + custom widgets. + To load an SVG file, construct a QSvgRenderer with a file name or the + contents of a file, or call QSvgRenderer::load() on an existing + renderer. If the SVG file has been loaded successfully the + QSvgRenderer::isValid() will return true. + + Once you have loaded the SVG file successfully, you can render it + with the QSvgRenderer::render() function. Note that this scheme allows + you to render SVG files on all paint devices supported by Qt, including + QWidget, QGLWidget, and QImage. See the \l{SVG Viewer Example}{SVG Viewer} + example for more details. + + \endtable +*/ + +/*! + \page paintsystem-styling.html + \title Styling + + \previouspage Reading and Writing Image Files + \contentspage The Paint System + \nextpage Printing with Qt + + Qt's built-in widgets use the QStyle class to perform nearly all + of their drawing. QStyle is an abstract base class that + encapsulates the look and feel of a GUI, and can be used to make + the widgets look exactly like the equivalent native widgets or to + give the widgets a custom look. + + Qt provides a set of QStyle subclasses that emulate the native + look of the different platforms supported by Qt (QWindowsStyle, + QMacStyle, QMotifStyle, etc.). These styles are built into the + QtGui library, other styles can be made available using Qt's + plugin mechansim. + + Most functions for drawing style elements take four arguments: + + \list + \o an enum value specifying which graphical element to draw + \o a QStyleOption object specifying how and where to render that element + \o a QPainter object that should be used to draw the element + \o a QWidget object on which the drawing is performed (optional) + \endlist + + The style gets all the information it needs to render the + graphical element from the QStyleOption class. The widget is + passed as the last argument in case the style needs it to perform + special effects (such as animated default buttons on Mac OS X), + but it isn't mandatory. In fact, QStyle can be used to draw on any + paint device (not just widgets), in which case the widget argument + is a zero pointer. + + \image paintsystem-stylepainter.png + + The paint system also provides the QStylePainter class inheriting + from QPainter. QStylePainter is a convenience class for drawing + QStyle elements inside a widget, and extends QPainter with a set + of high-level drawing functions implemented on top of QStyle's + API. The advantage of using QStylePainter is that the parameter + lists get considerably shorter. + + \table 100% + \row + \o \inlineimage paintsystem-icon.png + \o \bold QIcon + + The QIcon class provides scalable icons in different modes and states. + + QIcon can generate pixmaps reflecting an icon's state, mode and + size. These pixmaps are generated from the set of pixmaps + made available to the icon, and are used by Qt widgets to show an + icon representing a particular action. + + The rendering of a QIcon object is handled by the QIconEngine + class. Each icon has a corresponding icon engine that is + responsible for drawing the icon with a requested size, mode and + state. + + \endtable + + For more information about widget styling and appearance, see the + \l{Styles and Style Aware Widgets}. +*/ diff --git a/doc/src/gui/qtgui.qdoc b/doc/src/gui/qtgui.qdoc new file mode 100644 index 0000000000..fd3bcac5a1 --- /dev/null +++ b/doc/src/gui/qtgui.qdoc @@ -0,0 +1,12 @@ +/*! + \module QtGui + \title QtGui Module + \ingroup modules + + \brief The QtGui module extends QtCore with GUI functionality. + + To include the definitions of both modules' classes, use the + following directive: + + \snippet doc/src/snippets/code/doc_src_qtgui.pro 0 +*/ diff --git a/doc/src/network-programming/bearermanagement.qdoc b/doc/src/network-programming/bearermanagement.qdoc deleted file mode 100644 index 3d0262aa95..0000000000 --- a/doc/src/network-programming/bearermanagement.qdoc +++ /dev/null @@ -1,271 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! -\page bearer-management.html - -\title Bearer Management -\ingroup qt-network -\brief An API to control the system's connectivity state. - -Bearer Management controls the connectivity state of the system so that -the user can start or stop interfaces or roam transparently between -access points. - -\tableofcontents - - -\section1 Overview - -The Bearer Management API controls the system's connectivity state. This -incorporates simple information such as whether the device is online and -how many interfaces there are as well as enables the application developer -to start, stop network interfaces and influences other connection specific -details. Depending on the platform's capabilities it may even provide -session management so that a network interface remains up for as long as -clients have a registered interest in them while at the same time -optimizes the interface's uptime. - -This API does not provide support for management of network configurations -themselves. It is up to the platform to provide infrastructure which -enables to user to create, edit or delete network configurations. - -\section2 The API in Detail - -Computer systems manage their network interfaces via a set of configurations. -Each configuration describes a set of parameters which instruct the system -how a particular network interface is started. One of the most simplistic -examples might be an Ethernet configuration that links a network card to a -DHCP server. A more complex example might be a Wireless LAN configuration -which may comprise of hardware details such as the WLAN card address, -WLAN access point details (e.g ESSID, encryption details) and user specific -information (for example username and password). Once the network interface -was configured and started according to the configuration blue print, -multiple applications are free to use this link layer connection/session -for their own socket operations. Note that the QNetworkConfiguration object -only provides limited information about the configuration details themselves. -It's main purpose is to act as a configuration identifier through which link -layer connections can be created, destroyed and monitored. - -QNetworkSession provides two types of use cases. It enables the monitoring of -physical network interfaces and management of network sessions. Network sessions -are a common feature on mobile devices where multiple applications -can request network sessions as they see fit. The system consolidates and tracks -active network sessions for the same network interface by maintaining the link -layer connections until the last session has been closed. The subsequent table -lists the major QNetworkSession functions and how they fit into the session and -hardware management categories: - -\table 60% -\header \o Interface management \o Session management -\row \o QNetworkSession::stop() \o QNetworkSession::open() -\row \o QNetworkSession::interface() \o QNetworkSession::close() -\row \o QNetworkSession::state() \o QNetworkSession::isOpen() -\row \o QNetworkSession::bytesWritten() \o QNetworkSession::migrate() -\row \o QNetworkSession::bytesReceived() \o QNetworkSession::ignore() -\row \o QNetworkSession::activeTime() \o QNetworkSession::accept() -\row \o QNetworkSession::stateChanged() \o QNetworkSession::reject() -\row \o \o QNetworkSession::opened() -\row \o \o QNetworkSession::closed() -\endtable - -The state of the session represents the state of the underlying access point -whereas the session's openness implies the networking/connectivity state available -to the current process. - -Possible use cases for interface management are network management related -applications which intend to monitor the connectivity state but do not engage -in network communication themselves. Any application wanting to open a socket -to a remote address will typically use session management related functionality. - -\section3 Service networks - -Some mobile platforms use the concept of grouped access points (also -called SNAP or Service Network Access Point). In principle multiple -configurations are grouped together and possibly even prioritized when -compared to each other. This is useful for use cases where all -configurations serve a similar purpose or context. A common context could -be that they provide access to the public Internet or possibly only to the -office Intranet. By providing a pool of configurations the system can make -a decision based on given priorities which usually map to factors such as -speed, availability and cost. Furthermore the system can automatically -roam from one access point to the next one while ensuring minimal impact on -the user experience. - -The \l{QNetworkConfiguration::Type} flag specifies to what category a -configuration belongs. The \l{QNetworkConfiguration::InternetAccessPoint} -type is the most common example. It represents a configuration that can be -used to create a session. The above mentioned grouping behavior is provided -by \l {QNetworkConfiguration::ServiceNetwork} configurations. Service -networks are place holders until such time when the user attempts to -\l {QNetworkSession::open()}{open()} a new session. At that point in time -the system determines which of the configurations \l{QNetworkConfiguration::children()} -is best to use. The selection algorithm is provided by the platform and is usually managed -by network settings applications. A service network can only have one level of indirection -which implies children can only be of type \l {QNetworkConfiguration::InternetAccessPoint}. - -Most systems allow the user to define the systems default configuration. -Usually the default behavior is either a service network, a particular -Internet access point or the user instructs the platform to ask the user -once an application requests the network. User interaction is generally -implemented by some sort of system dialog which shows up at the appropriate -point in time. The application does not have to handle the user input. This -API provides the \l QNetworkConfigurationManager::defaultConfiguration() -call which serves a similar purpose. The subsequent code snippet provides -a quick way how an application can quickly create a new network session -without (or only minimal) user interaction: - -\code - // Set Internet Access Point - QNetworkConfigurationManager manager; - const bool canStartIAP = (manager.capabilities() - & QNetworkConfigurationManager::CanStartAndStopInterfaces); - // Is there default access point, use it - QNetworkConfiguration cfg = manager.defaultConfiguration(); - if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) { - QMessageBox::information(this, tr("Network"), tr( - "No Access Point found.")); - return; - } - - session = new QNetworkSession(cfg, this); - session->open(); - session->waitForOpened(-1); -\endcode - -To accommodate the "Ask user" use case the default configuration can be of -type QNetworkConfiguration::UserChoice. A user choice configuration is -resolved as part of the \l {QNetworkSession::open()} call. Note that a -\l{QNetworkConfiguration::UserChoice}{UserChoice} configuration is only -ever returned via \l {QNetworkConfigurationManager::defaultConfiguration()} -and not \l QNetworkConfigurationManager::allConfigurations(). - -On systems which do not maintain a list of -\l {QNetworkConfigurationManager::defaultConfiguration()}{defaultConfiguration()} -an invalid configuration is returned. A possible workaround could be to -implement a custom dialog which is populated based on what -\l QNetworkConfigurationManager::allConfigurations() returns. - -\section3 Managing network sessions - -A QNetworkSession object separates a \l {QNetworkSession::state()}{state()} -and an \l{QNetworkSession::isOpen()}{isOpen()} condition. - -The state() attribute enables developers to detect whether the system -currently maintains a global network session for the given -QNetworkConfiguration. If \l {QNetworkSession::isOpen()}{isOpen()} -returns true the QNetworkSession instance at hand was at least one of the -entities requesting the global network session. This distinction is -required to support the notion of session registrations. For as long as -there are one or more open QNetworkSession instances the underlying -network interface is not shut down. Therefore the session -\l{QNetworkSession::state()}{state()} can be used to monitor the state of -network interfaces. - -An open session is created by calling \l {QNetworkSession::open()} and -closed via \l{QNetworkSession::close()}, respectively. If the session -is \l{QNetworkSession::Disconnected}{disconnected} at the time of the -\l{QNetworkSession::open()}{open()} call the underlying interface is started; -otherwise only the reference counter against the global session is -incremented. The opposite behavior can be observed when using -\l{QNetworkSession::close()}{close()}. - -In some use cases it may be necessary to turn the interface off despite of -open sessions. This can be achieved by calling -\l{QNetworkSession::stop()}{stop()}. An example use case could be a -network manager type of application allowing the user to control the -overall state of the devices connectivity. - -Global (inter-process) session support is platform dependent and can be -detected via \l {QNetworkConfigurationManager::SystemSessionSupport}. -If the system does not support global session calling -\l{QNetworkSession::close()}{close()} never stops the interface. - -\section3 Roaming - -Roaming is the process of reconnecting a device from one network to another -while minimizing the impact on the application. The system notifies the application -about link layer changes so that the required preparation can be taken. -The most common reaction would be to reinitialize sockets and to renegotiate -stateful connections with other parties. In the most extreme cases applications -may even prevent the roaming altogether. - -Roaming is initiated when the system determines that a more appropriate access point -becomes available to the user. In general such a decision is based on cost, network speed -or network type (access to certain private networks may only be provided via certain access points). -Almost all devices providing roaming support have some form of global configuration application -enabling the user to define such groups of access points (service networks) and priorities. - -This API supports two types of roaming. Application level roaming (ALR) -provides the most control over the process. Applications will be notified about upcoming -link layer changes and get the opportunity to test the new access point. Eventually they can -reject or accept the link layer change. The second form of roaming is referred to as Forced Roaming. -The system simply changes the link layer without consulting the application. It is up to -the application to detect that some of its internal socket may have become invalid. As a consequence -it has to reinitialize those sockets and reestablish the previous user session without -any interruption. Forced roaming has the advantage that applications don't have to -manage the entire roaming process by themselves. - -QNetworkSession is the central class for managing roaming related issues. - -\section3 Platform capabilities - -Some API features are not available on all platforms. The -\l QNetworkConfigurationManager::Capability should be used to detect -platform features at runtime. The following table lists the various -platform APIs being used by this API. This may assist in the process of -determining the feature support: - -\table - \header - \o Platform - \o Backend capabilities - \row - \o Linux\unicode{0xAE} - \o Linux uses the \l {http://projects.gnome.org/NetworkManager}{NetworkManager API} which supports interface notifications and starting and stopping of network interfaces. - \row - \o Windows\unicode{0xAE} XP - \o This platform supports interface notifications without active polling. - \row - \o Windows XP SP2+Hotfixes, Windows XP SP3, Windows Vista, Windows 7 - \o In addition to standard Windows XP wifi access point monitoring has been improved which includes the ability to start and stop wifi interfaces. This requires Windows to manage the wifi interfaces. - \row - \o Symbian\unicode{0xAE} Platform & S60 3.1 - \o Symbian support is based on Symbian platforms RConnection. In addition to interface notifications, starting and stopping of network it provides system wide session support and direct connection routing. - \row - \o Symbian Platform & S60 3.2+ - \o This platform enjoys the most comprehensive feature set. In addition to the features support by the S60 3.1 Network roaming is supported. - \row - \o Mac OS\unicode{0xAE} - \o This platform has full support by way of CoreWLAN offered in Mac OS 10.6. Previous - versions of Mac OS - 10.5 and 10.4 have limited support. - \row - \o All other platforms (*nix, Windows Mobile) - \o This backend is the fallback for all platforms supports network interface notifications via active polling only. -\endtable - -*/ diff --git a/doc/src/network-programming/qtnetwork.qdoc b/doc/src/network-programming/qtnetwork.qdoc deleted file mode 100644 index 93ba24815d..0000000000 --- a/doc/src/network-programming/qtnetwork.qdoc +++ /dev/null @@ -1,350 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group network - \title Network Programming API - \brief Classes for Network Programming - - \ingroup groups -*/ - -/*! - \page network-programming.html - \title Network Programming - \ingroup qt-network - \brief An Introduction to Network Programming with Qt - - The QtNetwork module offers classes that allow you to write TCP/IP clients - and servers. It offers classes such as QFtp that implement specific - application-level protocols, lower-level classes such as QTcpSocket, - QTcpServer and QUdpSocket that represent low level network concepts, - and high level classes such as QNetworkRequest, QNetworkReply and - QNetworkAccessManager to perform network operations using common protocols. - It also offers classes such as QNetworkConfiguration, - QNetworkConfigurationManager and QNetworkSession that implement bearer - management. - - \tableofcontents - - \section1 Qt's Classes for Network Programming - - The following classes provide support for network programming in Qt. - - \annotatedlist network - - \section1 High Level Network Operations for HTTP and FTP - - The Network Access API is a collection of classes for performing - common network operations. The API provides an abstraction layer - over the specific operations and protocols used (for example, - getting and posting data over HTTP), and only exposes classes, - functions, and signals for general or high level concepts. - - Network requests are represented by the QNetworkRequest class, - which also acts as a general container for information associated - with a request, such as any header information and the encryption - used. The URL specified when a request object is constructed - determines the protocol used for a request. - Currently HTTP, FTP and local file URLs are supported for uploading - and downloading. - - The coordination of network operations is performed by the - QNetworkAccessManager class. Once a request has been created, - this class is used to dispatch it and emit signals to report on - its progress. The manager also coordinates the use of - \l{QNetworkCookieJar}{cookies} to store data on the client, - authentication requests, and the use of proxies. - - Replies to network requests are represented by the QNetworkReply - class; these are created by QNetworkAccessManager when a request - is dispatched. The signals provided by QNetworkReply can be used - to monitor each reply individually, or developers may choose to - use the manager's signals for this purpose instead and discard - references to replies. Since QNetworkReply is a subclass of - QIODevice, replies can be handled synchronously or asynchronously; - i.e., as blocking or non-blocking operations. - - Each application or library can create one or more instances of - QNetworkAccessManager to handle network communication. - - \section1 Writing FTP Clients with QFtp - - FTP (File Transfer Protocol) is a protocol used almost exclusively - for browsing remote directories and for transferring files. - - \image httpstack.png FTP Client and Server - - FTP uses two network connections, one for sending - commands and one for transferring data. The - FTP protocol has a state and requires the client to send several - commands before a file transfer takes place. - FTP clients establish a connection - and keeps it open throughout the session. In each session, multiple - transfers can occur. - - The QFtp class provides client-side support for FTP. - It has the following characteristics: - \list - - \o \e{Non-blocking behavior.} QFtp is asynchronous. - You can schedule a series of commands which are executed later, - when control returns to Qt's event loop. - - \o \e{Command IDs.} Each command has a unique ID number that you - can use to follow the execution of the command. For example, QFtp - emits the \l{QFtp::commandStarted()}{commandStarted()} and - \l{QFtp::commandFinished()}{commandFinished()} signal with the - command ID for each command that is executed. - - \o \e{Data transfer progress indicators.} QFtp emits signals - whenever data is transferred (QFtp::dataTransferProgress(), - QNetworkReply::downloadProgress(), and - QNetworkReply::uploadProgress()). You could connect these signals - to QProgressBar::setProgress() or QProgressDialog::setProgress(), - for example. - - \o \e{QIODevice support.} The class supports convenient - uploading from and downloading to \l{QIODevice}s, in addition to a - QByteArray-based API. - - \endlist - - There are two main ways of using QFtp. The most common - approach is to keep track of the command IDs and follow the - execution of every command by connecting to the appropriate - signals. The other approach is to schedule all commands at once - and only connect to the done() signal, which is emitted when all - scheduled commands have been executed. The first approach - requires more work, but it gives you more control over the - execution of individual commands and allows you to initiate new - commands based on the result of a previous command. It also - enables you to provide detailed feedback to the user. - - The \l{network/qftp}{FTP} example - illustrates how to write an FTP client. - Writing your own FTP (or HTTP) server is possible using the - lower-level classes QTcpSocket and QTcpServer. - - \section1 Using TCP with QTcpSocket and QTcpServer - - TCP (Transmission Control Protocol) is a low-level network - protocol used by most Internet protocols, including HTTP and FTP, - for data transfer. It is a reliable, stream-oriented, - connection-oriented transport protocol. It is particularly well - suited to the continuous transmission of data. - - \image tcpstream.png A TCP Stream - - The QTcpSocket class provides an interface for TCP. You can use - QTcpSocket to implement standard network protocols such as POP3, - SMTP, and NNTP, as well as custom protocols. - - A TCP connection must be established to a remote host and port - before any data transfer can begin. Once the connection has been - established, the IP address and port of the peer are available - through QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At - any time, the peer can close the connection, and data transfer - will then stop immediately. - - QTcpSocket works asynchronously and emits signals to report status - changes and errors, just like QNetworkAccessManager and QFtp. It - relies on the event loop to detect incoming data and to - automatically flush outgoing data. You can write data to the - socket using QTcpSocket::write(), and read data using - QTcpSocket::read(). QTcpSocket represents two independent streams - of data: one for reading and one for writing. - - Since QTcpSocket inherits QIODevice, you can use it with - QTextStream and QDataStream. When reading from a QTcpSocket, you - must make sure that enough data is available by calling - QTcpSocket::bytesAvailable() beforehand. - - If you need to handle incoming TCP connections (e.g., in a server - application), use the QTcpServer class. Call QTcpServer::listen() - to set up the server, and connect to the - QTcpServer::newConnection() signal, which is emitted once for - every client that connects. In your slot, call - QTcpServer::nextPendingConnection() to accept the connection and - use the returned QTcpSocket to communicate with the client. - - Although most of its functions work asynchronously, it's possible - to use QTcpSocket synchronously (i.e., blocking). To get blocking - behavior, call QTcpSocket's waitFor...() functions; these suspend - the calling thread until a signal has been emitted. For example, - after calling the non-blocking QTcpSocket::connectToHost() - function, call QTcpSocket::waitForConnected() to block the thread - until the \l{QTcpSocket::connected()}{connected()} signal has - been emitted. - - Synchronous sockets often lead to code with a simpler flow of - control. The main disadvantage of the waitFor...() approach is - that events won't be processed while a waitFor...() function is - blocking. If used in the GUI thread, this might freeze the - application's user interface. For this reason, we recommend that - you use synchronous sockets only in non-GUI threads. When used - synchronously, QTcpSocket doesn't require an event loop. - - The \l{network/fortuneclient}{Fortune Client} and - \l{network/fortuneserver}{Fortune Server} examples show how to use - QTcpSocket and QTcpServer to write TCP client-server - applications. See also \l{network/blockingfortuneclient}{Blocking - Fortune Client} for an example on how to use a synchronous - QTcpSocket in a separate thread (without using an event loop), - and \l{network/threadedfortuneserver}{Threaded Fortune Server} - for an example of a multithreaded TCP server with one thread per - active client. - - \section1 Using UDP with QUdpSocket - - UDP (User Datagram Protocol) is a lightweight, unreliable, - datagram-oriented, connectionless protocol. It can be used when - reliability isn't important. For example, a server that reports - the time of day could choose UDP. If a datagram with the time of - day is lost, the client can simply make another request. - - \image udppackets.png UDP Packets - - The QUdpSocket class allows you to send and receive UDP - datagrams. It inherits QAbstractSocket, and it therefore shares - most of QTcpSocket's interface. The main difference is that - QUdpSocket transfers data as datagrams instead of as a continuous - stream of data. In short, a datagram is a data packet of limited - size (normally smaller than 512 bytes), containing the IP address - and port of the datagram's sender and receiver in addition to the - data being transferred. - - QUdpSocket supports IPv4 broadcasting. Broadcasting is often used - to implement network discovery protocols, such as finding which - host on the network has the most free hard disk space. One host - broadcasts a datagram to the network that all other hosts - receive. Each host that receives a request then sends a reply - back to the sender with its current amount of free disk space. - The originator waits until it has received replies from all - hosts, and can then choose the server with most free space to - store data. To broadcast a datagram, simply send it to the - special address QHostAddress::Broadcast (255.255.255.255), or - to your local network's broadcast address. - - QUdpSocket::bind() prepares the socket for accepting incoming - datagrams, much like QTcpServer::listen() for TCP servers. - Whenever one or more datagrams arrive, QUdpSocket emits the - \l{QUdpSocket::readyRead()}{readyRead()} signal. Call - QUdpSocket::readDatagram() to read the datagram. - - The \l{network/broadcastsender}{Broadcast Sender} and - \l{network/broadcastreceiver}{Broadcast Receiver} examples show how to - write a UDP sender and a UDP receiver using Qt. - - QUdpSocket also supports multicasting. The - \l{network/multicastsender}{Multicast Sender} and - \l{network/multicastreceiver}{Multicast Receiver} examples show how to use - write UDP multicast clients. - - \section1 Resolving Host Names using QHostInfo - - Before establishing a network connection, QTcpSocket and - QUdpSocket perform a name lookup, translating the host name - you're connecting to into an IP address. This operation is - usually performed using the DNS (Domain Name Service) protocol. - - QHostInfo provides a static function that lets you perform such a - lookup yourself. By calling QHostInfo::lookupHost() with a host - name, a QObject pointer, and a slot signature, QHostInfo will - perform the name lookup and invoke the given slot when the - results are ready. The actual lookup is done in a separate - thread, making use of the operating system's own methods for - performing name lookups. - - QHostInfo also provides a static function called - QHostInfo::fromName() that takes the host name as argument and - returns the results. In this case, the name lookup is performed - in the same thread as the caller. This overload is useful for - non-GUI applications or for doing name lookups in a separate, - non-GUI thread. (Calling this function in a GUI thread may cause - your user interface to freeze while the function blocks as - it performs the lookup.) - - \section1 Support for Network Proxies - - Network communication with Qt can be performed through proxies, - which direct or filter network traffic between local and remote - connections. - - Individual proxies are represented by the QNetworkProxy class, - which is used to describe and configure the connection to a proxy. - Proxy types which operate on different levels of network communication - are supported, with SOCKS 5 support allowing proxying of network - traffic at a low level, and HTTP and FTP proxying working at the - protocol level. See QNetworkProxy::ProxyType for more information. - - Proxying can be enabled on a per-socket basis or for all network - communication in an application. A newly opened socket can be - made to use a proxy by calling its QAbstractSocket::setProxy() - function before it is connected. Application-wide proxying can - be enabled for all subsequent socket connections through the use - of the QNetworkProxy::setApplicationProxy() function. - - Proxy factories are used to create policies for proxy use. - QNetworkProxyFactory supplies proxies based on queries for specific - proxy types. The queries themselves are encoded in QNetworkProxyQuery - objects which enable proxies to be selected based on key criteria, - such as the purpose of the proxy (TCP, UDP, TCP server, URL request), - local port, remote host and port, and the protocol in use (HTTP, FTP, - etc.). - - QNetworkProxyFactory::proxyForQuery() is used to query the factory - directly. An application-wide policy for proxying can be implemented - by passing a factory to QNetworkProxyFactory::setApplicationProxyFactory() - and a custom proxying policy can be created by subclassing - QNetworkProxyFactory; see the class documentation for details. - - \section1 Bearer Management Support - - Bearer Management controls the connectivity state of the device such that - the application can start or stop network interfaces and roam - transparently between access points. - - The QNetworkConfigurationManager class manages the list of network - configurations known to the device. A network configuration describes the - set of parameters used to start a network interface and is represented by - the QNetworkConfiguration class. - - A network interface is started by openning a QNetworkSession based on a - given network configuration. In most situations creating a network session - based on the platform specified default network configuration is - appropriate. The default network configuration is returned by the - QNetworkConfigurationManager::defaultConfiguration() function. - - On some platforms it is a platform requirement that the application open a - network session before any network operations can be performed. This can be - tested by the presents of the - QNetworkConfigurationManager::NetworkSessionRequired flag in the value - returned by the QNetworkConfigurationManager::capabilities() function. - - \sa {Bearer Management} -*/ diff --git a/doc/src/network-programming/ssl.qdoc b/doc/src/network-programming/ssl.qdoc deleted file mode 100644 index 0bbcd8afb7..0000000000 --- a/doc/src/network-programming/ssl.qdoc +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page ssl.html - \title Secure Sockets Layer (SSL) Classes - \brief Classes for secure communication over network sockets. - \ingroup qt-network - - \keyword SSL - - The classes below provide support for secure network communication using - the Secure Sockets Layer (SSL) protocol, using the \l{OpenSSL Toolkit} to - perform encryption and protocol handling. - - See the \l{General Qt Requirements} page for information about the - versions of OpenSSL that are known to work with Qt. - - \section1 Enabling and Disabling SSL Support - - When building Qt from source, the configuration system checks for the presence - of the \c{openssl/opensslv.h} header provided by source or developer packages - of OpenSSL. - - By default, an SSL-enabled Qt library dynamically loads any installed OpenSSL - library at run-time. However, it is possible to link against the library at - compile-time by configuring Qt with the \c{-openssl-linked} option. - - When building a version of Qt linked against OpenSSL, the build system will - attempt to link with libssl and libcrypt libraries located in the default - location on the developer's system. This location is configurable: - set the \c OPENSSL_LIBS environment variable to contain the linker options - required to link Qt against the installed library. For example, on a Unix/Linux - system: - - \code - ./configure -openssl-linked OPENSSL_LIBS='-L/opt/ssl/lib -lssl -lcrypto' - \endcode - - To disable SSL support in a Qt build, configure Qt with the \c{-no-openssl} - option. - - \section1 Licensing Information - - \note Due to import and export restrictions in some parts of the world, we - are unable to supply the OpenSSL Toolkit with Qt packages. Developers wishing - to use SSL communication in their deployed applications should either ensure - that their users have the appropriate libraries installed, or they should - consult a suitably qualified legal professional to ensure that applications - using code from the OpenSSL project are correctly certified for import - and export in relevant regions of the world. - - When the QtNetwork module is built with SSL support, the library is linked - against OpenSSL in a way that requires OpenSSL license compliance. -*/ diff --git a/doc/src/network/files-and-resources/datastreamformat.qdoc b/doc/src/network/files-and-resources/datastreamformat.qdoc new file mode 100644 index 0000000000..6fe888b52e --- /dev/null +++ b/doc/src/network/files-and-resources/datastreamformat.qdoc @@ -0,0 +1,361 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page datastreamformat.html + \title Serializing Qt Data Types + \ingroup qt-network + \brief Representations of data types that can be serialized by QDataStream. + + The \l QDataStream allows you to serialize some of the Qt data types. + The table below lists the data types that QDataStream can serialize + and how they are represented. The format described below is + \l{QDataStream::setVersion()}{version 12}. + + It is always best to cast integers to a Qt integer type, such as + qint16 or quint32, when reading and writing. This ensures that + you always know exactly what size integers you are reading and + writing, no matter what the underlying platform and architecture + the application happens to be running on. + + \table + \row \o bool + \o \list + \o boolean + \endlist + \row \o qint8 + \o \list + \o signed byte + \endlist + \row \o qint16 + \o \list + \o signed 16-bit integer + \endlist + \row \o qint32 + \o \list + \o signed 32-bit integer + \endlist + \row \o qint64 + \o \list + \o signed 64-bit integer + \endlist + \row \o quint8 + \o \list + \o unsigned byte + \endlist + \row \o quint16 + \o \list + \o unsigned 16-bit integer + \endlist + \row \o quint32 + \o \list + \o unsigned 32-bit integer + \endlist + \row \o quint64 + \o \list + \o unsigned 64-bit integer + \endlist + \row \o \c float + \o \list + \o 32-bit floating point number using the standard IEEE 754 format + \endlist + \row \o \c double + \o \list + \o 64-bit floating point number using the standard IEEE 754 format + \endlist + \row \o \c {const char *} + \o \list + \o The string length (quint32) + \o The string bytes, excluding the terminating 0 + \endlist + \row \o QBitArray + \o \list + \o The array size (quint32) + \o The array bits, i.e. (size + 7)/8 bytes + \endlist + \row \o QBrush + \o \list + \o The brush style (quint8) + \o The brush color (QColor) + \o If style is CustomPattern, the brush pixmap (QPixmap) + \endlist + \row \o QByteArray + \o \list + \o If the byte array is null: 0xFFFFFFFF (quint32) + \o Otherwise: the array size (quint32) followed by the array bytes, i.e. size bytes + \endlist + \row \o \l QColor + \o \list + \o Color spec (qint8) + \o Alpha value (quint16) + \o Red value (quint16) + \o Green value (quint16) + \o Blue value (quint16) + \o Pad value (quint16) + \endlist + \row \o QCursor + \o \list + \o Shape ID (qint16) + \o If shape is BitmapCursor: The bitmap (QPixmap), mask (QPixmap), and hot spot (QPoint) + \endlist + \row \o QDate + \o \list + \o Julian day (quint32) + \endlist + \row \o QDateTime + \o \list + \o Date (QDate) + \o Time (QTime) + \o 0 for Qt::LocalTime, 1 for Qt::UTC (quint8) + \endlist + \row \o QEasingCurve + \o \list + \o type (quint8) + \o func (quint64) + \o hasConfig (bool) + \o If hasConfig is true then these fields follow: + \o list + \o period (double) + \o amplitude (double) + \o overshoot (double) + \endlist + \row \o QFont + \o \list + \o The family (QString) + \o The point size (qint16) + \o The style hint (quint8) + \o The char set (quint8) + \o The weight (quint8) + \o The font bits (quint8) + \endlist + \row \o QHash + \o \list + \o The number of items (quint32) + \o For all items, the key (Key) and value (T) + \endlist + \row \o QIcon + \o \list + \o The number of pixmap entries (quint32) + \o For all pixmap entries: + \list + \o The pixmap (QPixmap) + \o The file name (QString) + \o The pixmap size (QSize) + \o The \l{QIcon::Mode}{mode} (quint32) + \o The \l{QIcon::State}{state} (quint32) + \endlist + \endlist + \row \o QImage + \o \list + \o If the image is null a "null image" marker is saved; + otherwise the image is saved in PNG or BMP format (depending + on the stream version). If you want control of the format, + stream the image into a QBuffer (using QImageIO) and stream + that. + \endlist + \row \o QKeySequence + \o \list + \o A QList, where each integer is a key in the key sequence + \endlist + \row \o QLinkedList + \o \list + \o The number of items (quint32) + \o The items (T) + \endlist + \row \o QList + \o \list + \o The number of items (quint32) + \o The items (T) + \endlist + \row \o QMap + \o \list + \o The number of items (quint32) + \o For all items, the key (Key) and value (T) + \endlist + \row \o QMatrix + \o \list + \o m11 (double) + \o m12 (double) + \o m21 (double) + \o m22 (double) + \o dx (double) + \o dy (double) + \endlist + \row \o QMatrix4x4 + \o \list + \o m11 (double) + \o m12 (double) + \o m13 (double) + \o m14 (double) + \o m21 (double) + \o m22 (double) + \o m23 (double) + \o m24 (double) + \o m31 (double) + \o m32 (double) + \o m33 (double) + \o m34 (double) + \o m41 (double) + \o m42 (double) + \o m43 (double) + \o m44 (double) + \endlist + \row \o QPair + \o \list + \o first (T1) + \o second (T2) + \endlist + \row \o QPalette + \o The disabled, active, and inactive color groups, each of which consists + of the following: + \list + \o foreground (QBrush) + \o button (QBrush) + \o light (QBrush) + \o midlight (QBrush) + \o dark (QBrush) + \o mid (QBrush) + \o text (QBrush) + \o brightText (QBrush) + \o buttonText (QBrush) + \o base (QBrush) + \o background (QBrush) + \o shadow (QBrush) + \o highlight (QBrush) + \o highlightedText (QBrush) + \o link (QBrush) + \o linkVisited (QBrush) + \endlist + \row \o QPen + \o \list + \o The pen styles (quint8) + \o The pen width (quint16) + \o The pen color (QColor) + \endlist + \row \o QPicture + \o \list + \o The size of the picture data (quint32) + \o The raw bytes of picture data (char) + \endlist + \row \o QPixmap + \o \list + \o Save it as a PNG image. + \endlist + \row \o QPoint + \o \list + \o The x coordinate (qint32) + \o The y coordinate (qint32) + \endlist + \row \o QQuaternion + \o \list + \o The scalar component (double) + \o The x coordinate (double) + \o The y coordinate (double) + \o The z coordinate (double) + \endlist + \row \o QRect + \o \list + \o left (qint32) + \o top (qint32) + \o right (qint32) + \o bottom (qint32) + \endlist + \row \o QRegExp + \o \list + \o The regexp pattern (QString) + \o Case sensitivity (quint8) + \o Regular expression syntax (quint8) + \o Minimal matching (quint8) + \endlist + \row \o QRegion + \o \list + \o The size of the data, i.e. 8 + 16 * (number of rectangles) (quint32) + \o 10 (qint32) + \o The number of rectangles (quint32) + \o The rectangles in sequential order (QRect) + \endlist + \row \o QSize + \o \list + \o width (qint32) + \o height (qint32) + \endlist + \row \o QString + \o \list + \o If the string is null: 0xFFFFFFFF (quint32) + \o Otherwise: The string length in bytes (quint32) followed by the data in UTF-16 + \endlist + \row \o QTime + \o \list + \o Milliseconds since midnight (quint32) + \endlist + \row \o QTransform + \o \list + \o m11 (double) + \o m12 (double) + \o m13 (double) + \o m21 (double) + \o m22 (double) + \o m23 (double) + \o m31 (double) + \o m32 (double) + \o m33 (double) + \endlist + \row \o QUrl + \o \list + \o Holds an URL (QString) + \endlist + \row \o QVariant + \o \list + \o The type of the data (quint32) + \o The null flag (qint8) + \o The data of the specified type + \endlist + \row \o QVector2D + \o \list + \o the x coordinate (double) + \o the y coordinate (double) + \endlist + \row \o QVector3D + \o \list + \o the x coordinate (double) + \o the y coordinate (double) + \o the z coordinate (double) + \endlist + \row \o QVector4D + \o \list + \o the x coordinate (double) + \o the y coordinate (double) + \o the z coordinate (double) + \o the w coordinate (double) + \endlist + \row \o QVector + \o \list + \o The number of items (quint32) + \o The items (T) + \endlist + \endtable +*/ diff --git a/doc/src/network/files-and-resources/resources.qdoc b/doc/src/network/files-and-resources/resources.qdoc new file mode 100644 index 0000000000..d6e320bf04 --- /dev/null +++ b/doc/src/network/files-and-resources/resources.qdoc @@ -0,0 +1,214 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group io + \title Input/Output and Networking + \ingroup groups + + \brief Classes providing file input and output along with directory and + network handling. + + These classes are used to handle input and output to and from external + devices, processes, files etc. as well as manipulating files and directories. +*/ + +/*! + \page resources.html + \title The Qt Resource System + \ingroup qt-network + \brief A platform-independent mechanism for storing binary files in an application. + + \keyword resource system + + The Qt resource system is a platform-independent mechanism for + storing binary files in the application's executable. This is + useful if your application always needs a certain set of files + (icons, translation files, etc.) and you don't want to run the + risk of losing the files. + + The resource system is based on tight cooperation between \l qmake, + \l rcc (Qt's resource compiler), and QFile. It obsoletes Qt 3's + \c qembed tool and the + \l{http://qt.nokia.com/doc/qq/qq05-iconography.html#imagestorage}{image + collection} mechanism. + + \section1 Resource Collection Files (\c{.qrc}) + + The resources associated with an application are specified in a + \c .qrc file, an XML-based file format that lists files on the + disk and optionally assigns them a resource name that the + application must use to access the resource. + + Here's an example \c .qrc file: + + \quotefile mainwindows/application/application.qrc + + The resource files listed in the \c .qrc file are files that are + part of the application's source tree. The specified paths are + relative to the directory containing the \c .qrc file. Note that + the listed resource files must be located in the same directory as + the \c .qrc file, or one of its subdirectories. + + Resource data can either be compiled into the binary and thus accessed + immediately in application code, or a binary resource can be created + and at a later point in application code registered with the resource + system. + + By default, resources are accessible in the application under the + same file name as they have in the source tree, with a \c :/ prefix, + or by a \link QUrl URL\endlink with a \c qrc scheme. + + For example, the file path \c :/images/cut.png or the URL + \c qrc:///images/cut.png would give access to the + \c cut.png file, whose location in the application's source tree + is \c images/cut.png. This can be changed using the \c file tag's + \c alias attribute: + + \snippet doc/src/snippets/code/doc_src_resources.qdoc 0 + + The file is then accessible as \c :/cut-img.png from the + application. It is also possible to specify a path prefix for all + files in the \c .qrc file using the \c qresource tag's \c prefix + attribute: + + \snippet doc/src/snippets/code/doc_src_resources.qdoc 1 + + In this case, the file is accessible as \c + :/myresources/cut-img.png. + + Some resources, such as translation files and icons, many need to + change based on the user's locale. This is done by adding a \c lang + attribute to the \c qresource tag, specifying a suitable locale + string. For example: + + \snippet doc/src/snippets/code/doc_src_resources.qdoc 2 + + If the user's locale is French (i.e., QLocale::system().name() returns + "fr_FR"), \c :/cut.jpg becomes a reference to the \c cut_fr.jpg + image. For other locales, \c cut.jpg is used. + + See the QLocale documentation for a description of the format to use + for locale strings. + + + \section2 External Binary Resources + + For an external binary resource to be created you must create the resource + data (commonly given the \c .rcc extension) by passing the -binary switch to + \l rcc. Once the binary resource is created you can register the resource + with the QResource API. + + For example, a set of resource data specified in a \c .qrc file can be + compiled in the following way: + + \snippet doc/src/snippets/code/doc_src_resources.qdoc 3 + + In the application, this resource would be registered with code like this: + + \snippet doc/src/snippets/code/doc_src_resources.cpp 4 + + \section2 Compiled-In Resources + + For a resource to be compiled into the binary the \c .qrc file must be + mentioned in the application's \c .pro file so that \c qmake knows + about it. For example: + + \snippet examples/mainwindows/application/application.pro 0 + + \c qmake will produce make rules to generate a file called \c + qrc_application.cpp that is linked into the application. This + file contains all the data for the images and other resources as + static C++ arrays of compressed binary data. The \c + qrc_application.cpp file is automatically regenerated whenever + the \c .qrc file changes or one of the files that it refers to + changes. If you don't use \c .pro files, you can either invoke + \c rcc manually or add build rules to your build system. + + \image resources.png Building resources into an application + + Currently, Qt always stores the data directly in the executable, + even on Windows and Mac OS X, where the operating system provides + native support for resources. This might change in a future Qt + release. + + \section1 Compression + + Resources are compressed by default (in the \c ZIP format). It is + possible to turn off compression. This can be useful if your + resources already contain a compressed format, such as \c .png + files. You do this by giving the \c {-no-compress} command line + argument. + + \code + rcc -no-compress myresources.qrc + \endcode + + \c rcc also gives you some control over the compression. You can + specify the compression level and the threshold level to consider + while compressing files, for example: + + \code + rcc -compress 2 -threshold 3 myresources.qrc + \endcode + + \section1 Using Resources in the Application + + In the application, resource paths can be used in most places + instead of ordinary file system paths. In particular, you can + pass a resource path instead of a file name to the QIcon, QImage, + or QPixmap constructor: + + \snippet examples/mainwindows/application/mainwindow.cpp 21 + + See the \l{mainwindows/application}{Application} example for an + actual application that uses Qt's resource system to store its + icons. + + In memory, resources are represented by a tree of resource + objects. The tree is automatically built at startup and used by + QFile for resolving paths to resources. You can use a QDir initialized + with ":/" to navigate through the resource tree from the root. + + Qt's resources support the concept of a search path list. If you then + refer to a resource with \c : instead of \c :/ as the prefix, the + resource will be looked up using the search path list. The search + path list is empty at startup; call QDir::addSearchPath() to + add paths to it. + + If you have resources in a static library, you might need to + force initialization of your resources by calling \l + Q_INIT_RESOURCE() with the base name of the \c .qrc file. For + example: + + \snippet doc/src/snippets/code/doc_src_resources.cpp 5 + + Similarly, if you must unload a set of resources explicitly + (because a plugin is being unloaded or the resources are not valid + any longer), you can force removal of your resources by calling + Q_CLEANUP_RESOURCE() with the same base name as above. +*/ diff --git a/doc/src/network/network-programming/bearermanagement.qdoc b/doc/src/network/network-programming/bearermanagement.qdoc new file mode 100644 index 0000000000..3d0262aa95 --- /dev/null +++ b/doc/src/network/network-programming/bearermanagement.qdoc @@ -0,0 +1,271 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! +\page bearer-management.html + +\title Bearer Management +\ingroup qt-network +\brief An API to control the system's connectivity state. + +Bearer Management controls the connectivity state of the system so that +the user can start or stop interfaces or roam transparently between +access points. + +\tableofcontents + + +\section1 Overview + +The Bearer Management API controls the system's connectivity state. This +incorporates simple information such as whether the device is online and +how many interfaces there are as well as enables the application developer +to start, stop network interfaces and influences other connection specific +details. Depending on the platform's capabilities it may even provide +session management so that a network interface remains up for as long as +clients have a registered interest in them while at the same time +optimizes the interface's uptime. + +This API does not provide support for management of network configurations +themselves. It is up to the platform to provide infrastructure which +enables to user to create, edit or delete network configurations. + +\section2 The API in Detail + +Computer systems manage their network interfaces via a set of configurations. +Each configuration describes a set of parameters which instruct the system +how a particular network interface is started. One of the most simplistic +examples might be an Ethernet configuration that links a network card to a +DHCP server. A more complex example might be a Wireless LAN configuration +which may comprise of hardware details such as the WLAN card address, +WLAN access point details (e.g ESSID, encryption details) and user specific +information (for example username and password). Once the network interface +was configured and started according to the configuration blue print, +multiple applications are free to use this link layer connection/session +for their own socket operations. Note that the QNetworkConfiguration object +only provides limited information about the configuration details themselves. +It's main purpose is to act as a configuration identifier through which link +layer connections can be created, destroyed and monitored. + +QNetworkSession provides two types of use cases. It enables the monitoring of +physical network interfaces and management of network sessions. Network sessions +are a common feature on mobile devices where multiple applications +can request network sessions as they see fit. The system consolidates and tracks +active network sessions for the same network interface by maintaining the link +layer connections until the last session has been closed. The subsequent table +lists the major QNetworkSession functions and how they fit into the session and +hardware management categories: + +\table 60% +\header \o Interface management \o Session management +\row \o QNetworkSession::stop() \o QNetworkSession::open() +\row \o QNetworkSession::interface() \o QNetworkSession::close() +\row \o QNetworkSession::state() \o QNetworkSession::isOpen() +\row \o QNetworkSession::bytesWritten() \o QNetworkSession::migrate() +\row \o QNetworkSession::bytesReceived() \o QNetworkSession::ignore() +\row \o QNetworkSession::activeTime() \o QNetworkSession::accept() +\row \o QNetworkSession::stateChanged() \o QNetworkSession::reject() +\row \o \o QNetworkSession::opened() +\row \o \o QNetworkSession::closed() +\endtable + +The state of the session represents the state of the underlying access point +whereas the session's openness implies the networking/connectivity state available +to the current process. + +Possible use cases for interface management are network management related +applications which intend to monitor the connectivity state but do not engage +in network communication themselves. Any application wanting to open a socket +to a remote address will typically use session management related functionality. + +\section3 Service networks + +Some mobile platforms use the concept of grouped access points (also +called SNAP or Service Network Access Point). In principle multiple +configurations are grouped together and possibly even prioritized when +compared to each other. This is useful for use cases where all +configurations serve a similar purpose or context. A common context could +be that they provide access to the public Internet or possibly only to the +office Intranet. By providing a pool of configurations the system can make +a decision based on given priorities which usually map to factors such as +speed, availability and cost. Furthermore the system can automatically +roam from one access point to the next one while ensuring minimal impact on +the user experience. + +The \l{QNetworkConfiguration::Type} flag specifies to what category a +configuration belongs. The \l{QNetworkConfiguration::InternetAccessPoint} +type is the most common example. It represents a configuration that can be +used to create a session. The above mentioned grouping behavior is provided +by \l {QNetworkConfiguration::ServiceNetwork} configurations. Service +networks are place holders until such time when the user attempts to +\l {QNetworkSession::open()}{open()} a new session. At that point in time +the system determines which of the configurations \l{QNetworkConfiguration::children()} +is best to use. The selection algorithm is provided by the platform and is usually managed +by network settings applications. A service network can only have one level of indirection +which implies children can only be of type \l {QNetworkConfiguration::InternetAccessPoint}. + +Most systems allow the user to define the systems default configuration. +Usually the default behavior is either a service network, a particular +Internet access point or the user instructs the platform to ask the user +once an application requests the network. User interaction is generally +implemented by some sort of system dialog which shows up at the appropriate +point in time. The application does not have to handle the user input. This +API provides the \l QNetworkConfigurationManager::defaultConfiguration() +call which serves a similar purpose. The subsequent code snippet provides +a quick way how an application can quickly create a new network session +without (or only minimal) user interaction: + +\code + // Set Internet Access Point + QNetworkConfigurationManager manager; + const bool canStartIAP = (manager.capabilities() + & QNetworkConfigurationManager::CanStartAndStopInterfaces); + // Is there default access point, use it + QNetworkConfiguration cfg = manager.defaultConfiguration(); + if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) { + QMessageBox::information(this, tr("Network"), tr( + "No Access Point found.")); + return; + } + + session = new QNetworkSession(cfg, this); + session->open(); + session->waitForOpened(-1); +\endcode + +To accommodate the "Ask user" use case the default configuration can be of +type QNetworkConfiguration::UserChoice. A user choice configuration is +resolved as part of the \l {QNetworkSession::open()} call. Note that a +\l{QNetworkConfiguration::UserChoice}{UserChoice} configuration is only +ever returned via \l {QNetworkConfigurationManager::defaultConfiguration()} +and not \l QNetworkConfigurationManager::allConfigurations(). + +On systems which do not maintain a list of +\l {QNetworkConfigurationManager::defaultConfiguration()}{defaultConfiguration()} +an invalid configuration is returned. A possible workaround could be to +implement a custom dialog which is populated based on what +\l QNetworkConfigurationManager::allConfigurations() returns. + +\section3 Managing network sessions + +A QNetworkSession object separates a \l {QNetworkSession::state()}{state()} +and an \l{QNetworkSession::isOpen()}{isOpen()} condition. + +The state() attribute enables developers to detect whether the system +currently maintains a global network session for the given +QNetworkConfiguration. If \l {QNetworkSession::isOpen()}{isOpen()} +returns true the QNetworkSession instance at hand was at least one of the +entities requesting the global network session. This distinction is +required to support the notion of session registrations. For as long as +there are one or more open QNetworkSession instances the underlying +network interface is not shut down. Therefore the session +\l{QNetworkSession::state()}{state()} can be used to monitor the state of +network interfaces. + +An open session is created by calling \l {QNetworkSession::open()} and +closed via \l{QNetworkSession::close()}, respectively. If the session +is \l{QNetworkSession::Disconnected}{disconnected} at the time of the +\l{QNetworkSession::open()}{open()} call the underlying interface is started; +otherwise only the reference counter against the global session is +incremented. The opposite behavior can be observed when using +\l{QNetworkSession::close()}{close()}. + +In some use cases it may be necessary to turn the interface off despite of +open sessions. This can be achieved by calling +\l{QNetworkSession::stop()}{stop()}. An example use case could be a +network manager type of application allowing the user to control the +overall state of the devices connectivity. + +Global (inter-process) session support is platform dependent and can be +detected via \l {QNetworkConfigurationManager::SystemSessionSupport}. +If the system does not support global session calling +\l{QNetworkSession::close()}{close()} never stops the interface. + +\section3 Roaming + +Roaming is the process of reconnecting a device from one network to another +while minimizing the impact on the application. The system notifies the application +about link layer changes so that the required preparation can be taken. +The most common reaction would be to reinitialize sockets and to renegotiate +stateful connections with other parties. In the most extreme cases applications +may even prevent the roaming altogether. + +Roaming is initiated when the system determines that a more appropriate access point +becomes available to the user. In general such a decision is based on cost, network speed +or network type (access to certain private networks may only be provided via certain access points). +Almost all devices providing roaming support have some form of global configuration application +enabling the user to define such groups of access points (service networks) and priorities. + +This API supports two types of roaming. Application level roaming (ALR) +provides the most control over the process. Applications will be notified about upcoming +link layer changes and get the opportunity to test the new access point. Eventually they can +reject or accept the link layer change. The second form of roaming is referred to as Forced Roaming. +The system simply changes the link layer without consulting the application. It is up to +the application to detect that some of its internal socket may have become invalid. As a consequence +it has to reinitialize those sockets and reestablish the previous user session without +any interruption. Forced roaming has the advantage that applications don't have to +manage the entire roaming process by themselves. + +QNetworkSession is the central class for managing roaming related issues. + +\section3 Platform capabilities + +Some API features are not available on all platforms. The +\l QNetworkConfigurationManager::Capability should be used to detect +platform features at runtime. The following table lists the various +platform APIs being used by this API. This may assist in the process of +determining the feature support: + +\table + \header + \o Platform + \o Backend capabilities + \row + \o Linux\unicode{0xAE} + \o Linux uses the \l {http://projects.gnome.org/NetworkManager}{NetworkManager API} which supports interface notifications and starting and stopping of network interfaces. + \row + \o Windows\unicode{0xAE} XP + \o This platform supports interface notifications without active polling. + \row + \o Windows XP SP2+Hotfixes, Windows XP SP3, Windows Vista, Windows 7 + \o In addition to standard Windows XP wifi access point monitoring has been improved which includes the ability to start and stop wifi interfaces. This requires Windows to manage the wifi interfaces. + \row + \o Symbian\unicode{0xAE} Platform & S60 3.1 + \o Symbian support is based on Symbian platforms RConnection. In addition to interface notifications, starting and stopping of network it provides system wide session support and direct connection routing. + \row + \o Symbian Platform & S60 3.2+ + \o This platform enjoys the most comprehensive feature set. In addition to the features support by the S60 3.1 Network roaming is supported. + \row + \o Mac OS\unicode{0xAE} + \o This platform has full support by way of CoreWLAN offered in Mac OS 10.6. Previous + versions of Mac OS - 10.5 and 10.4 have limited support. + \row + \o All other platforms (*nix, Windows Mobile) + \o This backend is the fallback for all platforms supports network interface notifications via active polling only. +\endtable + +*/ diff --git a/doc/src/network/network-programming/qtnetwork.qdoc b/doc/src/network/network-programming/qtnetwork.qdoc new file mode 100644 index 0000000000..93ba24815d --- /dev/null +++ b/doc/src/network/network-programming/qtnetwork.qdoc @@ -0,0 +1,350 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group network + \title Network Programming API + \brief Classes for Network Programming + + \ingroup groups +*/ + +/*! + \page network-programming.html + \title Network Programming + \ingroup qt-network + \brief An Introduction to Network Programming with Qt + + The QtNetwork module offers classes that allow you to write TCP/IP clients + and servers. It offers classes such as QFtp that implement specific + application-level protocols, lower-level classes such as QTcpSocket, + QTcpServer and QUdpSocket that represent low level network concepts, + and high level classes such as QNetworkRequest, QNetworkReply and + QNetworkAccessManager to perform network operations using common protocols. + It also offers classes such as QNetworkConfiguration, + QNetworkConfigurationManager and QNetworkSession that implement bearer + management. + + \tableofcontents + + \section1 Qt's Classes for Network Programming + + The following classes provide support for network programming in Qt. + + \annotatedlist network + + \section1 High Level Network Operations for HTTP and FTP + + The Network Access API is a collection of classes for performing + common network operations. The API provides an abstraction layer + over the specific operations and protocols used (for example, + getting and posting data over HTTP), and only exposes classes, + functions, and signals for general or high level concepts. + + Network requests are represented by the QNetworkRequest class, + which also acts as a general container for information associated + with a request, such as any header information and the encryption + used. The URL specified when a request object is constructed + determines the protocol used for a request. + Currently HTTP, FTP and local file URLs are supported for uploading + and downloading. + + The coordination of network operations is performed by the + QNetworkAccessManager class. Once a request has been created, + this class is used to dispatch it and emit signals to report on + its progress. The manager also coordinates the use of + \l{QNetworkCookieJar}{cookies} to store data on the client, + authentication requests, and the use of proxies. + + Replies to network requests are represented by the QNetworkReply + class; these are created by QNetworkAccessManager when a request + is dispatched. The signals provided by QNetworkReply can be used + to monitor each reply individually, or developers may choose to + use the manager's signals for this purpose instead and discard + references to replies. Since QNetworkReply is a subclass of + QIODevice, replies can be handled synchronously or asynchronously; + i.e., as blocking or non-blocking operations. + + Each application or library can create one or more instances of + QNetworkAccessManager to handle network communication. + + \section1 Writing FTP Clients with QFtp + + FTP (File Transfer Protocol) is a protocol used almost exclusively + for browsing remote directories and for transferring files. + + \image httpstack.png FTP Client and Server + + FTP uses two network connections, one for sending + commands and one for transferring data. The + FTP protocol has a state and requires the client to send several + commands before a file transfer takes place. + FTP clients establish a connection + and keeps it open throughout the session. In each session, multiple + transfers can occur. + + The QFtp class provides client-side support for FTP. + It has the following characteristics: + \list + + \o \e{Non-blocking behavior.} QFtp is asynchronous. + You can schedule a series of commands which are executed later, + when control returns to Qt's event loop. + + \o \e{Command IDs.} Each command has a unique ID number that you + can use to follow the execution of the command. For example, QFtp + emits the \l{QFtp::commandStarted()}{commandStarted()} and + \l{QFtp::commandFinished()}{commandFinished()} signal with the + command ID for each command that is executed. + + \o \e{Data transfer progress indicators.} QFtp emits signals + whenever data is transferred (QFtp::dataTransferProgress(), + QNetworkReply::downloadProgress(), and + QNetworkReply::uploadProgress()). You could connect these signals + to QProgressBar::setProgress() or QProgressDialog::setProgress(), + for example. + + \o \e{QIODevice support.} The class supports convenient + uploading from and downloading to \l{QIODevice}s, in addition to a + QByteArray-based API. + + \endlist + + There are two main ways of using QFtp. The most common + approach is to keep track of the command IDs and follow the + execution of every command by connecting to the appropriate + signals. The other approach is to schedule all commands at once + and only connect to the done() signal, which is emitted when all + scheduled commands have been executed. The first approach + requires more work, but it gives you more control over the + execution of individual commands and allows you to initiate new + commands based on the result of a previous command. It also + enables you to provide detailed feedback to the user. + + The \l{network/qftp}{FTP} example + illustrates how to write an FTP client. + Writing your own FTP (or HTTP) server is possible using the + lower-level classes QTcpSocket and QTcpServer. + + \section1 Using TCP with QTcpSocket and QTcpServer + + TCP (Transmission Control Protocol) is a low-level network + protocol used by most Internet protocols, including HTTP and FTP, + for data transfer. It is a reliable, stream-oriented, + connection-oriented transport protocol. It is particularly well + suited to the continuous transmission of data. + + \image tcpstream.png A TCP Stream + + The QTcpSocket class provides an interface for TCP. You can use + QTcpSocket to implement standard network protocols such as POP3, + SMTP, and NNTP, as well as custom protocols. + + A TCP connection must be established to a remote host and port + before any data transfer can begin. Once the connection has been + established, the IP address and port of the peer are available + through QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At + any time, the peer can close the connection, and data transfer + will then stop immediately. + + QTcpSocket works asynchronously and emits signals to report status + changes and errors, just like QNetworkAccessManager and QFtp. It + relies on the event loop to detect incoming data and to + automatically flush outgoing data. You can write data to the + socket using QTcpSocket::write(), and read data using + QTcpSocket::read(). QTcpSocket represents two independent streams + of data: one for reading and one for writing. + + Since QTcpSocket inherits QIODevice, you can use it with + QTextStream and QDataStream. When reading from a QTcpSocket, you + must make sure that enough data is available by calling + QTcpSocket::bytesAvailable() beforehand. + + If you need to handle incoming TCP connections (e.g., in a server + application), use the QTcpServer class. Call QTcpServer::listen() + to set up the server, and connect to the + QTcpServer::newConnection() signal, which is emitted once for + every client that connects. In your slot, call + QTcpServer::nextPendingConnection() to accept the connection and + use the returned QTcpSocket to communicate with the client. + + Although most of its functions work asynchronously, it's possible + to use QTcpSocket synchronously (i.e., blocking). To get blocking + behavior, call QTcpSocket's waitFor...() functions; these suspend + the calling thread until a signal has been emitted. For example, + after calling the non-blocking QTcpSocket::connectToHost() + function, call QTcpSocket::waitForConnected() to block the thread + until the \l{QTcpSocket::connected()}{connected()} signal has + been emitted. + + Synchronous sockets often lead to code with a simpler flow of + control. The main disadvantage of the waitFor...() approach is + that events won't be processed while a waitFor...() function is + blocking. If used in the GUI thread, this might freeze the + application's user interface. For this reason, we recommend that + you use synchronous sockets only in non-GUI threads. When used + synchronously, QTcpSocket doesn't require an event loop. + + The \l{network/fortuneclient}{Fortune Client} and + \l{network/fortuneserver}{Fortune Server} examples show how to use + QTcpSocket and QTcpServer to write TCP client-server + applications. See also \l{network/blockingfortuneclient}{Blocking + Fortune Client} for an example on how to use a synchronous + QTcpSocket in a separate thread (without using an event loop), + and \l{network/threadedfortuneserver}{Threaded Fortune Server} + for an example of a multithreaded TCP server with one thread per + active client. + + \section1 Using UDP with QUdpSocket + + UDP (User Datagram Protocol) is a lightweight, unreliable, + datagram-oriented, connectionless protocol. It can be used when + reliability isn't important. For example, a server that reports + the time of day could choose UDP. If a datagram with the time of + day is lost, the client can simply make another request. + + \image udppackets.png UDP Packets + + The QUdpSocket class allows you to send and receive UDP + datagrams. It inherits QAbstractSocket, and it therefore shares + most of QTcpSocket's interface. The main difference is that + QUdpSocket transfers data as datagrams instead of as a continuous + stream of data. In short, a datagram is a data packet of limited + size (normally smaller than 512 bytes), containing the IP address + and port of the datagram's sender and receiver in addition to the + data being transferred. + + QUdpSocket supports IPv4 broadcasting. Broadcasting is often used + to implement network discovery protocols, such as finding which + host on the network has the most free hard disk space. One host + broadcasts a datagram to the network that all other hosts + receive. Each host that receives a request then sends a reply + back to the sender with its current amount of free disk space. + The originator waits until it has received replies from all + hosts, and can then choose the server with most free space to + store data. To broadcast a datagram, simply send it to the + special address QHostAddress::Broadcast (255.255.255.255), or + to your local network's broadcast address. + + QUdpSocket::bind() prepares the socket for accepting incoming + datagrams, much like QTcpServer::listen() for TCP servers. + Whenever one or more datagrams arrive, QUdpSocket emits the + \l{QUdpSocket::readyRead()}{readyRead()} signal. Call + QUdpSocket::readDatagram() to read the datagram. + + The \l{network/broadcastsender}{Broadcast Sender} and + \l{network/broadcastreceiver}{Broadcast Receiver} examples show how to + write a UDP sender and a UDP receiver using Qt. + + QUdpSocket also supports multicasting. The + \l{network/multicastsender}{Multicast Sender} and + \l{network/multicastreceiver}{Multicast Receiver} examples show how to use + write UDP multicast clients. + + \section1 Resolving Host Names using QHostInfo + + Before establishing a network connection, QTcpSocket and + QUdpSocket perform a name lookup, translating the host name + you're connecting to into an IP address. This operation is + usually performed using the DNS (Domain Name Service) protocol. + + QHostInfo provides a static function that lets you perform such a + lookup yourself. By calling QHostInfo::lookupHost() with a host + name, a QObject pointer, and a slot signature, QHostInfo will + perform the name lookup and invoke the given slot when the + results are ready. The actual lookup is done in a separate + thread, making use of the operating system's own methods for + performing name lookups. + + QHostInfo also provides a static function called + QHostInfo::fromName() that takes the host name as argument and + returns the results. In this case, the name lookup is performed + in the same thread as the caller. This overload is useful for + non-GUI applications or for doing name lookups in a separate, + non-GUI thread. (Calling this function in a GUI thread may cause + your user interface to freeze while the function blocks as + it performs the lookup.) + + \section1 Support for Network Proxies + + Network communication with Qt can be performed through proxies, + which direct or filter network traffic between local and remote + connections. + + Individual proxies are represented by the QNetworkProxy class, + which is used to describe and configure the connection to a proxy. + Proxy types which operate on different levels of network communication + are supported, with SOCKS 5 support allowing proxying of network + traffic at a low level, and HTTP and FTP proxying working at the + protocol level. See QNetworkProxy::ProxyType for more information. + + Proxying can be enabled on a per-socket basis or for all network + communication in an application. A newly opened socket can be + made to use a proxy by calling its QAbstractSocket::setProxy() + function before it is connected. Application-wide proxying can + be enabled for all subsequent socket connections through the use + of the QNetworkProxy::setApplicationProxy() function. + + Proxy factories are used to create policies for proxy use. + QNetworkProxyFactory supplies proxies based on queries for specific + proxy types. The queries themselves are encoded in QNetworkProxyQuery + objects which enable proxies to be selected based on key criteria, + such as the purpose of the proxy (TCP, UDP, TCP server, URL request), + local port, remote host and port, and the protocol in use (HTTP, FTP, + etc.). + + QNetworkProxyFactory::proxyForQuery() is used to query the factory + directly. An application-wide policy for proxying can be implemented + by passing a factory to QNetworkProxyFactory::setApplicationProxyFactory() + and a custom proxying policy can be created by subclassing + QNetworkProxyFactory; see the class documentation for details. + + \section1 Bearer Management Support + + Bearer Management controls the connectivity state of the device such that + the application can start or stop network interfaces and roam + transparently between access points. + + The QNetworkConfigurationManager class manages the list of network + configurations known to the device. A network configuration describes the + set of parameters used to start a network interface and is represented by + the QNetworkConfiguration class. + + A network interface is started by openning a QNetworkSession based on a + given network configuration. In most situations creating a network session + based on the platform specified default network configuration is + appropriate. The default network configuration is returned by the + QNetworkConfigurationManager::defaultConfiguration() function. + + On some platforms it is a platform requirement that the application open a + network session before any network operations can be performed. This can be + tested by the presents of the + QNetworkConfigurationManager::NetworkSessionRequired flag in the value + returned by the QNetworkConfigurationManager::capabilities() function. + + \sa {Bearer Management} +*/ diff --git a/doc/src/network/network-programming/ssl.qdoc b/doc/src/network/network-programming/ssl.qdoc new file mode 100644 index 0000000000..0bbcd8afb7 --- /dev/null +++ b/doc/src/network/network-programming/ssl.qdoc @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page ssl.html + \title Secure Sockets Layer (SSL) Classes + \brief Classes for secure communication over network sockets. + \ingroup qt-network + + \keyword SSL + + The classes below provide support for secure network communication using + the Secure Sockets Layer (SSL) protocol, using the \l{OpenSSL Toolkit} to + perform encryption and protocol handling. + + See the \l{General Qt Requirements} page for information about the + versions of OpenSSL that are known to work with Qt. + + \section1 Enabling and Disabling SSL Support + + When building Qt from source, the configuration system checks for the presence + of the \c{openssl/opensslv.h} header provided by source or developer packages + of OpenSSL. + + By default, an SSL-enabled Qt library dynamically loads any installed OpenSSL + library at run-time. However, it is possible to link against the library at + compile-time by configuring Qt with the \c{-openssl-linked} option. + + When building a version of Qt linked against OpenSSL, the build system will + attempt to link with libssl and libcrypt libraries located in the default + location on the developer's system. This location is configurable: + set the \c OPENSSL_LIBS environment variable to contain the linker options + required to link Qt against the installed library. For example, on a Unix/Linux + system: + + \code + ./configure -openssl-linked OPENSSL_LIBS='-L/opt/ssl/lib -lssl -lcrypto' + \endcode + + To disable SSL support in a Qt build, configure Qt with the \c{-no-openssl} + option. + + \section1 Licensing Information + + \note Due to import and export restrictions in some parts of the world, we + are unable to supply the OpenSSL Toolkit with Qt packages. Developers wishing + to use SSL communication in their deployed applications should either ensure + that their users have the appropriate libraries installed, or they should + consult a suitably qualified legal professional to ensure that applications + using code from the OpenSSL project are correctly certified for import + and export in relevant regions of the world. + + When the QtNetwork module is built with SSL support, the library is linked + against OpenSSL in a way that requires OpenSSL license compliance. +*/ diff --git a/doc/src/network/qtnetwork.qdoc b/doc/src/network/qtnetwork.qdoc new file mode 100644 index 0000000000..084cebd497 --- /dev/null +++ b/doc/src/network/qtnetwork.qdoc @@ -0,0 +1,18 @@ +/*! + \module QtNetwork + \title QtNetwork Module + \ingroup modules + + \brief The QtNetwork module provides classes to make network programming + easier and portable. + + To include the definitions of the module's classes, use the + following directive: + + \snippet doc/src/snippets/code/doc_src_qtnetwork.cpp 1 + + To link against the module, add this line to your \l qmake \c + .pro file: + + \snippet doc/src/snippets/code/doc_src_qtnetwork.pro 0 +*/ diff --git a/doc/src/objectmodel/metaobjects.qdoc b/doc/src/objectmodel/metaobjects.qdoc deleted file mode 100644 index 597210e789..0000000000 --- a/doc/src/objectmodel/metaobjects.qdoc +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page metaobjects.html - \title The Meta-Object System - \brief An overview of Qt's meta-object system and introspection capabilities. - - \ingroup qt-basic-concepts - \keyword meta-object - \target Meta-Object System - - Qt's meta-object system provides the signals and slots mechanism for - inter-object communication, run-time type information, and the dynamic - property system. - - The meta-object system is based on three things: - - \list 1 - \o The \l QObject class provides a base class for objects that can - take advantage of the meta-object system. - \o The Q_OBJECT macro inside the private section of the class - declaration is used to enable meta-object features, such as - dynamic properties, signals, and slots. - \o The \l{moc}{Meta-Object Compiler} (\c moc) supplies each - QObject subclass with the necessary code to implement - meta-object features. - \endlist - - The \c moc tool reads a C++ source file. If it finds one or more - class declarations that contain the Q_OBJECT macro, it - produces another C++ source file which contains the meta-object - code for each of those classes. This generated source file is - either \c{#include}'d into the class's source file or, more - usually, compiled and linked with the class's implementation. - - In addition to providing the \l{signals and slots} mechanism for - communication between objects (the main reason for introducing - the system), the meta-object code provides the following - additional features: - - \list - \o QObject::metaObject() returns the associated - \l{QMetaObject}{meta-object} for the class. - \o QMetaObject::className() returns the class name as a - string at run-time, without requiring native run-time type information - (RTTI) support through the C++ compiler. - \o QObject::inherits() function returns whether an object is an - instance of a class that inherits a specified class within the - QObject inheritance tree. - \o QObject::tr() and QObject::trUtf8() translate strings for - \l{Internationalization with Qt}{internationalization}. - \o QObject::setProperty() and QObject::property() - dynamically set and get properties by name. - \o QMetaObject::newInstance() constructs a new instance of the class. - \endlist - - \target qobjectcast - It is also possible to perform dynamic casts using qobject_cast() - on QObject classes. The qobject_cast() function behaves similarly - to the standard C++ \c dynamic_cast(), with the advantages - that it doesn't require RTTI support and it works across dynamic - library boundaries. It attempts to cast its argument to the pointer - type specified in angle-brackets, returning a non-zero pointer if the - object is of the correct type (determined at run-time), or 0 - if the object's type is incompatible. - - For example, let's assume \c MyWidget inherits from QWidget and - is declared with the Q_OBJECT macro: - - \snippet doc/src/snippets/qtcast/qtcast.cpp 0 - - The \c obj variable, of type \c{QObject *}, actually refers to a - \c MyWidget object, so we can cast it appropriately: - - \snippet doc/src/snippets/qtcast/qtcast.cpp 1 - - The cast from QObject to QWidget is successful, because the - object is actually a \c MyWidget, which is a subclass of QWidget. - Since we know that \c obj is a \c MyWidget, we can also cast it to - \c{MyWidget *}: - - \snippet doc/src/snippets/qtcast/qtcast.cpp 2 - - The cast to \c MyWidget is successful because qobject_cast() - makes no distinction between built-in Qt types and custom types. - - \snippet doc/src/snippets/qtcast/qtcast.cpp 3 - \snippet doc/src/snippets/qtcast/qtcast.cpp 4 - - The cast to QLabel, on the other hand, fails. The pointer is then - set to 0. This makes it possible to handle objects of different - types differently at run-time, based on the type: - - \snippet doc/src/snippets/qtcast/qtcast.cpp 5 - \snippet doc/src/snippets/qtcast/qtcast.cpp 6 - - While it is possible to use QObject as a base class without the - Q_OBJECT macro and without meta-object code, neither signals - and slots nor the other features described here will be available - if the Q_OBJECT macro is not used. From the meta-object - system's point of view, a QObject subclass without meta code is - equivalent to its closest ancestor with meta-object code. This - means for example, that QMetaObject::className() will not return - the actual name of your class, but the class name of this - ancestor. - - Therefore, we strongly recommend that all subclasses of QObject - use the Q_OBJECT macro regardless of whether or not they - actually use signals, slots, and properties. - - \sa QMetaObject, {Qt's Property System}, {Signals and Slots} -*/ diff --git a/doc/src/objectmodel/object.qdoc b/doc/src/objectmodel/object.qdoc deleted file mode 100644 index d843f834a5..0000000000 --- a/doc/src/objectmodel/object.qdoc +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page object.html - \title Object Model - \ingroup qt-basic-concepts - \brief A description of the powerful features made possible by Qt's dynamic object model. - - The standard C++ object model provides very efficient runtime - support for the object paradigm. But its static nature is - inflexibile in certain problem domains. Graphical user interface - programming is a domain that requires both runtime efficiency and - a high level of flexibility. Qt provides this, by combining the - speed of C++ with the flexibility of the Qt Object Model. - - Qt adds these features to C++: - - \list - \o a very powerful mechanism for seamless object - communication called \l{signals and slots} - \o queryable and designable \l{Qt's Property System}{object - properties} - \o powerful \l{The Event System}{events and event filters} - \o contextual \l{i18n}{string translation for internationalization} - \o sophisticated interval driven \l timers that make it possible - to elegantly integrate many tasks in an event-driven GUI - \o hierarchical and queryable \l{Object Trees & Ownership}{object - trees} that organize object ownership in a natural way - \o guarded pointers (QPointer) that are automatically - set to 0 when the referenced object is destroyed, unlike normal C++ - pointers which become dangling pointers when their objects are destroyed - \o a \l{metaobjects.html#qobjectcast}{dynamic cast} that works across - library boundaries. - \endlist - - Many of these Qt features are implemented with standard C++ - techniques, based on inheritance from QObject. Others, like the - object communication mechanism and the dynamic property system, - require the \l{Meta-Object System} provided - by Qt's own \l{moc}{Meta-Object Compiler (moc)}. - - The meta-object system is a C++ extension that makes the language - better suited to true component GUI programming. Although - templates can be used to extend C++, the meta-object system - provides benefits using standard C++ that cannot be achieved with - templates; see \l{Why Doesn't Qt Use Templates for Signals and - Slots?} - - \section1 Important Classes - - These classes form the basis of the Qt Object Model. - - \annotatedlist objectmodel - - \target Identity vs Value - \section1 Qt Objects: Identity vs Value - - Some of the added features listed above for the Qt Object Model, - require that we think of Qt Objects as identities, not values. - Values are copied or assigned; identities are cloned. Cloning - means to create a new identity, not an exact copy of the old - one. For example, twins have different identities. They may look - identical, but they have different names, different locations, and - may have completely different social networks. - - Then cloning an identity is a more complex operation than copying - or assigning a value. We can see what this means in the Qt Object - Model. - - \bold{A Qt Object...} - - \list - - \o might have a unique \l{QObject::objectName()}. If we copy a Qt - Object, what name should we give the copy? - - \o has a location in an \l{Object Trees & Ownership} - {object hierarchy}. If we copy a Qt Object, where should the copy - be located? - - \o can be connected to other Qt Objects to emit signals to them or - to receive signals emitted by them. If we copy a Qt Object, how - should we transfer these connections to the copy? - - \o can have \l{Qt's Property System} {new properties} added to it - at runtime that are not declared in the C++ class. If we copy a Qt - Object, should the copy include the properties that were added to - the original? - - \endlist - - For these reasons, Qt Objects should be treated as identities, not - as values. Identities are cloned, not copied or assigned, and - cloning an identity is a more complex operation than copying or - assigning a value. Therefore, QObject and all subclasses of - QObject (direct or indirect) have their \l{No copy constructor} - {copy constructor and assignment operator} disabled. - - */ diff --git a/doc/src/objectmodel/objecttrees.qdoc b/doc/src/objectmodel/objecttrees.qdoc deleted file mode 100644 index 46921106b6..0000000000 --- a/doc/src/objectmodel/objecttrees.qdoc +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page objecttrees.html - \title Object Trees & Ownership - \ingroup qt-basic-concepts - \brief Information about the parent-child pattern used to describe - object ownership in Qt. - - \section1 Overview - - \link QObject QObjects\endlink organize themselves in object trees. - When you create a QObject with another object as parent, it's added to - the parent's \link QObject::children() children() \endlink list, and - is deleted when the parent is. It turns out that this approach fits - the needs of GUI objects very well. For example, a \l QShortcut - (keyboard shortcut) is a child of the relevant window, so when the - user closes that window, the shorcut is deleted too. - - \l QWidget, the base class of everything that appears on the screen, - extends the parent-child relationship. A child normally also becomes a - child widget, i.e. it is displayed in its parent's coordinate system - and is graphically clipped by its parent's boundaries. For example, - when the application deletes a message box after it has been - closed, the message box's buttons and label are also deleted, just as - we'd want, because the buttons and label are children of the message - box. - - You can also delete child objects yourself, and they will remove - themselves from their parents. For example, when the user removes a - toolbar it may lead to the application deleting one of its \l QToolBar - objects, in which case the tool bar's \l QMainWindow parent would - detect the change and reconfigure its screen space accordingly. - - The debugging functions \l QObject::dumpObjectTree() and \l - QObject::dumpObjectInfo() are often useful when an application looks or - acts strangely. - - \target note on the order of construction/destruction of QObjects - \section1 Construction/Destruction Order of QObjects - - When \l {QObject} {QObjects} are created on the heap (i.e., created - with \e new), a tree can be constructed from them in any order, and - later, the objects in the tree can be destroyed in any order. When any - QObject in the tree is deleted, if the object has a parent, the - destructor automatically removes the object from its parent. If the - object has children, the destructor automatically deletes each - child. No QObject is deleted twice, regardless of the order of - destruction. - - When \l {QObject} {QObjects} are created on the stack, the same - behavior applies. Normally, the order of destruction still doesn't - present a problem. Consider the following snippet: - - \snippet doc/src/snippets/code/doc_src_objecttrees.cpp 0 - - The parent, \c window, and the child, \c quit, are both \l {QObject} - {QObjects} because QPushButton inherits QWidget, and QWidget inherits - QObject. This code is correct: the destructor of \c quit is \e not - called twice because the C++ language standard \e {(ISO/IEC 14882:2003)} - specifies that destructors of local objects are called in the reverse - order of their constructors. Therefore, the destructor of - the child, \c quit, is called first, and it removes itself from its - parent, \c window, before the destructor of \c window is called. - - But now consider what happens if we swap the order of construction, as - shown in this second snippet: - - \snippet doc/src/snippets/code/doc_src_objecttrees.cpp 1 - - In this case, the order of destruction causes a problem. The parent's - destructor is called first because it was created last. It then calls - the destructor of its child, \c quit, which is incorrect because \c - quit is a local variable. When \c quit subsequently goes out of scope, - its destructor is called again, this time correctly, but the damage has - already been done. -*/ diff --git a/doc/src/objectmodel/properties.qdoc b/doc/src/objectmodel/properties.qdoc deleted file mode 100644 index befbde190b..0000000000 --- a/doc/src/objectmodel/properties.qdoc +++ /dev/null @@ -1,273 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page properties.html - \title The Property System - \brief An overview of Qt's property system. - - \ingroup qt-basic-concepts - \target Qt's Property System - - Qt provides a sophisticated property system similar to the ones - supplied by some compiler vendors. However, as a compiler- and - platform-independent library, Qt does not rely on non-standard - compiler features like \c __property or \c [property]. The Qt - solution works with \e any standard C++ compiler on every platform - Qt supports. It is based on the \l {Meta-Object System} that also - provides inter-object communication via \l{signals and slots}. - - \section1 Requirements for Declaring Properties - - To declare a property, use the \l {Q_PROPERTY()} {Q_PROPERTY()} - macro in a class that inherits QObject. - - \snippet doc/src/snippets/code/doc_src_properties.cpp 0 - - Here are some typical examples of property declarations taken from - class QWidget. - - \snippet doc/src/snippets/code/doc_src_properties.cpp 1 - - A property behaves like a class data member, but it has additional - features accessible through the \l {Meta-Object System}. - - \list - - \o A \c READ accessor function is required. It is for reading the - property value. Ideally, a const function is used for this purpose, - and it must return either the property's type or a pointer or - reference to that type. e.g., QWidget::focus is a read-only property - with \c READ function, QWidget::hasFocus(). - - \o A \c WRITE accessor function is optional. It is for setting the - property value. It must return void and must take exactly one - argument, either of the property's type or a pointer or reference - to that type. e.g., QWidget::enabled has the \c WRITE function - QWidget::setEnabled(). Read-only properties do not need \c WRITE - functions. e.g., QWidget::focus has no \c WRITE function. - - \o A \c RESET function is optional. It is for setting the property - back to its context specific default value. e.g., QWidget::cursor - has the typical \c READ and \c WRITE functions, QWidget::cursor() - and QWidget::setCursor(), and it also has a \c RESET function, - QWidget::unsetCursor(), since no call to QWidget::setCursor() can - mean \e {reset to the context specific cursor}. The \c RESET - function must return void and take no parameters. - - \o A \c NOTIFY signal is optional. If defined, it should specify one - existing signal in that class that is emitted whenever the value - of the property changes. - - \o A \c REVISION number is optional. If included, it defines the - the property and its notifier signal to be used in a particular - revision of the API that is exposed to QML. - - \o The \c DESIGNABLE attribute indicates whether the property - should be visible in the property editor of GUI design tool (e.g., - \l {Qt Designer}). Most properties are \c DESIGNABLE (default - true). Instead of true or false, you can specify a boolean - member function. - - \o The \c SCRIPTABLE attribute indicates whether this property - should be accessible by a scripting engine (default true). - Instead of true or false, you can specify a boolean member - function. - - \o The \c STORED attribute indicates whether the property should - be thought of as existing on its own or as depending on other - values. It also indicates whether the property value must be saved - when storing the object's state. Most properties are \c STORED - (default true), but e.g., QWidget::minimumWidth() has \c STORED - false, because its value is just taken from the width component - of property QWidget::minimumSize(), which is a QSize. - - \o The \c USER attribute indicates whether the property is - designated as the user-facing or user-editable property for the - class. Normally, there is only one \c USER property per class - (default false). e.g., QAbstractButton::checked is the user - editable property for (checkable) buttons. Note that QItemDelegate - gets and sets a widget's \c USER property. - - \o The presence of the \c CONSTANT attibute indicates that the property - value is constant. For a given object instance, the READ method of a - constant property must return the same value every time it is called. This - constant value may be different for different instances of the object. A - constant property cannot have a WRITE method or a NOTIFY signal. - - \o The presence of the \c FINAL attribute indicates that the property - will not be overridden by a derived class. This can be used for performance - optimizations in some cases, but is not enforced by moc. Care must be taken - never to override a \c FINAL property. - - \endlist - - The \c READ, \c WRITE, and \c RESET functions can be inherited. - They can also be virtual. When they are inherited in classes where - multiple inheritance is used, they must come from the first - inherited class. - - The property type can be any type supported by QVariant, or it can - be a user-defined type. In this example, class QDate is considered - to be a user-defined type. - - \snippet doc/src/snippets/code/doc_src_properties.cpp 2 - - Because QDate is user-defined, you must include the \c{} - header file with the property declaration. - - For QMap, QList, and QValueList properties, the property value is - a QVariant whose value is the entire list or map. Note that the - Q_PROPERTY string cannot contain commas, because commas separate - macro arguments. Therefore, you must use \c QMap as the property - type instead of \c QMap. For consistency, also - use \c QList and \c QValueList instead of \c QList and - \c QValueList. - - \section1 Reading and Writing Properties with the Meta-Object System - - A property can be read and written using the generic functions - QObject::property() and QObject::setProperty(), without knowing - anything about the owning class except the property's name. In - the code snippet below, the call to QAbstractButton::setDown() and - the call to QObject::setProperty() both set property "down". - - \snippet doc/src/snippets/code/doc_src_properties.cpp 3 - - Accessing a property through its \c WRITE accessor is the better - of the two, because it is faster and gives better diagnostics at - compile time, but setting the property this way requires that you - know about the class at compile time. Accessing properties by name - lets you access classes you don't know about at compile time. You - can \e discover a class's properties at run time by querying its - QObject, QMetaObject, and \l {QMetaProperty} {QMetaProperties}. - - \snippet doc/src/snippets/code/doc_src_properties.cpp 4 - - In the above snippet, QMetaObject::property() is used to get \l - {QMetaProperty} {metadata} about each property defined in some - unknown class. The property name is fetched from the metadata and - passed to QObject::property() to get the \l {QVariant} {value} of - the property in the current \l {QObject}{object}. - - \section1 A Simple Example - - Suppose we have a class MyClass, which is derived from QObject and - which uses the Q_OBJECT macro in its private section. We want to - declare a property in MyClass to keep track of a priorty - value. The name of the property will be \e priority, and its type - will be an enumeration type named \e Priority, which is defined in - MyClass. - - We declare the property with the Q_PROPERTY() macro in the private - section of the class. The required \c READ function is named \c - priority, and we include a \c WRITE function named \c setPriority. - The enumeration type must be registered with the \l {Meta-Object - System} using the Q_ENUMS() macro. Registering an enumeration type - makes the enumerator names available for use in calls to - QObject::setProperty(). We must also provide our own declarations - for the \c READ and \c WRITE functions. The declaration of MyClass - then might look like this: - - \snippet doc/src/snippets/code/doc_src_properties.cpp 5 - - The \c READ function is const and returns the property type. The - \c WRITE function returns void and has exactly one parameter of - the property type. The meta-object compiler enforces these - requirements. - - Given a pointer to an instance of MyClass or a pointer to a - QObject that is an instance of MyClass, we have two ways to set - its priority property: - - \snippet doc/src/snippets/code/doc_src_properties.cpp 6 - - In the example, the enumeration type that is the property type is - declared in MyClass and registered with the \l{Meta-Object System} - using the Q_ENUMS() macro. This makes the enumeration values - available as strings for use as in the call to setProperty(). Had - the enumeration type been declared in another class, its fully - qualified name (i.e., OtherClass::Priority) would be required, and - that other class would also have to inherit QObject and register - the enumeration type there using the Q_ENUMS() macro. - - A similar macro, Q_FLAGS(), is also available. Like Q_ENUMS(), it - registers an enumeration type, but it marks the type as being a - set of \e flags, i.e. values that can be OR'd together. An I/O - class might have enumeration values \c Read and \c Write and then - QObject::setProperty() could accept \c{Read | Write}. Q_FLAGS() - should be used to register this enumeration type. - - \section1 Dynamic Properties - - QObject::setProperty() can also be used to add \e new properties - to an instance of a class at runtime. When it is called with a - name and a value, if a property with the given name exists in the - QObject, and if the given value is compatible with the property's - type, the value is stored in the property, and true is returned. - If the value is \e not compatible with the property's type, the - property is \e not changed, and false is returned. But if the - property with the given name doesn't exist in the QObject (i.e., - if it wasn't declared with Q_PROPERTY(), a new property with the - given name and value is automatically added to the QObject, but - false is still returned. This means that a return of false can't - be used to determine whether a particular property was actually - set, unless you know in advance that the property already exists - in the QObject. - - Note that \e dynamic properties are added on a per instance basis, - i.e., they are added to QObject, not QMetaObject. A property can - be removed from an instance by passing the property name and an - invalid QVariant value to QObject::setProperty(). The default - constructor for QVariant constructs an invalid QVariant. - - Dynamic properties can be queried with QObject::property(), just - like properties declared at compile time with Q_PROPERTY(). - - \sa {Meta-Object System}, {Signals and Slots} - - \section1 Properties and Custom Types - - Custom types used by properties need to be registered using the - Q_DECLARE_METATYPE() macro so that their values can be stored in - QVariant objects. This makes them suitable for use with both - static properties declared using the Q_PROPERTY() macro in class - definitions and dynamic properties created at run-time. - - \sa Q_DECLARE_METATYPE(), QMetaType, QVariant - - \section1 Adding Additional Information to a Class - - Connected to the property system is an additional macro, - Q_CLASSINFO(), that can be used to attach additional - \e{name}--\e{value} pairs to a class's meta-object, for example: - - \snippet doc/src/snippets/code/doc_src_properties.cpp 7 - - Like other meta-data, class information is accessible at run-time - through the meta-object; see QMetaObject::classInfo() for details. -*/ diff --git a/doc/src/objectmodel/signalsandslots.qdoc b/doc/src/objectmodel/signalsandslots.qdoc deleted file mode 100644 index 2f8646ea1c..0000000000 --- a/doc/src/objectmodel/signalsandslots.qdoc +++ /dev/null @@ -1,451 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page signalsandslots.html - \title Signals & Slots - \ingroup qt-basic-concepts - \brief An overview of Qt's signals and slots inter-object - communication mechanism. - - Signals and slots are used for communication between objects. The - signals and slots mechanism is a central feature of Qt and - probably the part that differs most from the features provided by - other frameworks. - - \tableofcontents - - \section1 Introduction - - In GUI programming, when we change one widget, we often want - another widget to be notified. More generally, we want objects of - any kind to be able to communicate with one another. For example, - if a user clicks a \gui{Close} button, we probably want the - window's \l{QWidget::close()}{close()} function to be called. - - Older toolkits achieve this kind of communication using - callbacks. A callback is a pointer to a function, so if you want - a processing function to notify you about some event you pass a - pointer to another function (the callback) to the processing - function. The processing function then calls the callback when - appropriate. Callbacks have two fundamental flaws: Firstly, they - are not type-safe. We can never be certain that the processing - function will call the callback with the correct arguments. - Secondly, the callback is strongly coupled to the processing - function since the processing function must know which callback - to call. - - \section1 Signals and Slots - - In Qt, we have an alternative to the callback technique: We use - signals and slots. A signal is emitted when a particular event - occurs. Qt's widgets have many predefined signals, but we can - always subclass widgets to add our own signals to them. A slot - is a function that is called in response to a particular signal. - Qt's widgets have many pre-defined slots, but it is common - practice to subclass widgets and add your own slots so that you - can handle the signals that you are interested in. - - \img abstract-connections.png - \omit - \caption An abstract view of some signals and slots connections - \endomit - - The signals and slots mechanism is type safe: The signature of a - signal must match the signature of the receiving slot. (In fact a - slot may have a shorter signature than the signal it receives - because it can ignore extra arguments.) Since the signatures are - compatible, the compiler can help us detect type mismatches. - Signals and slots are loosely coupled: A class which emits a - signal neither knows nor cares which slots receive the signal. - Qt's signals and slots mechanism ensures that if you connect a - signal to a slot, the slot will be called with the signal's - parameters at the right time. Signals and slots can take any - number of arguments of any type. They are completely type safe. - - All classes that inherit from QObject or one of its subclasses - (e.g., QWidget) can contain signals and slots. Signals are emitted by - objects when they change their state in a way that may be interesting - to other objects. This is all the object does to communicate. It - does not know or care whether anything is receiving the signals it - emits. This is true information encapsulation, and ensures that the - object can be used as a software component. - - Slots can be used for receiving signals, but they are also normal - member functions. Just as an object does not know if anything receives - its signals, a slot does not know if it has any signals connected to - it. This ensures that truly independent components can be created with - Qt. - - You can connect as many signals as you want to a single slot, and a - signal can be connected to as many slots as you need. It is even - possible to connect a signal directly to another signal. (This will - emit the second signal immediately whenever the first is emitted.) - - Together, signals and slots make up a powerful component programming - mechanism. - - \section1 A Small Example - - A minimal C++ class declaration might read: - - \snippet doc/src/snippets/signalsandslots/signalsandslots.h 0 - - A small QObject-based class might read: - - \snippet doc/src/snippets/signalsandslots/signalsandslots.h 1 - \codeline - \snippet doc/src/snippets/signalsandslots/signalsandslots.h 2 - \snippet doc/src/snippets/signalsandslots/signalsandslots.h 3 - - The QObject-based version has the same internal state, and provides - public methods to access the state, but in addition it has support - for component programming using signals and slots. This class can - tell the outside world that its state has changed by emitting a - signal, \c{valueChanged()}, and it has a slot which other objects - can send signals to. - - All classes that contain signals or slots must mention - Q_OBJECT at the top of their declaration. They must also derive - (directly or indirectly) from QObject. - - Slots are implemented by the application programmer. - Here is a possible implementation of the \c{Counter::setValue()} - slot: - - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 0 - - The \c{emit} line emits the signal \c valueChanged() from the - object, with the new value as argument. - - In the following code snippet, we create two \c Counter objects - and connect the first object's \c valueChanged() signal to the - second object's \c setValue() slot using QObject::connect(): - - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 1 - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 2 - \codeline - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 3 - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 4 - - Calling \c{a.setValue(12)} makes \c{a} emit a - \c{valueChanged(12)} signal, which \c{b} will receive in its - \c{setValue()} slot, i.e. \c{b.setValue(12)} is called. Then - \c{b} emits the same \c{valueChanged()} signal, but since no slot - has been connected to \c{b}'s \c{valueChanged()} signal, the - signal is ignored. - - Note that the \c{setValue()} function sets the value and emits - the signal only if \c{value != m_value}. This prevents infinite - looping in the case of cyclic connections (e.g., if - \c{b.valueChanged()} were connected to \c{a.setValue()}). - - By default, for every connection you make, a signal is emitted; - two signals are emitted for duplicate connections. You can break - all of these connections with a single disconnect() call. - If you pass the Qt::UniqueConnection \a type, the connection will only - be made if it is not a duplicate. If there is already a duplicate - (exact same signal to the exact same slot on the same objects), - the connection will fail and connect will return false - - This example illustrates that objects can work together without needing to - know any information about each other. To enable this, the objects only - need to be connected together, and this can be achieved with some simple - QObject::connect() function calls, or with \c{uic}'s - \l{Using a Designer UI File in Your Application#Automatic Connections} - {automatic connections} feature. - - \section1 Building the Example - - The C++ preprocessor changes or removes the \c{signals}, - \c{slots}, and \c{emit} keywords so that the compiler is - presented with standard C++. - - By running the \l moc on class definitions that contain signals - or slots, a C++ source file is produced which should be compiled - and linked with the other object files for the application. If - you use \l qmake, the makefile rules to automatically invoke \c - moc will be added to your project's makefile. - - \section1 Signals - - Signals are emitted by an object when its internal state has changed - in some way that might be interesting to the object's client or owner. - Only the class that defines a signal and its subclasses can emit the - signal. - - When a signal is emitted, the slots connected to it are usually - executed immediately, just like a normal function call. When this - happens, the signals and slots mechanism is totally independent of - any GUI event loop. Execution of the code following the \c emit - statement will occur once all slots have returned. The situation is - slightly different when using \l{Qt::ConnectionType}{queued - connections}; in such a case, the code following the \c emit keyword - will continue immediately, and the slots will be executed later. - - If several slots are connected to one signal, the slots will be - executed one after the other, in the order they have been connected, - when the signal is emitted. - - Signals are automatically generated by the \l moc and must not be - implemented in the \c .cpp file. They can never have return types - (i.e. use \c void). - - A note about arguments: Our experience shows that signals and slots - are more reusable if they do not use special types. If - QScrollBar::valueChanged() were to use a special type such as the - hypothetical QScrollBar::Range, it could only be connected to - slots designed specifically for QScrollBar. Connecting different - input widgets together would be impossible. - - \section1 Slots - - A slot is called when a signal connected to it is emitted. Slots are - normal C++ functions and can be called normally; their only special - feature is that signals can be connected to them. - - Since slots are normal member functions, they follow the normal C++ - rules when called directly. However, as slots, they can be invoked - by any component, regardless of its access level, via a signal-slot - connection. This means that a signal emitted from an instance of an - arbitrary class can cause a private slot to be invoked in an instance - of an unrelated class. - - You can also define slots to be virtual, which we have found quite - useful in practice. - - Compared to callbacks, signals and slots are slightly slower - because of the increased flexibility they provide, although the - difference for real applications is insignificant. In general, - emitting a signal that is connected to some slots, is - approximately ten times slower than calling the receivers - directly, with non-virtual function calls. This is the overhead - required to locate the connection object, to safely iterate over - all connections (i.e. checking that subsequent receivers have not - been destroyed during the emission), and to marshall any - parameters in a generic fashion. While ten non-virtual function - calls may sound like a lot, it's much less overhead than any \c - new or \c delete operation, for example. As soon as you perform a - string, vector or list operation that behind the scene requires - \c new or \c delete, the signals and slots overhead is only - responsible for a very small proportion of the complete function - call costs. - - The same is true whenever you do a system call in a slot; or - indirectly call more than ten functions. On an i586-500, you can - emit around 2,000,000 signals per second connected to one - receiver, or around 1,200,000 per second connected to two - receivers. The simplicity and flexibility of the signals and - slots mechanism is well worth the overhead, which your users - won't even notice. - - Note that other libraries that define variables called \c signals - or \c slots may cause compiler warnings and errors when compiled - alongside a Qt-based application. To solve this problem, \c - #undef the offending preprocessor symbol. - - \section1 Meta-Object Information - - The meta-object compiler (\l moc) parses the class declaration in - a C++ file and generates C++ code that initializes the - meta-object. The meta-object contains the names of all the signal - and slot members, as well as pointers to these functions. - - The meta-object contains additional information such as the - object's \link QObject::className() class name\endlink. You can - also check if an object \link QObject::inherits() - inherits\endlink a specific class, for example: - - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 5 - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 6 - - The meta-object information is also used by qobject_cast(), which - is similar to QObject::inherits() but is less error-prone: - - \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 7 - - See \l{Meta-Object System} for more information. - - \section1 A Real Example - - Here is a simple commented example of a widget. - - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 0 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 1 - \codeline - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 2 - \codeline - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 3 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 4 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 5 - - \c LcdNumber inherits QObject, which has most of the signal-slot - knowledge, via QFrame and QWidget. It is somewhat similar to the - built-in QLCDNumber widget. - - The Q_OBJECT macro is expanded by the preprocessor to declare - several member functions that are implemented by the \c{moc}; if - you get compiler errors along the lines of "undefined reference - to vtable for \c{LcdNumber}", you have probably forgotten to - \l{moc}{run the moc} or to include the moc output in the link - command. - - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 6 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 7 - - It's not obviously relevant to the moc, but if you inherit - QWidget you almost certainly want to have the \c parent argument - in your constructor and pass it to the base class's constructor. - - Some destructors and member functions are omitted here; the \c - moc ignores member functions. - - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 8 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 9 - - \c LcdNumber emits a signal when it is asked to show an impossible - value. - - If you don't care about overflow, or you know that overflow - cannot occur, you can ignore the \c overflow() signal, i.e. don't - connect it to any slot. - - If on the other hand you want to call two different error - functions when the number overflows, simply connect the signal to - two different slots. Qt will call both (in the order they were connected). - - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 10 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 11 - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 12 - \codeline - \snippet doc/src/snippets/signalsandslots/lcdnumber.h 13 - - A slot is a receiving function used to get information about - state changes in other widgets. \c LcdNumber uses it, as the code - above indicates, to set the displayed number. Since \c{display()} - is part of the class's interface with the rest of the program, - the slot is public. - - Several of the example programs connect the - \l{QScrollBar::valueChanged()}{valueChanged()} signal of a - QScrollBar to the \c display() slot, so the LCD number - continuously shows the value of the scroll bar. - - Note that \c display() is overloaded; Qt will select the - appropriate version when you connect a signal to the slot. With - callbacks, you'd have to find five different names and keep track - of the types yourself. - - Some irrelevant member functions have been omitted from this - example. - - \section1 Signals And Slots With Default Arguments - - The signatures of signals and slots may contain arguments, and the - arguments can have default values. Consider QObject::destroyed(): - - \code - void destroyed(QObject* = 0); - \endcode - - When a QObject is deleted, it emits this QObject::destroyed() - signal. We want to catch this signal, wherever we might have a - dangling reference to the deleted QObject, so we can clean it up. - A suitable slot signature might be: - - \code - void objectDestroyed(QObject* obj = 0); - \endcode - - To connect the signal to the slot, we use QObject::connect() and - the \c{SIGNAL()} and \c{SLOT()} macros. The rule about whether to - include arguments or not in the \c{SIGNAL()} and \c{SLOT()} - macros, if the arguments have default values, is that the - signature passed to the \c{SIGNAL()} macro must \e not have fewer - arguments than the signature passed to the \c{SLOT()} macro. - - All of these would work: - \code - connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed(Qbject*))); - connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed())); - connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed())); - \endcode - But this one won't work: - \code - connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed(QObject*))); - \endcode - - ...because the slot will be expecting a QObject that the signal - will not send. This connection will report a runtime error. - - \section1 Advanced Signals and Slots Usage - - For cases where you may require information on the sender of the - signal, Qt provides the QObject::sender() function, which returns - a pointer to the object that sent the signal. - - The QSignalMapper class is provided for situations where many - signals are connected to the same slot and the slot needs to - handle each signal differently. - - Suppose you have three push buttons that determine which file you - will open: "Tax File", "Accounts File", or "Report File". - - In order to open the correct file, you use QSignalMapper::setMapping() to - map all the clicked() signals to a QSignalMapper object. Then you connect - the file's QPushButton::clicked() signal to the QSignalMapper::map() slot. - - \snippet doc/src/snippets/signalmapper/filereader.cpp 0 - - Then, you connect the \l{QSignalMapper::}{mapped()} signal to - \c{readFile()} where a different file will be opened, depending on - which push button is pressed. - - \snippet doc/src/snippets/signalmapper/filereader.cpp 1 - - \note The following code will compile and run, but due to signature normalization, the code will be slower. - - \snippet doc/src/snippets/signalmapper/filereader.cpp 2 - - \sa {Meta-Object System}, {Qt's Property System} - - \target 3rd Party Signals and Slots - \section2 Using Qt with 3rd Party Signals and Slots - - It is possible to use Qt with a 3rd party signal/slot mechanism. - You can even use both mechanisms in the same project. Just add the - following line to your qmake project (.pro) file. - - \snippet doc/src/snippets/code/doc_src_containers.cpp 22 - - It tells Qt not to define the moc keywords \c{signals}, \c{slots}, - and \c{emit}, because these names will be used by a 3rd party - library, e.g. Boost. Then to continue using Qt signals and slots - with the \c{no_keywords} flag, simply replace all uses of the Qt - moc keywords in your sources with the corresponding Qt macros - Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), and Q_EMIT. -*/ diff --git a/doc/src/painting-and-printing/coordsys.qdoc b/doc/src/painting-and-printing/coordsys.qdoc deleted file mode 100644 index 96eebd01e0..0000000000 --- a/doc/src/painting-and-printing/coordsys.qdoc +++ /dev/null @@ -1,461 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page coordsys.html - \title Coordinate System - \ingroup qt-graphics - \ingroup best-practices - \brief Information about the coordinate system used by the paint - system. - - The coordinate system is controlled by the QPainter - class. Together with the QPaintDevice and QPaintEngine classes, - QPainter form the basis of Qt's painting system, Arthur. QPainter - is used to perform drawing operations, QPaintDevice is an - abstraction of a two-dimensional space that can be painted on - using a QPainter, and QPaintEngine provides the interface that the - painter uses to draw onto different types of devices. - - The QPaintDevice class is the base class of objects that can be - painted: Its drawing capabilities are inherited by the QWidget, - QPixmap, QPicture, QImage, and QPrinter classes. The default - coordinate system of a paint device has its origin at the top-left - corner. The \e x values increase to the right and the \e y values - increase downwards. The default unit is one pixel on pixel-based - devices and one point (1/72 of an inch) on printers. - - The mapping of the logical QPainter coordinates to the physical - QPaintDevice coordinates are handled by QPainter's transformation - matrix, viewport and "window". The logical and physical coordinate - systems coincide by default. QPainter also supports coordinate - transformations (e.g. rotation and scaling). - - \tableofcontents - - \section1 Rendering - - \section2 Logical Representation - - The size (width and height) of a graphics primitive always - correspond to its mathematical model, ignoring the width of the - pen it is rendered with: - - \table - \row - \o \inlineimage coordinatesystem-rect.png - \o \inlineimage coordinatesystem-line.png - \row - \o QRect(1, 2, 6, 4) - \o QLine(2, 7, 6, 1) - \endtable - - \section2 Aliased Painting - - When drawing, the pixel rendering is controlled by the - QPainter::Antialiasing render hint. - - The \l {QPainter::RenderHint}{RenderHint} enum is used to specify - flags to QPainter that may or may not be respected by any given - engine. The QPainter::Antialiasing value indicates that the engine - should antialias edges of primitives if possible, i.e. smoothing - the edges by using different color intensities. - - But by default the painter is \e aliased and other rules apply: - When rendering with a one pixel wide pen the pixels will be - rendered to the \e {right and below the mathematically defined - points}. For example: - - \table - \row - \o \inlineimage coordinatesystem-rect-raster.png - \o \inlineimage coordinatesystem-line-raster.png - - \row - \o - \snippet doc/src/snippets/code/doc_src_coordsys.cpp 0 - - \o - \snippet doc/src/snippets/code/doc_src_coordsys.cpp 1 - \endtable - - When rendering with a pen with an even number of pixels, the - pixels will be rendered symetrically around the mathematical - defined points, while rendering with a pen with an odd number of - pixels, the spare pixel will be rendered to the right and below - the mathematical point as in the one pixel case. See the QRectF - diagrams below for concrete examples. - - \table - \header - \o {3,1} QRectF - \row - \o \inlineimage qrect-diagram-zero.png - \o \inlineimage qrectf-diagram-one.png - \row - \o Logical representation - \o One pixel wide pen - \row - \o \inlineimage qrectf-diagram-two.png - \o \inlineimage qrectf-diagram-three.png - \row - \o Two pixel wide pen - \o Three pixel wide pen - \endtable - - Note that for historical reasons the return value of the - QRect::right() and QRect::bottom() functions deviate from the true - bottom-right corner of the rectangle. - - QRect's \l {QRect::right()}{right()} function returns \l - {QRect::left()}{left()} + \l {QRect::width()}{width()} - 1 and the - \l {QRect::bottom()}{bottom()} function returns \l - {QRect::top()}{top()} + \l {QRect::height()}{height()} - 1. The - bottom-right green point in the diagrams shows the return - coordinates of these functions. - - We recommend that you simply use QRectF instead: The QRectF class - defines a rectangle in the plane using floating point coordinates - for accuracy (QRect uses integer coordinates), and the - QRectF::right() and QRectF::bottom() functions \e do return the - true bottom-right corner. - - Alternatively, using QRect, apply \l {QRect::x()}{x()} + \l - {QRect::width()}{width()} and \l {QRect::y()}{y()} + \l - {QRect::height()}{height()} to find the bottom-right corner, and - avoid the \l {QRect::right()}{right()} and \l - {QRect::bottom()}{bottom()} functions. - - \section2 Anti-aliased Painting - - If you set QPainter's \l {QPainter::Antialiasing}{anti-aliasing} - render hint, the pixels will be rendered symetrically on both - sides of the mathematically defined points: - - \table - \row - \o \inlineimage coordinatesystem-rect-antialias.png - \o \inlineimage coordinatesystem-line-antialias.png - \row - \o - - \snippet doc/src/snippets/code/doc_src_coordsys.cpp 2 - - \o - \snippet doc/src/snippets/code/doc_src_coordsys.cpp 3 - \endtable - - \section1 Transformations - - By default, the QPainter operates on the associated device's own - coordinate system, but it also has complete support for affine - coordinate transformations. - - You can scale the coordinate system by a given offset using the - QPainter::scale() function, you can rotate it clockwise using the - QPainter::rotate() function and you can translate it (i.e. adding - a given offset to the points) using the QPainter::translate() - function. - - \table - \row - \o \inlineimage qpainter-clock.png - \o \inlineimage qpainter-rotation.png - \o \inlineimage qpainter-scale.png - \o \inlineimage qpainter-translation.png - \row - \o nop - \o \l {QPainter::rotate()}{rotate()} - \o \l {QPainter::scale()}{scale()} - \o \l {QPainter::translate()}{translate()} - \endtable - - You can also twist the coordinate system around the origin using - the QPainter::shear() function. See the \l {painting/affine}{Affine - Transformations} example for a visualization of a sheared coordinate - system. All the transformation operations operate on QPainter's - transformation matrix that you can retrieve using the - QPainter::worldTransform() function. A matrix transforms a point - in the plane to another point. - - If you need the same transformations over and over, you can also - use QTransform objects and the QPainter::worldTransform() and - QPainter::setWorldTransform() functions. You can at any time save the - QPainter's transformation matrix by calling the QPainter::save() - function which saves the matrix on an internal stack. The - QPainter::restore() function pops it back. - - One frequent need for the transformation matrix is when reusing - the same drawing code on a variety of paint devices. Without - transformations, the results are tightly bound to the resolution - of the paint device. Printers have high resolution, e.g. 600 dots - per inch, whereas screens often have between 72 and 100 dots per - inch. - - \table 100% - \header - \o {2,1} Analog Clock Example - \row - \o \inlineimage coordinatesystem-analogclock.png - \o - The Analog Clock example shows how to draw the contents of a - custom widget using QPainter's transformation matrix. - - Qt's example directory provides a complete walk-through of the - example. Here, we will only review the example's \l - {QWidget::paintEvent()}{paintEvent()} function to see how we can - use the transformation matrix (i.e. QPainter's matrix functions) - to draw the clock's face. - - We recommend compiling and running this example before you read - any further. In particular, try resizing the window to different - sizes. - - \row - \o {2,1} - - \snippet examples/widgets/analogclock/analogclock.cpp 9 - - First, we set up the painter. We translate the coordinate system - so that point (0, 0) is in the widget's center, instead of being - at the top-left corner. We also scale the system by \c side / 100, - where \c side is either the widget's width or the height, - whichever is shortest. We want the clock to be square, even if the - device isn't. - - This will give us a 200 x 200 square area, with the origin (0, 0) - in the center, that we can draw on. What we draw will show up in - the largest possible square that will fit in the widget. - - See also the \l {Window-Viewport Conversion} section. - - \snippet examples/widgets/analogclock/analogclock.cpp 18 - - We draw the clock's hour hand by rotating the coordinate system - and calling QPainter::drawConvexPolygon(). Thank's to the - rotation, it's drawn pointed in the right direction. - - The polygon is specified as an array of alternating \e x, \e y - values, stored in the \c hourHand static variable (defined at the - beginning of the function), which corresponds to the four points - (2, 0), (0, 2), (-2, 0), and (0, -25). - - The calls to QPainter::save() and QPainter::restore() surrounding - the code guarantees that the code that follows won't be disturbed - by the transformations we've used. - - \snippet examples/widgets/analogclock/analogclock.cpp 24 - - We do the same for the clock's minute hand, which is defined by - the four points (1, 0), (0, 1), (-1, 0), and (0, -40). These - coordinates specify a hand that is thinner and longer than the - minute hand. - - \snippet examples/widgets/analogclock/analogclock.cpp 27 - - Finally, we draw the clock face, which consists of twelve short - lines at 30-degree intervals. At the end of that, the painter is - rotated in a way which isn't very useful, but we're done with - painting so that doesn't matter. - \endtable - - For a demonstation of Qt's ability to perform affine - transformations on painting operations, see the \l - {painting/affine}{Affine Transformations} example which allows the user - to experiment with the transformation operations. See also the \l - {painting/transformations}{Transformations} example which shows - how transformations influence the way that QPainter renders - graphics primitives. In particular, it shows how the order of - transformations affects the result. - - For more information about the transformation matrix, see the - QTransform documentation. - - \section1 Window-Viewport Conversion - - When drawing with QPainter, we specify points using logical - coordinates which then are converted into the physical coordinates - of the paint device. - - The mapping of the logical coordinates to the physical coordinates - are handled by QPainter's world transformation \l - {QPainter::worldTransform()}{worldTransform()} (described in the \l - Transformations section), and QPainter's \l - {QPainter::viewport()}{viewport()} and \l - {QPainter::window()}{window()}. The viewport represents the - physical coordinates specifying an arbitrary rectangle. The - "window" describes the same rectangle in logical coordinates. By - default the logical and physical coordinate systems coincide, and - are equivalent to the paint device's rectangle. - - Using window-viewport conversion you can make the logical - coordinate system fit your preferences. The mechanism can also be - used to make the drawing code independent of the paint device. You - can, for example, make the logical coordinates extend from (-50, - -50) to (50, 50) with (0, 0) in the center by calling the - QPainter::setWindow() function: - - \snippet doc/src/snippets/code/doc_src_coordsys.cpp 4 - - Now, the logical coordinates (-50,-50) correspond to the paint - device's physical coordinates (0, 0). Independent of the paint - device, your painting code will always operate on the specified - logical coordinates. - - By setting the "window" or viewport rectangle, you perform a - linear transformation of the coordinates. Note that each corner of - the "window" maps to the corresponding corner of the viewport, and - vice versa. For that reason it normally is a good idea to let the - viewport and "window" maintain the same aspect ratio to prevent - deformation: - - \snippet doc/src/snippets/code/doc_src_coordsys.cpp 5 - - If we make the logical coordinate system a square, we should also - make the viewport a square using the QPainter::setViewport() - function. In the example above we make it equivalent to the - largest square that fit into the paint device's rectangle. By - taking the paint device's size into consideration when setting the - window or viewport, it is possible to keep the drawing code - independent of the paint device. - - Note that the window-viewport conversion is only a linear - transformation, i.e. it does not perform clipping. This means that - if you paint outside the currently set "window", your painting is - still transformed to the viewport using the same linear algebraic - approach. - - \image coordinatesystem-transformations.png - - The viewport, "window" and transformation matrix determine how - logical QPainter coordinates map to the paint device's physical - coordinates. By default the world transformation matrix is the - identity matrix, and the "window" and viewport settings are - equivalent to the paint device's settings, i.e. the world, - "window" and device coordinate systems are equivalent, but as we - have seen, the systems can be manipulated using transformation - operations and window-viewport conversion. The illustration above - describes the process. - - \omit - \section1 Related Classes - - Qt's paint system, Arthur, is primarily based on the QPainter, - QPaintDevice, and QPaintEngine classes: - - \table - \header \o Class \o Description - \row - \o QPainter - \o - The QPainter class performs low-level painting on widgets and - other paint devices. QPainter can operate on any object that - inherits the QPaintDevice class, using the same code. - \row - \o QPaintDevice - \o - The QPaintDevice class is the base class of objects that can be - painted. Qt provides several devices: QWidget, QImage, QPixmap, - QPrinter and QPicture, and other devices can also be defined by - subclassing QPaintDevice. - \row - \o QPaintEngine - \o - The QPaintEngine class provides an abstract definition of how - QPainter draws to a given device on a given platform. Qt 4 - provides several premade implementations of QPaintEngine for the - different painter backends we support; it provides one paint - engine for each supported window system and painting - frameworkt. You normally don't need to use this class directly. - \endtable - - The 2D transformations of the coordinate system are specified - using the QTransform class: - - \table - \header \o Class \o Description - \row - \o QTransform - \o - A 3 x 3 transformation matrix. Use QTransform to rotate, shear, - scale, or translate the coordinate system. - \endtable - - In addition Qt provides several graphics primitive classes. Some - of these classes exist in two versions: an \c{int}-based version - and a \c{qreal}-based version. For these, the \c qreal version's - name is suffixed with an \c F. - - \table - \header \o Class \o Description - \row - \o \l{QPoint}(\l{QPointF}{F}) - \o - A single 2D point in the coordinate system. Most functions in Qt - that deal with points can accept either a QPoint, a QPointF, two - \c{int}s, or two \c{qreal}s. - \row - \o \l{QSize}(\l{QSizeF}{F}) - \o - A single 2D vector. Internally, QPoint and QSize are the same, but - a point is not the same as a size, so both classes exist. Again, - most functions accept either QSizeF, a QSize, two \c{int}s, or two - \c{qreal}s. - \row - \o \l{QRect}(\l{QRectF}{F}) - \o - A 2D rectangle. Most functions accept either a QRectF, a QRect, - four \c{int}s, or four \c {qreal}s. - \row - \o \l{QLine}(\l{QLineF}{F}) - \o - A 2D finite-length line, characterized by a start point and an end - point. - \row - \o \l{QPolygon}(\l{QPolygonF}{F}) - \o - A 2D polygon. A polygon is a vector of \c{QPoint(F)}s. If the - first and last points are the same, the polygon is closed. - \row - \o QPainterPath - \o - A vectorial specification of a 2D shape. Painter paths are the - ultimate painting primitive, in the sense that any shape - (rectange, ellipse, spline) or combination of shapes can be - expressed as a path. A path specifies both an outline and an area. - \row - \o QRegion - \o - An area in a paint device, expressed as a list of - \l{QRect}s. In general, we recommend using the vectorial - QPainterPath class instead of QRegion for specifying areas, - because QPainterPath handles painter transformations much better. - \endtable - \endomit - - \sa {Analog Clock Example}, {Transformations Example} -*/ diff --git a/doc/src/painting-and-printing/paintsystem.qdoc b/doc/src/painting-and-printing/paintsystem.qdoc deleted file mode 100644 index a567509186..0000000000 --- a/doc/src/painting-and-printing/paintsystem.qdoc +++ /dev/null @@ -1,560 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group painting - \title Painting Classes - \ingroup groups - - \brief Classes that provide support for painting. - - See also this introduction to the \link coordsys.html Qt - coordinate system. \endlink -*/ - -/*! - \group painting-3D - \title Rendering in 3D - \ingroup groups - - \brief Classes that provide support for rendering in 3D. -*/ - -/*! - \page paintsystem.html - \title Paint System - \brief A system for painting on the screen or on print devices using the same API - \ingroup qt-graphics - \ingroup frameworks-technologies - \ingroup qt-basic-concepts - - - Qt's paint system enables painting on screen and print devices - using the same API, and is primarily based on the QPainter, - QPaintDevice, and QPaintEngine classes. - - QPainter is used to perform drawing operations, QPaintDevice is an - abstraction of a two-dimensional space that can be painted on - using a QPainter, and QPaintEngine provides the interface that the - painter uses to draw onto different types of devices. The - QPaintEngine class is used internally by QPainter and - QPaintDevice, and is hidden from application programmers unless - they create their own device type. - - \image paintsystem-core.png - - The main benefit of this approach is that all painting follows the - same painting pipeline making it easy to add support for new - features and providing default implementations for unsupported - ones. - - \section1 Topics - \list - \o \l{Classes for Painting} - \o \l{Paint Devices and Backends} - \o \l{Drawing and Filling} - \o \l{Coordinate System} - \o \l{Reading and Writing Image Files} - \o \l{Styling} - \o \l{Printing with Qt} - \endlist - - \section1 Classes for Painting - - These classes provide support for painting onto a paint device. - - \annotatedlist painting - - Alternatively, Qt provides the QtOpenGL module, offering classes - that makes it easy to use OpenGL in Qt applications. Among others, - the module provides an OpenGL widget class that can be used just - like any other Qt widget, except that it opens an OpenGL display - buffer where the OpenGL API can be used to render the contents. -*/ - - -/*! - \page paintsystem-devices.html - \title Paint Devices and Backends - - \contentspage The Paint System - \nextpage Drawing and Filling - - \section1 Creating a Paint Device - - The QPaintDevice class is the base class of objects that can be - painted, i.e. QPainter can draw on any QPaintDevice - subclass. QPaintDevice's drawing capabilities are currently - implemented by the QWidget, QImage, QPixmap, QGLWidget, - QGLPixelBuffer, QPicture and QPrinter subclasses. - - \image paintsystem-devices.png - - \table 100% - \row \o \bold Widget - - The QWidget class is the base class of all user interface - objects. The widget is the atom of the user interface: it receives - mouse, keyboard and other events from the window system, and - paints a representation of itself on the screen. - - \row \o \bold Image - - The QImage class provides a hardware-independent image - representation which is designed and optimized for I/O, and for - direct pixel access and manipulation. QImage supports several - image formats including monochrome, 8-bit, 32-bit and - alpha-blended images. - - One advantage of using QImage as a paint device is that it is - possible to guarantee the pixel exactness of any drawing operation - in a platform-independent way. Another benefit is that the - painting can be performed in another thread than the current GUI - thread. - - \row \o \bold Pixmap - - The QPixmap class is an off-screen image representation which is - designed and optimized for showing images on screen. Unlike - QImage, the pixel data in a pixmap is internal and is managed by - the underlying window system, i.e. pixels can only be accessed - through QPainter functions or by converting the QPixmap to a - QImage. - - To optimize drawing with QPixmap, Qt provides the QPixmapCache - class which can be used to store temporary pixmaps that are - expensive to generate without using more storage space than the - cache limit. - - Qt also provides the QBitmap convenience class, inheriting - QPixmap. QBitmap guarantees monochrome (1-bit depth) pixmaps, and - is mainly used for creating custom QCursor and QBrush objects, - constructing QRegion objects, and for setting masks for pixmaps - and widgets. - - \row \o \bold {OpenGL Widget} - - As mentioned previously, Qt provides the QtOpenGL module offering - classes that makes it easy to use OpenGL in Qt applications. For - example, the QGLWidget enables the OpenGL API for - rendering. - - But QGLWidget is also a QWidget subclass, and can be used by - QPainter as any other paint device. One huge benefit from this is - that it enables Qt to utilize the high performance of OpenGL for - most drawing operations, such as transformations and pixmap - drawing. - - \row \o \bold {Pixel Buffer} - - The QtOpenGL module also provides the QGLPixelBuffer class which - inherits QPaintDevice directly. - - QGLPixelBuffer encapsulates an OpenGL pbuffer. Rendering into a - pbuffer is normally done using full hardware acceleration which - can be significantly faster than rendering into a QPixmap. - - \row \o \bold {Framebuffer Object} - - The QtOpenGL module also provides the QGLFramebufferObject class - which inherits QPaintDevice directly. - - QGLFramebufferObject encapsulates an OpenGL framebuffer object. - Framebuffer objects can also be used for off-screen rendering, and - offer several advantages over pixel buffers for this purpose. - These are described in the QGLFramebufferObject class documentation. - - \row \o \bold {Picture} - - The QPicture class is a paint device that records and replays - QPainter commands. A picture serializes painter commands to an IO - device in a platform-independent format. QPicture is also - resolution independent, i.e. a QPicture can be displayed on - different devices (for example svg, pdf, ps, printer and screen) - looking the same. - - Qt provides the QPicture::load() and QPicture::save() functions - as well as streaming operators for loading and saving pictures. - - \row \o \bold {Printer} - - The QPrinter class is a paint device that paints on a printer. On - Windows or Mac OS X, QPrinter uses the built-in printer - drivers. On X11, QPrinter generates postscript and sends that to - lpr, lp, or another print program. QPrinter can also print to any - other QPrintEngine object. - - The QPrintEngine class defines an interface for how QPrinter - interacts with a given printing subsystem. The common case when - creating your own print engine, is to derive from both - QPaintEngine and QPrintEngine. - - The output format is by default determined by the platform the - printer is running on, but by explicitly setting the output format - to QPrinter::PdfFormat, QPrinter will generate its output as a PDF - file. - - \row \o \bold {Custom Backends} - - Support for a new backend can be implemented by deriving from the - QPaintDevice class and reimplementing the virtual - QPaintDevice::paintEngine() function to tell QPainter which paint - engine should be used to draw on this particular device. To - actually be able to draw on the device, this paint engine must be - a custom paint engine created by deriving from the QPaintEngine - class. - - \endtable - - \section1 Selecting the Painting Backend - - Since Qt 4.5, it is possible to replace the paint engines and paint - devices used for widgets, pixmaps and the offscreen double buffer. By - default the backends are: - - \table - \row - \o Windows - \o Software Rasterizer - \row - \o X11 - \o X11 - \row - \o Mac OS X - \o CoreGraphics - \row - \o Embedded - \o Software Rasterizer - \endtable - - Passing a command line parameter to the application, such as, - \c{-graphicssystem raster}, specifies that Qt should use the software - rasterizer for this application. The Software rasterizer is fully - supported on all platforms. - - \code - > analogclock -graphicssystem raster - \endcode - - There is also a \c{-graphicssystem opengl} mode that uses OpenGL for - all drawing. Currently, this engine is experimental as it does not draw - everything correctly. - - Qt also supports being configured using \c {-graphicssystem - raster|opengl} in which case all applications will use the - specified graphics system for its graphics. -*/ - -/*! - \page paintsystem-drawing.html - \title Drawing and Filling - - \previouspage Paint Devices and Backends - \contentspage The Paint System - \nextpage Coordinate System - - \section1 Drawing - - QPainter provides highly optimized functions to do most of the - drawing GUI programs require. It can draw everything from simple - graphical primitives (represented by the QPoint, QLine, QRect, - QRegion and QPolygon classes) to complex shapes like vector - paths. In Qt vector paths are represented by the QPainterPath - class. QPainterPath provides a container for painting operations, - enabling graphical shapes to be constructed and reused. - - \table 100% - \row - \o \image paintsystem-painterpath.png - \o \bold QPainterPath - - A painter path is an object composed of lines and curves. For - example, a rectangle is composed by lines and an ellipse is - composed by curves. - - The main advantage of painter paths over normal drawing operations - is that complex shapes only need to be created once; then they can - be drawn many times using only calls to the QPainter::drawPath() - function. - - A QPainterPath object can be used for filling, outlining, and - clipping. To generate fillable outlines for a given painter path, - use the QPainterPathStroker class. - - \endtable - - Lines and outlines are drawn using the QPen class. A pen is - defined by its style (i.e. its line-type), width, brush, how the - endpoints are drawn (cap-style) and how joins between two - connected lines are drawn (join-style). The pen's brush is a - QBrush object used to fill strokes generated with the pen, - i.e. the QBrush class defines the fill pattern. - - QPainter can also draw aligned text and pixmaps. - - When drawing text, the font is specified using the QFont class. Qt - will use the font with the specified attributes, or if no matching - font exists, Qt will use the closest matching installed font. The - attributes of the font that is actually used can be retrieved - using the QFontInfo class. In addition, the QFontMetrics class - provides the font measurements, and the QFontDatabase class - provides information about the fonts available in the underlying - window system. - - Normally, QPainter draws in a "natural" coordinate system, but it - is able to perform view and world transformations using the - QTransform class. For more information, see \l {Coordinate - System}, which also describes the rendering process, i.e. the - relation between the logical representation and the rendered - pixels, and the benefits of anti-aliased painting. - - \table 100% - \row \o - \bold {Anti-Aliased Painting} - - When drawing, the pixel rendering is controlled by the - QPainter::Antialiasing render hint. The QPainter::RenderHint enum - is used to specify flags to QPainter that may or may not be - respected by any given engine. - - The QPainter::Antialiasing value indicates that the engine should - antialias edges of primitives if possible, i.e. smoothing the - edges by using different color intensities. - - \o \image paintsystem-antialiasing.png - - \endtable - - \section1 Filling - - Shapes are filled using the QBrush class. A brush is defined - by its color and its style (i.e. its fill pattern). - - Any color in Qt is represented by the QColor class which supports - the RGB, HSV and CMYK color models. QColor also support - alpha-blended outlining and filling (specifying the transparency - effect), and the class is platform and device independent (the - colors are mapped to hardware using the QColormap class). For more - information, see the QColor class documentation. - - When creating a new widget, it is recommend to use the colors in - the widget's palette rather than hard-coding specific colors. All - widgets in Qt contain a palette and use their palette to draw - themselves. A widget's palette is represented by the QPalette - class which contains color groups for each widget state. - - The available fill patterns are described by the Qt::BrushStyle - enum. These include basic patterns spanning from uniform color to - very sparse pattern, various line combinations, gradient fills and - textures. Qt provides the QGradient class to define custom - gradient fills, while texture patterns are specified using the - QPixmap class. - - \table 100% - \row - \o \image paintsystem-fancygradient.png - \o \bold QGradient - - The QGradient class is used in combination with QBrush to specify - gradient fills. - - \image paintsystem-gradients.png - - Qt currently supports three types of gradient fills: Linear - gradients interpolate colors between start and end points, radial - gradients interpolate colors between a focal point and end points - on a circle surrounding it, and conical gradients interpolate - colors around a center point. - - \endtable -*/ - -/*! - \page paintsystem-images.html - \title Reading and Writing Image Files - - \previouspage Coordinate System - \contentspage The Paint System - \nextpage Styling - - The most common way to read images is through QImage and QPixmap's - constructors, or by calling the QImage::load() and QPixmap::load() - functions. In addition, Qt provides the QImageReader class which - gives more control over the process. Depending on the underlying - support in the image format, the functions provided by the class - can save memory and speed up loading of images. - - Likewise, Qt provides the QImageWriter class which supports - setting format specific options, such as the gamma level, - compression level and quality, prior to storing the image. If you - do not need such options, you can use QImage::save() or - QPixmap::save() instead. - - \table 100% - \row - \o \bold QMovie - - QMovie is a convenience class for displaying animations, using the - QImageReader class internally. Once created, the QMovie class - provides various functions for both running and controlling the - given animation. - - \o \image paintsystem-movie.png - \endtable - - The QImageReader and QImageWriter classes rely on the - QImageIOHandler class which is the common image I/O interface for - all image formats in Qt. QImageIOHandler objects are used - internally by QImageReader and QImageWriter to add support for - different image formats to Qt. - - A list of the supported file formats are available through the - QImageReader::supportedImageFormats() and - QImageWriter::supportedImageFormats() functions. Qt supports - several file formats by default, and in addition new formats can - be added as plugins. The currently supported formats are listed in - the QImageReader and QImageWriter class documentation. - - Qt's plugin mechanism can also be used to write a custom image - format handler. This is done by deriving from the QImageIOHandler - class, and creating a QImageIOPlugin object which is a factory for - creating QImageIOHandler objects. When the plugin is installed, - QImageReader and QImageWriter will automatically load the plugin - and start using it. - - \section1 Rendering SVG files - - \table 100% - \row - \o \image paintsystem-svg.png - \o \bold {SVG Rendering} - - Scalable Vector Graphics (SVG) is a language for describing two-dimensional - graphics and graphical applications in XML. SVG 1.1 is a W3C Recommendation - and forms the core of the current SVG developments in Qt. SVG 1.2 is the - specification currently being developed by the \l{SVG Working Group}, and it - is \l{http://www.w3.org/TR/SVG12/}{available in draft form}. - The \l{Mobile SVG Profiles} (SVG Basic and SVG Tiny) are aimed at - resource-limited devices and are part of the 3GPP platform for third generation - mobile phones. You can read more about SVG at \l{About SVG}. - - Qt supports the \l{SVG 1.2 Tiny Static Features}{static features} of - \l{SVG 1.2 Tiny}. ECMA scripts and DOM manipulation are currently not - supported. - - SVG drawings can be rendered onto any QPaintDevice subclass. This - approach gives developers the flexibility to experiment, in order - to find the best solution for each application. - - The easiest way to render SVG files is to construct a QSvgWidget and - load an SVG file using one of the QSvgWidget::load() functions. - - QSvgRenderer is the class responsible for rendering SVG files for - QSvgWidget, and it can be used directly to provide SVG support for - custom widgets. - To load an SVG file, construct a QSvgRenderer with a file name or the - contents of a file, or call QSvgRenderer::load() on an existing - renderer. If the SVG file has been loaded successfully the - QSvgRenderer::isValid() will return true. - - Once you have loaded the SVG file successfully, you can render it - with the QSvgRenderer::render() function. Note that this scheme allows - you to render SVG files on all paint devices supported by Qt, including - QWidget, QGLWidget, and QImage. See the \l{SVG Viewer Example}{SVG Viewer} - example for more details. - - \endtable -*/ - -/*! - \page paintsystem-styling.html - \title Styling - - \previouspage Reading and Writing Image Files - \contentspage The Paint System - \nextpage Printing with Qt - - Qt's built-in widgets use the QStyle class to perform nearly all - of their drawing. QStyle is an abstract base class that - encapsulates the look and feel of a GUI, and can be used to make - the widgets look exactly like the equivalent native widgets or to - give the widgets a custom look. - - Qt provides a set of QStyle subclasses that emulate the native - look of the different platforms supported by Qt (QWindowsStyle, - QMacStyle, QMotifStyle, etc.). These styles are built into the - QtGui library, other styles can be made available using Qt's - plugin mechansim. - - Most functions for drawing style elements take four arguments: - - \list - \o an enum value specifying which graphical element to draw - \o a QStyleOption object specifying how and where to render that element - \o a QPainter object that should be used to draw the element - \o a QWidget object on which the drawing is performed (optional) - \endlist - - The style gets all the information it needs to render the - graphical element from the QStyleOption class. The widget is - passed as the last argument in case the style needs it to perform - special effects (such as animated default buttons on Mac OS X), - but it isn't mandatory. In fact, QStyle can be used to draw on any - paint device (not just widgets), in which case the widget argument - is a zero pointer. - - \image paintsystem-stylepainter.png - - The paint system also provides the QStylePainter class inheriting - from QPainter. QStylePainter is a convenience class for drawing - QStyle elements inside a widget, and extends QPainter with a set - of high-level drawing functions implemented on top of QStyle's - API. The advantage of using QStylePainter is that the parameter - lists get considerably shorter. - - \table 100% - \row - \o \inlineimage paintsystem-icon.png - \o \bold QIcon - - The QIcon class provides scalable icons in different modes and states. - - QIcon can generate pixmaps reflecting an icon's state, mode and - size. These pixmaps are generated from the set of pixmaps - made available to the icon, and are used by Qt widgets to show an - icon representing a particular action. - - The rendering of a QIcon object is handled by the QIconEngine - class. Each icon has a corresponding icon engine that is - responsible for drawing the icon with a requested size, mode and - state. - - \endtable - - For more information about widget styling and appearance, see the - \l{Styles and Style Aware Widgets}. -*/ diff --git a/doc/src/painting-and-printing/printing.qdoc b/doc/src/painting-and-printing/printing.qdoc deleted file mode 100644 index c8d6efbc39..0000000000 --- a/doc/src/painting-and-printing/printing.qdoc +++ /dev/null @@ -1,189 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group printing - \title Printer and Printing APIs - \brief Classes for producing printed output - \ingroup groups -*/ - -/*! - \page printing.html - \title Printing with Qt - \ingroup qt-graphics - - \previouspage Styling - \contentspage The Paint System - - \brief A guide to producing printed output with Qt's paint system and widgets. - - Qt provides extensive cross-platform support for printing. Using the printing - systems on each platform, Qt applications can print to attached printers and - across networks to remote printers. Qt's printing system also enables PostScript - and PDF files to be generated, providing the foundation for basic report - generation facilities. - - \tableofcontents - - \section1 Classes Supporting Printing - - The following classes support the selecting and setting up of printers and - printing output. - - \annotatedlist printing - - \section1 Paint Devices and Printing - - In Qt, printers are represented by QPrinter, a paint device that provides - functionality specific to printing, such as support for multiple pages and - double-sided output. As a result, printing involves using a QPainter to paint - onto a series of pages in the same way that you would paint onto a custom - widget or image. - - \section2 Creating a QPrinter - - Although QPrinter objects can be constructed and set up without requiring user - input, printing is often performed as a result of a request by the user; - for example, when the user selects the \gui{File|Print...} menu item in a GUI - application. In such cases, a newly-constructed QPrinter object is supplied to - a QPrintDialog, allowing the user to specify the printer to use, paper size, and - other printing properties. - - \snippet examples/richtext/orderform/mainwindow.cpp 18 - - It is also possible to set certain default properties by modifying the QPrinter - before it is supplied to the print dialog. For example, applications that - generate batches of reports for printing may set up the QPrinter to - \l{QPrinter::setOutputFileName()}{write to a local file} by default rather than - to a printer. - - \section2 Painting onto a Page - - Once a QPrinter object has been constructed and set up, a QPainter can be used - to perform painting operations on it. We can construct and set up a painter in - the following way: - - \snippet doc/src/snippets/printing-qprinter/object.cpp 0 - - Since the QPrinter starts with a blank page, we only need to call the - \l{QPrinter::}{newPage()} function after drawing each page, except for the - last page. - - The document is sent to the printer, or written to a local file, when we call - \l{QPainter::}{end()}. - - \section2 Coordinate Systems - - QPrinter provides functions that can be used to obtain information about the - dimensions of the paper (the paper rectangle) and the dimensions of the - printable area (the page rectangle). These are given in logical device - coordinates that may differ from the physical coordinates used by the device - itself, indicating that the printer is able to render text and graphics at a - (typically higher) resolution than the user's display. - - Although we do not need to handle the conversion between logical and physical - coordinates ourselves, we still need to apply transformations to painting - operations because the pixel measurements used to draw on screen are often - too small for the higher resolutions of typical printers. - - \table - \row \o \bold{Printer and Painter Coordinate Systems} - - The \l{QPrinter::}{paperRect()} and \l{QPrinter::}{pageRect()} functions - provide information about the size of the paper used for printing and the - area on it that can be painted on. - - The rectangle returned by \l{QPrinter::}{pageRect()} usually lies inside - the rectangle returned by \l{QPrinter::}{paperRect()}. You do not need to - take the positions and sizes of these area into account when using a QPainter - with a QPrinter as the underlying paint device; the origin of the painter's - coordinate system will coincide with the top-left corner of the page - rectangle, and painting operations will be clipped to the bounds of the - drawable part of the page. - - \o \inlineimage printer-rects.png - \endtable - - The paint system automatically uses the correct device metrics when painting - text but, if you need to position text using information obtained from - font metrics, you need to ensure that the print device is specified when - you construct QFontMetrics and QFontMetricsF objects, or ensure that each QFont - used is constructed using the form of the constructor that accepts a - QPaintDevice argument. - - \section1 Printing Widgets - - To print a widget, you can use the QWidget::render() function. As mentioned, - the printer's resolution is usually higher than the screen resolution, so you - will have to scale the painter. You may also want to position the widget on the - page. The following code sample shows how this may look. - - \snippet doc/src/snippets/widgetprinting.cpp 0 - - This will center the widget on the page and scale it so that it fits the page. - - \section1 Printing from Complex Widgets - - Certain widgets, such as QTextEdit and QGraphicsView, display rich content - that is typically managed by instances of other classes, such as QTextDocument - and QGraphicsScene. As a result, it is these content handling classes that - usually provide printing functionality, either via a function that can be used - to perform the complete task, or via a function that accepts an existing - QPainter object. Some widgets provide convenience functions to expose underlying - printing features, avoiding the need to obtain the content handler just to call - a single function. - - The following table shows which class and function are responsible for - printing from a selection of different widgets. For widgets that do not expose - printing functionality directly, the content handling classes containing this - functionality can be obtained via a function in the corresponding widget's API. - - \table - \header \o Widget \o Printing function \o Accepts - \row \o QGraphicsView \o QGraphicsView::render() \o QPainter - \row \o QSvgWidget \o QSvgRenderer::render() \o QPainter - \row \o QTextEdit \o QTextDocument::print() \o QPrinter - \row \o QTextLayout \o QTextLayout::draw() \o QPainter - \row \o QTextLine \o QTextLine::draw() \o QPainter - \endtable - - QTextEdit requires a QPrinter rather than a QPainter because it uses information - about the configured page dimensions in order to insert page breaks at the most - appropriate places in printed documents. -*/ - -/*! - \page pdf-licensing.html - \title Notes about PDF Licensing - \ingroup licensing - \brief Details of restrictions on the use of PDF-related trademarks. - - Please note that Adobe\reg places restrictions on the use of its trademarks - (including logos) in conjunction with PDF; e.g. "Adobe PDF". Please refer - to \l{http://www.adobe.com}{www.adobe.com} for guidelines. -*/ diff --git a/doc/src/printsupport/printing.qdoc b/doc/src/printsupport/printing.qdoc new file mode 100644 index 0000000000..c8d6efbc39 --- /dev/null +++ b/doc/src/printsupport/printing.qdoc @@ -0,0 +1,189 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group printing + \title Printer and Printing APIs + \brief Classes for producing printed output + \ingroup groups +*/ + +/*! + \page printing.html + \title Printing with Qt + \ingroup qt-graphics + + \previouspage Styling + \contentspage The Paint System + + \brief A guide to producing printed output with Qt's paint system and widgets. + + Qt provides extensive cross-platform support for printing. Using the printing + systems on each platform, Qt applications can print to attached printers and + across networks to remote printers. Qt's printing system also enables PostScript + and PDF files to be generated, providing the foundation for basic report + generation facilities. + + \tableofcontents + + \section1 Classes Supporting Printing + + The following classes support the selecting and setting up of printers and + printing output. + + \annotatedlist printing + + \section1 Paint Devices and Printing + + In Qt, printers are represented by QPrinter, a paint device that provides + functionality specific to printing, such as support for multiple pages and + double-sided output. As a result, printing involves using a QPainter to paint + onto a series of pages in the same way that you would paint onto a custom + widget or image. + + \section2 Creating a QPrinter + + Although QPrinter objects can be constructed and set up without requiring user + input, printing is often performed as a result of a request by the user; + for example, when the user selects the \gui{File|Print...} menu item in a GUI + application. In such cases, a newly-constructed QPrinter object is supplied to + a QPrintDialog, allowing the user to specify the printer to use, paper size, and + other printing properties. + + \snippet examples/richtext/orderform/mainwindow.cpp 18 + + It is also possible to set certain default properties by modifying the QPrinter + before it is supplied to the print dialog. For example, applications that + generate batches of reports for printing may set up the QPrinter to + \l{QPrinter::setOutputFileName()}{write to a local file} by default rather than + to a printer. + + \section2 Painting onto a Page + + Once a QPrinter object has been constructed and set up, a QPainter can be used + to perform painting operations on it. We can construct and set up a painter in + the following way: + + \snippet doc/src/snippets/printing-qprinter/object.cpp 0 + + Since the QPrinter starts with a blank page, we only need to call the + \l{QPrinter::}{newPage()} function after drawing each page, except for the + last page. + + The document is sent to the printer, or written to a local file, when we call + \l{QPainter::}{end()}. + + \section2 Coordinate Systems + + QPrinter provides functions that can be used to obtain information about the + dimensions of the paper (the paper rectangle) and the dimensions of the + printable area (the page rectangle). These are given in logical device + coordinates that may differ from the physical coordinates used by the device + itself, indicating that the printer is able to render text and graphics at a + (typically higher) resolution than the user's display. + + Although we do not need to handle the conversion between logical and physical + coordinates ourselves, we still need to apply transformations to painting + operations because the pixel measurements used to draw on screen are often + too small for the higher resolutions of typical printers. + + \table + \row \o \bold{Printer and Painter Coordinate Systems} + + The \l{QPrinter::}{paperRect()} and \l{QPrinter::}{pageRect()} functions + provide information about the size of the paper used for printing and the + area on it that can be painted on. + + The rectangle returned by \l{QPrinter::}{pageRect()} usually lies inside + the rectangle returned by \l{QPrinter::}{paperRect()}. You do not need to + take the positions and sizes of these area into account when using a QPainter + with a QPrinter as the underlying paint device; the origin of the painter's + coordinate system will coincide with the top-left corner of the page + rectangle, and painting operations will be clipped to the bounds of the + drawable part of the page. + + \o \inlineimage printer-rects.png + \endtable + + The paint system automatically uses the correct device metrics when painting + text but, if you need to position text using information obtained from + font metrics, you need to ensure that the print device is specified when + you construct QFontMetrics and QFontMetricsF objects, or ensure that each QFont + used is constructed using the form of the constructor that accepts a + QPaintDevice argument. + + \section1 Printing Widgets + + To print a widget, you can use the QWidget::render() function. As mentioned, + the printer's resolution is usually higher than the screen resolution, so you + will have to scale the painter. You may also want to position the widget on the + page. The following code sample shows how this may look. + + \snippet doc/src/snippets/widgetprinting.cpp 0 + + This will center the widget on the page and scale it so that it fits the page. + + \section1 Printing from Complex Widgets + + Certain widgets, such as QTextEdit and QGraphicsView, display rich content + that is typically managed by instances of other classes, such as QTextDocument + and QGraphicsScene. As a result, it is these content handling classes that + usually provide printing functionality, either via a function that can be used + to perform the complete task, or via a function that accepts an existing + QPainter object. Some widgets provide convenience functions to expose underlying + printing features, avoiding the need to obtain the content handler just to call + a single function. + + The following table shows which class and function are responsible for + printing from a selection of different widgets. For widgets that do not expose + printing functionality directly, the content handling classes containing this + functionality can be obtained via a function in the corresponding widget's API. + + \table + \header \o Widget \o Printing function \o Accepts + \row \o QGraphicsView \o QGraphicsView::render() \o QPainter + \row \o QSvgWidget \o QSvgRenderer::render() \o QPainter + \row \o QTextEdit \o QTextDocument::print() \o QPrinter + \row \o QTextLayout \o QTextLayout::draw() \o QPainter + \row \o QTextLine \o QTextLine::draw() \o QPainter + \endtable + + QTextEdit requires a QPrinter rather than a QPainter because it uses information + about the configured page dimensions in order to insert page breaks at the most + appropriate places in printed documents. +*/ + +/*! + \page pdf-licensing.html + \title Notes about PDF Licensing + \ingroup licensing + \brief Details of restrictions on the use of PDF-related trademarks. + + Please note that Adobe\reg places restrictions on the use of its trademarks + (including logos) in conjunction with PDF; e.g. "Adobe PDF". Please refer + to \l{http://www.adobe.com}{www.adobe.com} for guidelines. +*/ diff --git a/doc/src/printsupport/qtprintsupport.qdoc b/doc/src/printsupport/qtprintsupport.qdoc new file mode 100644 index 0000000000..d143d66ad2 --- /dev/null +++ b/doc/src/printsupport/qtprintsupport.qdoc @@ -0,0 +1,19 @@ +/*! + \module QtPrintSupport + \title QtPrintSupport Module + \ingroup modules + + \brief The QtPrintSupport module provides classes to make printing + easier and portable. + + To include the definitions of the module's classes, use the + following directive: + + \snippet doc/src/snippets/code/doc_src_qtprintsupport.cpp 1 + + To link against the module, add this line to your \l qmake \c + .pro file: + + \snippet doc/src/snippets/code/doc_src_qtprintsupport.pro 0 +*/ + diff --git a/doc/src/sql-programming/qsqldatatype-table.qdoc b/doc/src/sql-programming/qsqldatatype-table.qdoc deleted file mode 100644 index e5a9bf5c5a..0000000000 --- a/doc/src/sql-programming/qsqldatatype-table.qdoc +++ /dev/null @@ -1,570 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page sql-types.html - \title Data Types for Qt-supported Database Systems - \brief Recommended data types for database systems - - \ingroup qt-sql - - \section1 Recommended Data Types for Qt-Supported Database Systems - - This table shows the recommended data types for extracting data from - the databases supported in Qt. Note that types used in Qt are not - necessarily valid as input types to a specific database - system. e.g., A double might work perfectly as input for floating - point records in a particular database, but not necessarily as a - storage format for output from that database, because it would be - stored with 64-bit precision in C++. - - \tableofcontents - - \section2 IBM DB2 Data Types - - \table 90% - \header - \o IBM DB2 data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o SMALLINT - \o 16-bit signed integer - \o typedef qint16 - \row - \o INTEGER - \o 32-bit signed integer - \o typedef qint32 - \row - \o BIGINT - \o 64-bit signed integer - \o typedef qint64 - \row - \o REAL - \o 32-bit Single-precision floating point - \o By default mapping to QString - \row - \o DOUBLE PRECISION - \o 64-bit Double-precision floating point - \o By default mapping to QString - \row - \o FLOAT - \o 64-bit Double-precision floating point - \o By default mapping to QString - \row - \o CHAR - \o Fixed-length, null-terminated character string - \o Mapped to QString - \row - \o VARCHAR - \o Null-terminated varying length string - \o Mapped to QString - \row - \o LONG VARCHAR - \o Not null-terminated varying length character string - \o Mapped to QString - \row - \o BLOB - \o Not null-terminated varying binary string with 4-byte string - length indicator - \o Mapped to QByteArray - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o DATE - \o Null-terminated character string of the following format: - yyyy-mm-dd - \o Mapped to QDate - \row - \o TIME - \o Null-terminated character string of the following format: hh.mm.ss - \o Mapped to QTime - \row - \o TIMESTAMP - \o Null-terminated character string of the following format: yyyy-mm-dd-hh.mm.ss.nnnnnn - \o Mapped to QDateTime - \endtable - - \section2 Borland InterBase Data Types - - \table 90% - \header - \o Borland InterBase data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o BOOLEAN - \o Boolean - \o bool - \row - \o TINYINT - \o 8 bit signed integer - \o typedef qint8 - \row - \o SMALLINT - \o 16-bit signed integer - \o typedef qint16 - \row - \o INTEGER - \o 32-bit signed integer - \o typedef qint32 - \row - \o BIGINT LONG - \o 64-bit signed integer - \o typedef qint64 - \row - \o REAL FLOAT - \o 32-bit floating point - \o By default mapping to QString - \row - \o FLOAT - \o 64-bit floating point - \o By default mapping to QString - \row - \o DOUBLE - \o 64-bit floating point - \o By default mapping to QString - \row - \o DOUBLE PRECISION - \o 64-bit Double-precision floating point - \o By default mapping to QString - \row - \o VARCHAR STRING - \o Character string, Unicode - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o DATE - \o Displays date. Format: 'yyyy-mm-dd' - \o Mapped to QDate - \row - \o TIME - \o Displays time. Format is 'hh:mm:ss' in 24-hour format - \o Mapped to QTime - \row - \o TIMESTAMP - \o Displays a timestamp. Format is 'yyyy-mm-dd hh:mm:ss' - \o Mapped to QDateTime - \endtable - - \section2 MySQL Data Types - - \table 90% - \header - \o MySQL data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o TINYINT - \o 8 bit signed integer - \o typedef qint8 - \row - \o TINYINT UNSIGNED - \o 8 bit unsigned integer - \o typedef quint8 - \row - \o SMALLINT - \o 16-bit signed integer - \o typedef qint16 - \row - \o SMALLINT UNSIGNED - \o 16-bit unsigned integer - \o typedef quint16 - \row - \o INT - \o 32-bit signed integer - \o typedef qint32 - \row - \o INT UNSIGNED - \o 32-bit unsigned integer - \o typedef quint32 - \row - \o BIGINT - \o 64-bit signed integer - \o typedef qint64 - \row - \o FLOAT - \o 32-bit Floating Point - \o By default mapping to QString - \row - \o DOUBLE - \o 64-bit Floating Point - \o By default mapping to QString - \row - \o CHAR - \o Character string - \o Mapped to QString - \row - \o VARCHAR - \o Character string - \o Mapped to QString - \row - \o TINYTEXT - \o Character string - \o Mapped to QString - \row - \o TEXT - \o Character string - \o Mapped to QString - \row - \o MEDIUMTEXT - \o Character string - \o Mapped to QString - \row - \o LONGTEXT - \o Character string - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o all BLOB types - \o BLOB - \o Mapped to QByteArray - \row - \o DATE - \o Date without Time - \o Mapped to QDate - \row - \o DATETIME - \o Date and Time - \o Mapped to QDateTime - \row - \o TIMESTAMP - \o Date and Time - \o Mapped to QDateTime - \row - \o TIME - \o Time - \o Mapped to QTime - \row - \o YEAR - \o Year (int) - \o Mapped to QDateTime - \row - \o ENUM - \o Enumeration of Value Set - \o Mapped to QString - \endtable - - \section2 Oracle Call Interface Data Types - - \table 90% - \header - \o Oracle Call Interface data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o NUMBER - \o FLOAT, DOUBLE, PRECISIONc REAL - \o By default mapping to QString - \row - \o NUMBER(38) - \o INTEGER INT SMALLINT - \o typedef qint8/16/32/64 - \row - \o NUMBER(p,s) - \o NUMERIC(p,s) DECIMAL(p,s)a - \o By default mapping to QString - \row - \o NVARCHAR2(n) - \o Character string (NATIONAL CHARACTER VARYING(n) NATIONAL - CHAR VARYING(n) NCHAR VARYING(n)) - \o Mapped to QString - \row - \o NCHAR(n) - \o Character string (NATIONAL CHARACTER(n) NATIONAL CHAR(n) - NCHAR(n)) - \o Mapped to QString - \row - \o CHAR(n) - \o Character string (CHARACTER(n) CHAR(n)) - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o BLOB - \o A binary large object - \o Mapped to QByteArray - \row - \o TIMESTAMP - \o Year, month, and day values of date, as well as hour, minute, - and second values of time - \o Mapped to QDateTime - \endtable - - \section2 ODBC Data Types - - \table 90% - \header - \o ODBC data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o BIT - \o Boolean - \o BOOL - \row - \o TINYINT - \o 8 bit integer - \o typedef qint8 - \row - \o SMALLINT - \o 16-bit signed integer - \o typedef qint16 - \row - \o INTEGER - \o 32-bit signed integer - \o typedef qint32 - \row - \o BIGINT - \o 64-bit signed integer - \o typedef qint64 - \row - \o REAL - \o 32-bit Single-precision floating point - \o By default mapping to QString - \row - \o FLOAT - \o 64-bit Double floating point - \o By default mapping to QString - \row - \o DOUBLE - \o 64-bit Double floating point - \o By default mapping to QString - \row - \o CHAR - \o Character string - \o Mapped to QString - \row - \o VARCHAR - \o Character string - \o Mapped to QString - \row - \o LONGVARCHAR - \o Character string - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o DATE - \o Character string - \o Mapped to QDate - \row - \o TIME - \o Character Time, Character string - \o Mapped to QTime - \row - \o TIMESTAMP - \o Character Time, Character string - \o Mapped to QDateTime - \endtable - - \section2 PostgreSQL Data Types - - \table 90% - \header - \o PostgreSQL data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o BOOLEAN - \o Boolean - \o bool - \row - \o SMALLINT - \o 16-bit signed integer - \o typedef qint16 - \row - \o INTEGER - \o 32-bit signed integer - \o typedef qint32 - \row - \o BIGINT - \o 64-bit signed integer - \o typedef qint64 - \row - \o REAL - \o 32-bit variable-precision floating point - \o By default mapping to QString - \row - \o DOUBLE PRECISION - \o 64-bit variable-precision floating point - \o By default mapping to QString - \row - \o DECIMAL VARIABLE - \o user-specified precision, exact - \o Mapped to QString - \row - \o NUMERIC VARIABLE - \o user-specified precision, exact - \o Mapped to QString - \row - \o VARCHAR - \o variable-length character string - \o Mapped to QString - \row - \o CHARACTER - \o Character string of fixed-length - \o Mapped to QString - \row - \o TEXT - \o Character string of variable-length - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o TIMESTAMP - \o 8 bytes, both date and time - \o Mapped to QDateTime - \row - \o TIMESTAMP - \o 8 bytes, both date and time, with time zone - \o Mapped to QDateTime - \row - \o DATE - \o 4 bytes, dates only - \o Mapped to QDate - \row - \o TIME - \o 8 bytes, times of day only 00:00:00.00 - 23:59:59.99 - \o Mapped to QTime - \row - \o TIME - \o 12 bytes times of day only, with time zone 00:00:00.00+12 - \o Mapped to QDateTime - \endtable - - \section2 QSQLITE SQLite version 3 Data Types - - \table 90% - \header - \o QSQLITE SQLite version 3 data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o NULL - \o NULL value. - \o NULL - \row - \o INTEGER - \o Signed integer, stored in 8, 16, 24, 32, 48, or 64-bits - depending on the magnitude of the value. - \o typedef qint8/16/32/64 - \row - \o REAL - \o 64-bit floating point value. - \o By default mapping to QString - \row - \o TEXT - \o Character string (UTF-8, UTF-16BE or UTF-16-LE). - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o BLOB - \o The value is a BLOB of data, stored exactly as it was input. - \o Mapped to QByteArray - \endtable - - \section2 Sybase Adaptive Server Data Types - - \table 90% - \header - \o Sybase Adaptive Server data type - \o SQL type description - \o Recommended input (C++ or Qt data type) - \row - \o BINARY - \o Describes a fixed-length binary value up to 255 bytes in size. - \o Mapped to QByteArray - \row - \o CHAR - \o Character String - \o Mapped to QString - \row - \o DATETIME - \o Date and time. Range: 1753-01-01 00:00:00 through 9999-12-31 23:59:59. - \o Mapped to QDateTime - \row - \o NCHAR - \o Character String of fixed length - \o Mapped to QString - \row - \o NVARACHAR - \o Character String of variable length - \o Mapped to QString - \row - \o VARCHAR - \o Character String of fixed length - \o Mapped to QString - \row - \o CLOB - \o Character large string object - \o Mapped to QString - \row - \o TIMESTAMP - \o A unique number within a database - \o Mapped to QString - \row - \o SMALLDATETIME - \o Date and time. Range: 1900-01-01 00:00 through 2079-12-31 23:59 - \o Mapped to QDateTime - \row - \o UNICHAR - \o Character String of fixed length.(Unicode) - \o Mapped to QString - \row - \o UNIVARCHAR - \o Character String of variable length.(Unicode) - \o Mapped to QString - \row - \o VARBINARY - \o Describes a variable-length binary value up to 255 bytes in size - \o Mapped to QByteArray - \endtable - - \section2 SQLite Version 2 - - SQLite version 2 is "typeless". This means that you can store any kind of - data you want in any column of any table, regardless of the declared - data type of that column. We recommend that you map the data to QString. -*/ diff --git a/doc/src/sql-programming/sql-driver.qdoc b/doc/src/sql-programming/sql-driver.qdoc deleted file mode 100644 index 40c7c6a23c..0000000000 --- a/doc/src/sql-programming/sql-driver.qdoc +++ /dev/null @@ -1,828 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page sql-driver.html - \title SQL Database Drivers - \brief How to configure and install QtSql drivers for supported databases. - - \ingroup qt-sql - - The QtSql module uses driver \l{How to Create Qt - Plugins}{plugins} to communicate with the different database - APIs. Since Qt's SQL Module API is database-independent, all - database-specific code is contained within these drivers. Several - drivers are supplied with Qt and other drivers can be added. The - driver source code is supplied and can be used as a model for - \l{#development}{writing your own drivers}. - - \tableofcontents - - \section1 Supported Databases - - The table below lists the drivers included with Qt. Due to - license incompatibilities with the GPL, not all of the plugins - are provided with Open Source Versions of Qt. - - \table - \header \o Driver name \o DBMS - \row \o \link #QDB2 QDB2\endlink \o IBM DB2 (version 7.1 and above) - \row \o \link #QIBASE QIBASE\endlink \o Borland InterBase - \row \o \link #QMYSQL QMYSQL\endlink \o MySQL - \row \o \link #QOCI QOCI\endlink \o Oracle Call Interface Driver - \row \o \link #QODBC QODBC\endlink - \o Open Database Connectivity (ODBC) - Microsoft SQL Server and other - ODBC-compliant databases - \row \o \link #QPSQL QPSQL\endlink \o PostgreSQL (versions 7.3 and above) - \row \o \link #QSQLITE2 QSQLITE2\endlink \o SQLite version 2 - \row \o \link #QSQLITE QSQLITE\endlink \o SQLite version 3 - \row \o \link #QTDS QTDS\endlink \o Sybase Adaptive Server \note obsolete from Qt 4.7 - \endtable - - SQLite is the in-process database system with the best test coverage - and support on all platforms. Oracle via OCI, and PostreSQL and MySQL - through either ODBC or a native driver are well-tested on Windows and - Linux. The completeness of the support for other systems depends on the - availability and quality of client libraries. - - \bold{Note:} To build a driver plugin you need to have the appropriate - client library for your Database Management System (DBMS). This provides - access to the API exposed by the DBMS, and is typically shipped with it. - Most installation programs also allow you to install "development - libraries", and these are what you need. These libraries are responsible - for the low-level communication with the DBMS. - - \target building - \section1 Building the Drivers Using Configure - - On Unix and Mac OS X, the Qt \c configure script tries to - automatically detect the available client libraries on your - machine. Run \c{configure -help} to see what drivers can be - built. You should get an output similar to this: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 0 - - The \c configure script cannot detect the neccessary libraries - and include files if they are not in the standard paths, so it - may be necessary to specify these paths using the \c -I and \c -L - command-line options. For example, if your MySQL include files - are installed in \c /usr/local/mysql (or in \c{C:\mysql\include} - on Windows), then pass the following parameter to configure: \c - -I/usr/local/mysql (or \c{-I C:\mysql\include} for Windows). - - On Windows the \c -I parameter doesn't accept spaces in - filenames, so use the 8.3 name instead; for example, use - \c{C:\progra~1\mysql} instead of \c{C:\Program Files\mysql}. - - Use the \c{-qt-sql-} parameter to build the database driver - statically into your Qt library or \c{-plugin-sql-} to build - the driver as a plugin. Look at the sections that follow for - additional information about required libraries. - - \target buildingmanually - \section1 Building the Plugins Manually - - \target QMYSQL - \section2 QMYSQL for MySQL 4 and higher - - \section3 QMYSQL Stored Procedure Support - - MySQL 5 introduces stored procedure support at the SQL level, but no - API to control IN, OUT and INOUT parameters. Therefore, parameters - have to be set and read using SQL commands instead of QSqlQuery::bindValue(). - - Example stored procedure: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 1 - - Source code to access the OUT values: - - \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 2 - - \bold{Note:} \c{@outval1} and \c{@outval2} are variables local to the current - connection and will not be affected by queries sent from another host - or connection. - - \section3 Embedded MySQL Server - - The MySQL embedded server is a drop-in replacement for the normal - client library. With the embedded MySQL server, a MySQL server is - not required to use MySQL functionality. - - To use the embedded MySQL server, simply link the Qt plugin to \c - libmysqld instead of libmysqlclient. This can be done by replacing - \c -lmysqlclient_r by \c -lmysqld in the \c qmake command in the - section below. - - Please refer to the MySQL documentation, chapter "libmysqld, the Embedded - MySQL Server Library" for more information about the MySQL embedded server. - - \section3 How to Build the QMYSQL Plugin on Unix and Mac OS X - - You need the MySQL header files and as well as the shared library - \c{libmysqlclient.so}. Depending on your Linux distribution you may - need to install a package which is usually called "mysql-devel". - - Tell \l qmake where to find the MySQL header files and shared - libraries (here it is assumed that MySQL is installed in - \c{/usr/local}) and run \c{make}: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 3 - - After installing Qt, as described in the \l{Installing Qt for X11 - Platforms} document, you also need to install the plugin in the - standard location: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 4 - - \section3 How to Build the QMYSQL Plugin on Windows - - You need to get the MySQL installation files. Run \c SETUP.EXE and - choose "Custom Install". Install the "Libs & Include Files" Module. - Build the plugin as follows (here it is assumed that MySQL is - installed in \c{C:\MySQL}): - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 5 - - If you are not using a Microsoft compiler, replace \c nmake with \c - make in the line above. - - \note This database plugin is not supported for Windows CE. - - \note Including \c{"-o Makefile"} as an argument to \l qmake to - tell it where to build the makefile can cause the plugin to be - built in release mode only. If you are expecting a debug version - to be built as well, don't use the \c{"-o Makefile"} option. - - \section3 How to build the MySQL driver for MinGW users - - The following steps have been used successfully for WinXP SP3. In - this example, Qt 4.6.2 is shown. - - \list - - \o Download the following components: - \list - \o \c{MinGW-5.1.6.exe} - \o \c{mingw-utils-0.3.tar.gz} - \o Qt sources, e.g. \c{qt-everywhere-opensource-src-4.6.2.zip} - \o \c{mysql-5.1.35-win32.msi} - \endlist - - \o Install \c{MinGW-5.1.6.exe} in, e.g. \c{C:\MinGW}. - - \o Extract \c{mingw-utils-0.3.tar.gz} into, e.g. \c{C:\MinGW}. - - \o Add the path for \c{MinGW-5.1.6.exe} to your \c{PATH} variable, - e.g. \c{C:\MinGW\bin;} - - \o Extract the Qt sources, (\c{qt-everywhere-opensource-src-4.6.2.zip}), - into, e.g. \c{C:\Qt}. - - \o Add the path for the eventual Qt binary to your \c{PATH} variable, - e.g. \c{C:\Qt\4.6.2\bin;}. - - \o Install MySQL (\c{mysql-5.1.35-win32.msi}), customizing the - components. Select only the headers and libraries. Install in, - e.g. \c{C:\MySQL\MySQL51}. - - \o Open the DOS prompt, go to \c{C:\MySQL\MySQL51\lib\opt}, and run - the following commands: - \list - \o \c{reimp -d libmysql.lib} - \o \c{dlltool -k -d libmysql.def -l libmysql.a} - \endlist - - \o Open the DOS prompt, go to \c{C:\Qt\4.6.2} and run the following commands: - \list - \o \c{configure.exe -debug-and-release -platform win32-g++ -qt-sql-mysql - -l mysql -I C:\MySQL\MySQL51\include -L C:\MySQL\MySQL51\lib\opt} - \o \c{mingw32-make sub-src} - \endlist - This step takes a long time. - - \o Open the DOS prompt, go to - \c{C:\Qt\4.6.2\src\plugins\sqldrivers\mysql} and run the - following command: - \list - \o \c{qmake "INCLUDEPATH+=C:\MySQL\MySQL51\include" "LIBS+=-L. mysql" mysql.pro} - \endlist - - \o Now the following libraries are ready in \c{C:\Qt\4.6.2\plugins\sqldrivers}. - \list - \o \c{libqsqlmysql4.a} - \o \c{libqsqlmysqld4.a} - \o \c{qsqlmysql4.dll} - \o \c{qsqlmysqld4.dll} - \endlist - To use the SDK and QtCreator directly, copy these libraries to - your \c{C:\Qt\...\qt\plugins\sqldrivers\}, and copy - \c{C:\MySQL\MySQL51\lib\opt\libmysql.dll} to your \c{C:\Qt\...\qt\bin\}. - - \endlist - - \target QOCI - \section2 QOCI for the Oracle Call Interface (OCI) - - \section3 General Information about the OCI plugin - - The Qt OCI plugin supports Oracle 9i, 10g and higher. After - connecting to the Oracle server, the plugin will auto-detect the - database version and enable features accordingly. - - It's possible to connect to a Oracle database without a tnsnames.ora file. - This requires that the database SID is passed to the driver as the database - name and that a hostname is given. - - \section3 OCI User Authentication - - The Qt OCI plugin supports authentication using - external credentials (OCI_CRED_EXT). Usually, this means that the database - server will use the user authentication provided by the operating system - instead of its own authentication mechanism. - - Leave the username and password empty when opening a connection with - QSqlDatabase to use the external credentials authentication. - - \section3 OCI BLOB/LOB Support - - Binary Large Objects (BLOBs) can be read and written, but be aware - that this process may require a lot of memory. You should use a forward - only query to select LOB fields (see QSqlQuery::setForwardOnly()). - - Inserting BLOBs should be done using either a prepared query where the - BLOBs are bound to placeholders or QSqlTableModel, which uses a prepared - query to do this internally. - - \section3 How to Build the OCI Plugin on Unix and Mac OS X - - For Oracle 10g, all you need is the "Instant Client Package - Basic" and - "Instant Client Package - SDK". For Oracle prior to 10g, you require - the standard Oracle client and the SDK packages. - - Oracle library files required to build the driver: - - \list - \i \c libclntsh.so (all versions) - \i \c libwtc9.so (only Oracle 9) - \endlist - - Tell \c qmake where to find the Oracle header files and shared - libraries and run make: - - For Oracle version 9: - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 6 - - For Oracle version 10, we assume that you installed the RPM packages of the - Instant Client Package SDK (you need to adjust the version number accordingly): - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 7 - - \bold{Note:} If you are using the Oracle Instant Client package, - you will need to set LD_LIBRARY_PATH when building the OCI SQL plugin - and when running an applicaiton that uses the OCI SQL plugin. You can - avoid this requirement by setting and RPATH and listing all of the - libraries to link to. Here is an example: - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 32 - - If you wish to build the OCI plugin manually with this method the procedure looks like this: - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 33 - - \section3 How to Build the OCI Plugin on Windows - - Choosing the option "Programmer" in the Oracle Client Installer from - the Oracle Client Installation CD is generally sufficient to build the - plugin. For some versions of Oracle Client, you may also need to select - the "Call Interface (OCI)" option if it is available. - - Build the plugin as follows (here it is assumed that Oracle Client is - installed in \c{C:\oracle}): - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 8 - - If you are not using a Microsoft compiler, replace \c nmake with \c - make in the line above. - - When you run your application you will also need to add the \c oci.dll - path to your \c PATH environment variable: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 9 - - \bold{Note:} This database plugin is not supported for Windows CE. - - \target QODBC - \section2 QODBC for Open Database Connectivity (ODBC) - - \section3 General Information about the ODBC plugin - - ODBC is a general interface that allows you to connect to multiple - DBMSs using a common interface. The QODBC driver allows you to connect - to an ODBC driver manager and access the available data sources. Note - that you also need to install and configure ODBC drivers for the ODBC - driver manager that is installed on your system. The QODBC plugin - then allows you to use these data sources in your Qt applications. - - \bold{Note:} You should use native drivers in preference to the ODBC - driver where they are available. ODBC support can be used as a fallback - for compliant databases if no native drivers are available. - - On Windows an ODBC driver manager should be installed by default. - For Unix systems there are some implementations which must be - installed first. Note that every client that uses your application is - required to have an ODBC driver manager installed, otherwise the - QODBC plugin will not work. - - Be aware that when connecting to an ODBC datasource you must pass in - the name of the ODBC datasource to the QSqlDatabase::setDatabaseName() - function rather than the actual database name. - - The QODBC Plugin needs an ODBC compliant driver manager version 2.0 or - later to work. Some ODBC drivers claim to be version 2.0 compliant, - but do not offer all the necessary functionality. The QODBC plugin - therefore checks whether the data source can be used after a - connection has been established and refuses to work if the check - fails. If you don't like this behavior, you can remove the \c{#define - ODBC_CHECK_DRIVER} line from the file \c{qsql_odbc.cpp}. Do this at - your own risk! - - By default, Qt instructs the ODBC driver to behave as an ODBC 2.x - driver. However, for some \e{driver-manager/ODBC 3.x-driver} - combinations (e.g., \e{unixODBC/MaxDB ODBC}), telling the ODBC - driver to behave as a 2.x driver can cause the driver plugin to - have unexpected behavior. To avoid this problem, instruct the ODBC - driver to behave as a 3.x driver by - \l{QSqlDatabase::setConnectOptions()} {setting the connect option} - \c{"SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3"} before you - \l{QSqlDatabase::open()} {open your database connection}. Note - that this will affect multiple aspects of ODBC driver behavior, - e.g., the SQLSTATEs. Before setting this connect option, consult - your ODBC documentation about behavior differences you can expect. - - If you experience very slow access of the ODBC datasource, make sure - that ODBC call tracing is turned off in the ODBC datasource manager. - - Some drivers don't support scrollable cursors. In that case case only - queries in forwardOnly mode can be used successfully. - - \section3 ODBC Stored Procedure Support - - With Microsoft SQL Server the result set returned by a stored - procedure that uses the return statement, or returns multiple result - sets, will be accessible only if you set the query's forward only - mode to \e forward using \l QSqlQuery::setForwardOnly(). - - \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 10 - - \bold{Note:} The value returned by the stored procedure's return statement - is discarded. - - \section3 ODBC Unicode Support - - The QODBC Plugin will use the Unicode API if UNICODE is defined. On - Windows NT based systems, this is the default. Note that the ODBC - driver and the DBMS must also support Unicode. - - Some driver managers and drivers don't support UNICODE. To use the - QODBC plugin with such drivers it has to be compiled with the - Q_ODBC_VERSION_2 defined. - - For the Oracle 9 ODBC driver (Windows), it is neccessary to check - "SQL_WCHAR support" in the ODBC driver manager otherwise Oracle - will convert all Unicode strings to local 8-bit. - - \section3 How to Build the ODBC Plugin on Unix and Mac OS X - - It is recommended that you use unixODBC. You can find the latest - version and ODBC drivers at \l http://www.unixodbc.org. - You need the unixODBC header files and shared libraries. - - Tell \c qmake where to find the unixODBC header files and shared - libraries (here it is assumed that unixODBC is installed in - \c{/usr/local/unixODBC}) and run \c{make}: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 11 - - \section3 How to Build the ODBC Plugin on Windows - - The ODBC header and include files should already be installed in the - right directories. You just have to build the plugin as follows: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 12 - - If you are not using a Microsoft compiler, replace \c nmake with \c - make in the line above. - - \bold{Note:} This database plugin is not officially supported for Windows CE. - - \target QPSQL - \section2 QPSQL for PostgreSQL (Version 7.3 and Above) - - \section3 General Information about the QPSQL driver - - The QPSQL driver supports version 7.3 and higher of the PostgreSQL server. - We recommend that you use a client library from version 7.3.15, 7.4.13, - 8.0.8, 8.1.4 or more recent as these versions contain security fixes, and - as the QPSQL driver might not build with older versions of the client - library depending on your platform. - - For more information about PostgreSQL visit \l http://www.postgresql.org. - - \section3 QPSQL Unicode Support - - The QPSQL driver automatically detects whether the PostgreSQL - database you are connecting to supports Unicode or not. Unicode is - automatically used if the server supports it. Note that the driver - only supports the UTF-8 encoding. If your database uses any other - encoding, the server must be compiled with Unicode conversion - support. - - Unicode support was introduced in PostgreSQL version 7.1 and it will - only work if both the server and the client library have been compiled - with multibyte support. More information about how to set up a - multibyte enabled PostgreSQL server can be found in the PostgreSQL - Administrator Guide, Chapter 5. - - \section3 QPSQL BLOB Support - - Binary Large Objects are supported through the \c BYTEA field type in - PostgreSQL server versions >= 7.1. - - \section3 How to Build the QPSQL Plugin on Unix and Mac OS X - - You need the PostgreSQL client library and headers installed. - - To make \c qmake find the PostgreSQL header files and shared - libraries, run \c qmake the following way (assuming that the - PostgreSQL client is installed in \c{/usr}): - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 13 - - After installing Qt, as described in the \l{Installing Qt for X11 Platforms} document, - you also need to install the plugin in the standard location: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 14 - - \section3 How to Build the QPSQL Plugin on Windows - - Install the appropriate PostgreSQL developer libraries for your - compiler. Assuming that PostgreSQL was installed in \c{C:\psql}, - build the plugin as follows: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 15 - - Users of MinGW may wish to consult the following online document: - \l{Compiling PostgreSQL On Native Win32 FAQ}. - - \bold{Note:} This database plugin is not supported for Windows CE. - - \target QTDS - \section2 QTDS for Sybase Adaptive Server - - \note TDS is no longer used by MS Sql Server, and is superceded by - \l{QODBC}{ODBC}. QTDS is obsolete from Qt 4.7. - - \section3 General Information about QTDS - - It is not possible to set the port with QSqlDatabase::setPort() due to limitations in the - Sybase client library. Refer to the Sybase documentation for information on how to set up - a Sybase client configuration file to enable connections to databases on non-default ports. - - \section3 How to Build the QTDS Plugin on Unix and Mac OS X - - Under Unix, two libraries are available which support the TDS protocol: - - \list - \i FreeTDS, a free implementation of the TDS protocol - (\l{http://www.freetds.org}). Note that FreeTDS is not yet stable, - so some functionality may not work as expected. - - \i Sybase Open Client, available from \l{http://www.sybase.com}. - Note for Linux users: Get the Open Client RPM from - \l{http://linux.sybase.com}. - \endlist - - Regardless of which library you use, the shared object file - \c{libsybdb.so} is needed. Set the \c SYBASE environment variable to - point to the directory where you installed the client library and - execute \c{qmake}: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 16 - - \section3 How to Build the QDTS Plugin on Windows - - You can either use the DB-Library supplied by Microsoft or the Sybase - Open Client (\l{http://www.sybase.com}). You must include \c - NTWDBLIB.LIB to build the plugin: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 17 - - By default the Microsoft library is used on Windows, if you want to - force the use of the Sybase Open Client, you must define \c - Q_USE_SYBASE in \c{%QTDIR%\src\sql\drivers\tds\qsql_tds.cpp}. If you - are not using a Microsoft compiler, replace \c nmake with \c make in - the line above. - - \bold{Note:} This database plugin is not supported for Windows CE. - - \target QDB2 - \section2 QDB2 for IBM DB2 (Version 7.1 and Above) - - \section3 General Information about QDB2 - - The Qt DB2 plugin makes it possible to access IBM DB2 databases. It - has been tested with IBM DB2 v7.1 and 7.2. You must install the IBM - DB2 development client library, which contains the header and library - files necessary for compiling the QDB2 plugin. - - The QDB2 driver supports prepared queries, reading/writing of Unicode - strings and reading/writing of BLOBs. - - We suggest using a forward-only query when calling stored procedures - in DB2 (see QSqlQuery::setForwardOnly()). - - \section3 How to Build the QDB2 Plugin on Unix and Mac OS X - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 18 - - After installing Qt, as described in the \l{Installing Qt for X11 Platforms} document, - you also need to install the plugin in the standard location: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 19 - - \section3 How to Build the QDB2 Plugin on Windows - - The DB2 header and include files should already be installed in the - right directories. You just have to build the plugin as follows: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 20 - - If you are not using a Microsoft compiler, replace \c nmake - with \c make in the line above. - - \bold{Note:} This database plugin is not supported for Windows CE. - - \target QSQLITE2 - \section2 QSQLITE2 for SQLite Version 2 - - The Qt SQLite 2 plugin is offered for compatibility. Whenever - possible, use the \l{#QSQLITE}{version 3 plugin} instead. The - build instructions for version 3 apply to version 2 as well. - - \target QSQLITE - \section2 QSQLITE for SQLite (Version 3 and Above) - - \section3 General Information about QSQLITE - - The Qt SQLite plugin makes it possible to access SQLite - databases. SQLite is an in-process database, which means that it - is not necessary to have a database server. SQLite operates on a - single file, which must be set as the database name when opening - a connection. If the file does not exist, SQLite will try to - create it. SQLite also supports in-memory databases, simply pass - ":memory:" as the database name. - - SQLite has some restrictions regarding multiple users and - multiple transactions. If you try to read/write on a resource from different - transactions, your application might freeze until one transaction commits - or rolls back. The Qt SQLite driver will retry to write to a locked resource - until it runs into a timeout (see \c{QSQLITE_BUSY_TIMEOUT} - at QSqlDatabase::setConnectOptions()). - - In SQLite any column, with the exception of an INTEGER PRIMARY KEY column, - may be used to store any type of value. For instance, a column declared as - INTEGER may contain an integer value in one row and a text value in the - next. This is due to SQLite associating the type of a value with the value - itself rather than with the column it is stored in. A consequence of this - is that the type returned by QSqlField::type() only indicates the field's - recommended type. No assumption of the actual type should be made from - this and the type of the individual values should be checked. - - The driver is locked for updates while a select is executed. This - may cause problems when using QSqlTableModel because Qt's item views - fetch data as needed (with QSqlQuery::fetchMore() in the case of - QSqlTableModel). - - You can find information about SQLite on \l{http://www.sqlite.org}. - - \section3 How to Build the QSQLITE Plugin - - SQLite version 3 is included as a third-party library within Qt. - It can be built by passing the following parameters to the - configure script: \c{-plugin-sql-sqlite} (build as a plugin) or - \c{-qt-sql-sqlite} (linked directly into the Qt library). - - If you don't want to use the SQLite library included with Qt, you - can build it manually (replace \c $SQLITE by the directory where - SQLite resides): - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 21 - - After installing Qt, as described in the \l{Installing Qt for X11 Platforms} document, - you also need to install the plugin in the standard location: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 22 - - On Windows: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 23 - - \section3 QSQLITE File Format Compatibility - - SQLite minor releases sometimes break file format forward compatibility. - For example, SQLite 3.3 can read database files created with SQLite 3.2, - but databases created with SQLite 3.3 cannot be read by SQLite 3.2. - Please refer to the SQLite documentation and change logs for information about - file format compatibility between versions. - - Qt minor releases usually follow the SQLite minor releases, while Qt patch releases - follow SQLite patch releases. Patch releases are therefore both backward and forward - compatible. - - To force SQLite to use a specific file format, it is neccessary to build and - ship your own database plugin with your own SQLite library as illustrated above. - Some versions of SQLite can be forced to write a specific file format by setting - the \c{SQLITE_DEFAULT_FILE_FORMAT} define when building SQLite. - - \target QIBASE - \section2 QIBASE for Borland InterBase - - \section3 General Information about QIBASE - - The Qt InterBase plugin makes it possible to access the InterBase and - Firebird databases. InterBase can either be used as a client/server or - without a server in which case it operates on local files. The - database file must exist before a connection can be established. Firebird - must be used with a server configuration. - - Note that InterBase requires you to specify the full path to the - database file, no matter whether it is stored locally or on another - server. - - \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 24 - - You need the InterBase/Firebird development headers and libraries - to build this plugin. - - Due to license incompatibilities with the GPL, users of the Qt Open Source - Edition are not allowed to link this plugin to the commercial editions of - InterBase. Please use Firebird or the free edition of InterBase. - - \section3 QIBASE Unicode Support and Text Encoding - - By default the driver connects to the database using UNICODE_FSS. This can - be overridden by setting the ISC_DPB_LC_CTYPE parameter with - QSqlDatabase::setConnectOptions() before opening the connection. - - \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 25 - - If Qt doesn't support the given text encoding the driver will issue a - warning message and connect to the database using UNICODE_FSS. - - Note that if the text encoding set when connecting to the database is - not the same as in the database, problems with transliteration might arise. - - \section3 QIBASE Stored procedures - - InterBase/Firebird return OUT values as result set, so when calling stored - procedure, only IN values need to be bound via QSqlQuery::bindValue(). The - RETURN/OUT values can be retrieved via QSqlQuery::value(). Example: - - \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 26 - - \section3 How to Build the QIBASE Plugin on Unix and Mac OS X - - The following assumes InterBase or Firebird is installed in - \c{/opt/interbase}: - - If you are using InterBase: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 27 - - If you are using Firebird, the Firebird library has to be set explicitly: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 28 - - \section3 How to Build the QIBASE Plugin on Windows - - The following assumes InterBase or Firebird is installed in - \c{C:\interbase}: - - If you are using InterBase: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 29 - - If you are using Firebird, the Firebird library has to be set explicitely: - - \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 30 - - If you are not using a Microsoft compiler, replace \c nmake - with \c make in the line above. - - Note that \c{C:\interbase\bin} must be in the \c PATH. - - \bold{Note:} This database plugin is not supported for Windows CE. - - \target troubleshooting - \section1 Troubleshooting - - You should always use client libraries that have been compiled with - the same compiler as you are using for your project. If you cannot get - a source distibution to compile the client libraries yourself, you - must make sure that the pre-compiled library is compatible with - your compiler, otherwise you will get a lot of "undefined symbols" - errors. Some compilers have tools to convert libraries, e.g. Borland - ships the tool \c{COFF2OMF.EXE} to convert libraries that have been - generated with Microsoft Visual C++. - - If the compilation of a plugin succeeds but it cannot be loaded, - make sure that the following requirements are met: - - \list - \i Ensure that you are using a shared Qt library; you cannot use the - plugins with a static build. - \i Ensure that the plugin is in the correct directory. You can use - QApplication::libraryPaths() to determine where Qt looks for plugins. - \i Ensure that the client libraries of the DBMS are available on the - system. On Unix, run the command \c{ldd} and pass the name of the - plugin as parameter, for example \c{ldd libqsqlmysql.so}. You will - get a warning if any of the client libraries couldn't be found. - On Windows, you can use Visual Studio's dependency walker. - \i Compile Qt with \c{QT_DEBUG_COMPONENT} defined to get very verbose - debug output when loading plugins. - \endlist - - Make sure you have followed the guide to \l{Deploying Plugins}. - If you experience plugin load problems and see output like this: - - \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 31 - - the problem is usually that the plugin had the wrong \l{Deploying - Plugins#The Build Key}{build key}. This might require removing an - entry from the \l{Deploying Plugins#The Plugin Cache} {plugin cache}. - - \target development - \section1 How to Write Your Own Database Driver - - QSqlDatabase is responsible for loading and managing database driver - plugins. When a database is added (see QSqlDatabase::addDatabase()), - the appropriate driver plugin is loaded (using QSqlDriverPlugin). - QSqlDatabase relies on the driver plugin to provide interfaces for - QSqlDriver and QSqlResult. - - QSqlDriver is an abstract base class which defines the functionality - of a SQL database driver. This includes functions such as - QSqlDriver::open() and QSqlDriver::close(). QSqlDriver is responsible - for connecting to a database, establish the proper environment, etc. - In addition, QSqlDriver can create QSqlQuery objects appropriate for - the particular database API. QSqlDatabase forwards many of its - function calls directly to QSqlDriver which provides the concrete - implementation. - - QSqlResult is an abstract base class which defines the functionality - of a SQL database query. This includes statements such as \c{SELECT}, - \c{UPDATE}, and \c{ALTER} \c{TABLE}. QSqlResult contains functions - such as QSqlResult::next() and QSqlResult::value(). QSqlResult is - responsible for sending queries to the database, returning result - data, etc. QSqlQuery forwards many of its function calls directly to - QSqlResult which provides the concrete implementation. - - QSqlDriver and QSqlResult are closely connected. When implementing a - Qt SQL driver, both of these classes must to be subclassed and the - abstract virtual methods in each class must be implemented. - - To implement a Qt SQL driver as a plugin (so that it is - recognized and loaded by the Qt library at runtime), the driver - must use the Q_EXPORT_PLUGIN2() macro. Read \l{How to Create Qt - Plugins} for more information on this. You can also check out how - this is done in the SQL plugins that are provided with Qt in - \c{QTDIR/src/plugins/sqldrivers} and \c{QTDIR/src/sql/drivers}. - - The following code can be used as a skeleton for a SQL driver: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 47 - \codeline - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 48 -*/ diff --git a/doc/src/sql-programming/sql-programming.qdoc b/doc/src/sql-programming/sql-programming.qdoc deleted file mode 100644 index 55f97484bb..0000000000 --- a/doc/src/sql-programming/sql-programming.qdoc +++ /dev/null @@ -1,609 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group database - \title Database Classes - - \brief Database related classes, e.g. for SQL databases. -*/ - -/*! - \page sql-programming.html - \title SQL Programming - \ingroup qt-sql - \nextpage Connecting to Databases - - \brief Database integration for Qt applications. - - This overview assumes that you have at least a basic knowledge of - SQL. You should be able to understand simple \c SELECT, \c - INSERT, \c UPDATE, and \c DELETE statements. Although the \l - QSqlTableModel class provides an interface to database browsing - and editing that does not require a knowledge of SQL, a basic - understanding of SQL is highly recommended. A standard text - covering SQL databases is \e {An Introduction to Database Systems} - (7th Ed.) by C. J. Date, ISBN 0201385902. - - \section1 Topics: - - \list - \o \l{Database Classes} - \o \l{Connecting to Databases} - \list - \o \l{SQL Database Drivers} - \endlist - \o \l{Executing SQL Statements} - \list - \o \l{Data Types for Qt-supported Database Systems} - \endlist - \o \l{Using the SQL Model Classes} - \o \l{Presenting Data in a Table View} - \o \l{Creating Data-Aware Forms} - \endlist - - \section1 Database Classes - - These classes provide access to SQL databases. - - \annotatedlist database - - The SQL classes are divided into three layers: - - \section2 Driver Layer - - This comprises the classes QSqlDriver, QSqlDriverCreator, - QSqlDriverCreatorBase, QSqlDriverPlugin, and QSqlResult. - - This layer provides the low-level bridge between the specific databases - and the SQL API layer. See \l{SQL Database Drivers} for more information. - - \section2 SQL API Layer - - These classes provide access to databases. Connections - are made using the QSqlDatabase class. Database - interaction is achieved by using the QSqlQuery class. - In addition to QSqlDatabase and QSqlQuery, the SQL API - layer is supported by QSqlError, QSqlField, QSqlIndex, - and QSqlRecord. - - \section2 User Interface Layer - - These classes link the data from a database to data-aware widgets. - They include QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel. - These classes are designed to work with Qt's - \l{Model/View Programming}{model/view framework}. - - Note that to use any of these classes, a QCoreApplication object - must have been instantiated first. -*/ - -/*! - \page sql-connecting.html - \title Connecting to Databases - \ingroup qt-sql - - \contentspage SQL Programming - \previouspage SQL Programming - \nextpage Executing SQL Statements - - To access a database with QSqlQuery or QSqlQueryModel, create and - open one or more database connections. Database connections are - normally identified by connection name, \e{not} by database name. - You can have multiple connections to the same database. - QSqlDatabase also supports the concept of a \e{default} - connection, which is an unnamed connection. When calling QSqlQuery - or QSqlQueryModel member functions that take a connection name - argument, if you don't pass a connection name, the default - connection will be used. Creating a default connection is - convenient when your application only requires one database - connection. - - Note the difference between creating a connection and opening it. - Creating a connection involves creating an instance of class - QSqlDatabase. The connection is not usable until it is opened. The - following snippet shows how to create a \e{default} connection - and then open it: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 26 - - The first line creates the connection object, and the last line - opens it for use. In between, we initialize some connection - information, including the \l{QSqlDatabase::setDatabaseName()} - {database name}, the \l{QSqlDatabase::setHostName()} {host name}, - the \l{QSqlDatabase::setUserName()} {user name}, and the - \l{QSqlDatabase::setPassword()} {password}. In this case, we are - connecting to the MySQL database \c{flightdb} on the host - \c{bigblue}. The \c{"QMYSQL"} argument to - \l{QSqlDatabase::addDatabase()} {addDatabase()} specifies the type - of database driver to use for the connection. The set of database - drivers included with Qt are shown in the table of \l{SQL Database - Drivers#Supported Databases} {supported database drivers}. - - The connection in the snippet will be the \e{default} connection, - because we don't pass the second argument to - \l{QSqlDatabase::addDatabase()} {addDatabase()}, which is the - connection name. For example, here we establish two MySQL database - connections named \c{"first"} and \c{"second"}: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 27 - - After these connections have been initialized, \l{QSqlDatabase::} - {open()} for each one to establish the live connections. If the - \l{QSqlDatabase::} {open()} fails, it returns false. In that case, - call QSqlDatabase::lastError() to get error information. - - Once a connection is established, we can call the static function - QSqlDatabase::database() from anywhere with a connection name to - get a pointer to that database connection. If we don't pass a - connection name, it will return the default connection. For - example: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 28 - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 29 - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 30 - - To remove a database connection, first close the database using - QSqlDatabase::close(), then remove it using the static method - QSqlDatabase::removeDatabase(). -*/ - -/*! - \page sql-sqlstatements.html - \title Executing SQL Statements - \ingroup qt-sql - - \previouspage Connecting to Databases - \contentspage SQL Programming - \nextpage Using the SQL Model Classes - - - The QSqlQuery class provides an interface for executing SQL - statements and navigating through the result set of a query. - - The QSqlQueryModel and QSqlTableModel classes described in the - next section provide a higher-level interface for accessing - databases. If you are unfamiliar with SQL, you might want to skip - directly to the next section (\l{Using the SQL Model Classes}). - - \section2 Executing a Query - - To execute an SQL statement, simply create a QSqlQuery object and - call QSqlQuery::exec() like this: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 31 - - The QSqlQuery constructor accepts an optional QSqlDatabase object - that specifies which database connection to use. In the example - above, we don't specify any connection, so the default connection - is used. - - If an error occurs, \l{QSqlQuery::exec()}{exec()} returns false. - The error is then available as QSqlQuery::lastError(). - - \section2 Navigating the Result Set - - QSqlQuery provides access to the result set one record at a time. - After the call to \l{QSqlQuery::exec()}{exec()}, QSqlQuery's - internal pointer is located one position \e{before} the first - record. We must call QSqlQuery::next() once to advance to the - first record, then \l{QSqlQuery::next()}{next()} again repeatedly - to access the other records, until it returns false. Here's a - typical loop that iterates over all the records in order: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 32 - - The QSqlQuery::value() function returns the value of a field in - the current record. Fields are specified as zero-based indexes. - QSqlQuery::value() returns a QVariant, a type that can hold - various C++ and core Qt data types such as \c int, QString, and - QByteArray. The different database types are automatically mapped - into the closest Qt equivalent. In the code snippet, we call - QVariant::toString() and QVariant::toInt() to convert - variants to QString and \c int. - - For an overview of the recommended types for use with Qt-supported - Databases, please refer to \l{Data Types for Qt-supported Database - Systems} {this table}. - - You can iterate back and forth using QSqlQuery::next(), - QSqlQuery::previous(), QSqlQuery::first(), QSqlQuery::last(), and - QSqlQuery::seek(). The current row index is returned by - QSqlQuery::at(), and the total number of rows in the result set - is avaliable as QSqlQuery::size() for databases that support it. - - To determine whether a database driver supports a given feature, - use QSqlDriver::hasFeature(). In the following example, we call - QSqlQuery::size() to determine the size of a result set of - the underlying database supports that feature; otherwise, we - navigate to the last record and use the query's position to tell - us how many records there are. - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 33 - - If you iterate through a result set only using next() and seek() - with positive values, you can call - QSqlQuery::setForwardOnly(true) before calling exec(). This is an - easy optimization that will speed up the query significantly when - operating on large result sets. - - \section2 Inserting, Updating, and Deleting Records - - QSqlQuery can execute arbitrary SQL statements, not just - \c{SELECT}s. The following example inserts a record into a table - using \c{INSERT}: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 34 - - If you want to insert many records at the same time, it is often - more efficient to separate the query from the actual values being - inserted. This can be done using placeholders. Qt supports two - placeholder syntaxes: named binding and positional binding. - Here's an example of named binding: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 35 - - Here's an example of positional binding: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 36 - - Both syntaxes work with all database drivers provided by Qt. If - the database supports the syntax natively, Qt simply forwards the - query to the DBMS; otherwise, Qt simulates the placeholder syntax - by preprocessing the query. The actual query that ends up being - executed by the DBMS is available as QSqlQuery::executedQuery(). - - When inserting multiple records, you only need to call - QSqlQuery::prepare() once. Then you call - \l{QSqlQuery::bindValue()}{bindValue()} or - \l{QSqlQuery::addBindValue()}{addBindValue()} followed by - \l{QSqlQuery::exec()}{exec()} as many times as necessary. - - Besides performance, one advantage of placeholders is that you - can easily specify arbitrary values without having to worry about - escaping special characters. - - Updating a record is similar to inserting it into a table: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 37 - - You can also use named or positional binding to associate - parameters to actual values. - - Finally, here's an example of a \c DELETE statement: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 38 - - \section2 Transactions - - If the underlying database engine supports transactions, - QSqlDriver::hasFeature(QSqlDriver::Transactions) will return - true. You can use QSqlDatabase::transaction() to initiate a - transaction, followed by the SQL commands you want to execute - within the context of the transaction, and then either - QSqlDatabase::commit() or QSqlDatabase::rollback(). When - using transactions you must start the transaction before you - create your query. - - Example: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 39 - - Transactions can be used to ensure that a complex operation is - atomic (for example, looking up a foreign key and creating a - record), or to provide a means of canceling a complex change in - the middle. - - \omit - It would be useful to mention transactions, and the fact that - some databases don't support them. - \endomit -*/ - -/*! - \page sql-model.html - \title Using the SQL Model Classes - \ingroup qt-sql - - \previouspage Executing SQL Statements - \contentspage SQL Programming - \nextpage Presenting Data in a Table View - - In addition to QSqlQuery, Qt offers three higher-level classes - for accessing databases. These classes are QSqlQueryModel, - QSqlTableModel, and QSqlRelationalTableModel. - - \table - \row \o QSqlQueryModel - \o A read-only model based on an arbitrary SQL query. - \row \o QSqlTableModel - \o A read-write model that works on a single table. - \row \o QSqlRelationalTableModel - \o A QSqlTableModel subclass with foreign key support. - \endtable - - These classes derive from QAbstractTableModel (which in turn - inherits from QAbstractItemModel) and make it easy to present - data from a database in an item view class such as QListView and - QTableView. This is explained in detail in the \l{Presenting Data - in a Table View} section. - - Another advantage of using these classes is that it can make your - code easier to adapt to other data sources. For example, if you - use QSqlTableModel and later decide to use XML files to store - data instead of a database, it is essentially just a matter of - replacing one data model with another. - - \section2 The SQL Query Model - - QSqlQueryModel offers a read-only model based on an SQL query. - - Example: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 40 - - After setting the query using QSqlQueryModel::setQuery(), you can - use QSqlQueryModel::record(int) to access the individual records. - You can also use QSqlQueryModel::data() and any of the other - functions inherited from QAbstractItemModel. - - There's also a \l{QSqlQueryModel::setQuery()}{setQuery()} - overload that takes a QSqlQuery object and operates on its result - set. This enables you to use any features of QSqlQuery to set up - the query (e.g., prepared queries). - - \section2 The SQL Table Model - - QSqlTableModel offers a read-write model that works on a single - SQL table at a time. - - Example: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 41 - - QSqlTableModel is a high-level alternative to QSqlQuery for - navigating and modifying individual SQL tables. It typically - results in less code and requires no knowledge of SQL syntax. - - Use QSqlTableModel::record() to retrieve a row in the table, and - QSqlTableModel::setRecord() to modify the row. For example, the - following code will increase every employee's salary by 10 per - cent: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 42 - - You can also use QSqlTableModel::data() and - QSqlTableModel::setData(), which are inherited from - QAbstractItemModel, to access the data. For example, here's how - to update a record using - \l{QSqlTableModel::setData()}{setData()}: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 43 - - Here's how to insert a row and populate it: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 44 - - Here's how to delete five consecutive rows: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 45 - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 46 - - The first argument to QSqlTableModel::removeRows() is the index - of the first row to delete. - - When you're finished changing a record, you should always call - QSqlTableModel::submitAll() to ensure that the changes are - written to the database. - - When and whether you actually \e need to call submitAll() depends - on the table's \l{QSqlTableModel::editStrategy()}{edit strategy}. - The default strategy is QSqlTableModel::OnRowChange, which - specifies that pending changes are applied to the database when - the user selects a different row. Other strategies are - QSqlTableModel::OnManualSubmit (where all changes are cached in - the model until you call submitAll()) and - QSqlTableModel::OnFieldChange (where no changes are cached). - These are mostly useful when QSqlTableModel is used with a view. - - QSqlTableModel::OnFieldChange seems to deliver the promise that - you never need to call submitAll() explicitly. There are two - pitfalls, though: - - \list - \o Without any caching, performance may drop significantly. - \o If you modify a primary key, the record might slip through - your fingers while you are trying to populate it. - \endlist - - \section2 The SQL Relational Table Model - - QSqlRelationalTableModel extends QSqlTableModel to provide - support for foreign keys. A foreign key is a 1-to-1 mapping - between a field in one table and the primary key field of another - table. For example, if a \c book table has a field called \c - authorid that refers to the author table's \c id field, we say - that \c authorid is a foreign key. - - \table - \row \o \inlineimage noforeignkeys.png - \o \inlineimage foreignkeys.png - \endtable - - The screenshot on the left shows a plain QSqlTableModel in a - QTableView. Foreign keys (\c city and \c country) aren't resolved - to human-readable values. The screenshot on the right shows a - QSqlRelationalTableModel, with foreign keys resolved into - human-readable text strings. - - The following code snippet shows how the QSqlRelationalTableModel - was set up: - - \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 0 - \codeline - \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 1 - \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 2 - - See the QSqlRelationalTableModel documentation for details. -*/ - -/*! - \page sql-presenting.html - \title Presenting Data in a Table View - \ingroup qt-sql - - \previouspage Using the SQL Model Classes - \contentspage SQL Programming - \nextpage Creating Data-Aware Forms - - The QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel - classes can be used as a data source for Qt's view classes such - as QListView, QTableView, and QTreeView. In practice, QTableView - is by far the most common choice, because an SQL result set is - essentially a two-dimensional data structure. - - \image relationaltable.png A table view displaying a QSqlTableModel - - The following example creates a view based on an SQL data model: - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 17 - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 18 - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 19 - - If the model is a read-write model (e.g., QSqlTableModel), the - view lets the user edit the fields. You can disable this by - calling - - \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 20 - - You can use the same model as a data source for multiple views. - If the user edits the model through one of the views, the other - views will reflect the changes immediately. The - \l{sql/tablemodel}{Table Model} example shows how it works. - - View classes display a header at the top to label the columns. To - change the header texts, call - \l{QAbstractItemModel::setHeaderData()}{setHeaderData()} on the - model. The header's labels default to the table's field names. - For example: - - \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 3 - - QTableView also has a vertical header on the left with numbers - identifying the rows. If you insert rows programmatically using - QSqlTableModel::insertRows(), the new rows will be marked with an - asterisk (*) until they are submitted using - \l{QSqlTableModel::submitAll()}{submitAll()} or automatically - when the user moves to another record (assuming the - \l{QSqlTableModel::EditStrategy}{edit strategy} is - QSqlTableModel::OnRowChange). - - \image insertrowinmodelview.png Inserting a row in a model - - Likewise, if you remove rows using - \l{QSqlTableModel::removeRows()}{removeRows()}, the rows will be - marked with an exclamation mark (!) until the change is - submitted. - - The items in the view are rendered using a delegate. The default - delegate, QItemDelegate, handles the most common data types (\c - int, QString, QImage, etc.). The delegate is also responsible for - providing editor widgets (e.g., a combobox) when the user starts - editing an item in the view. You can create your own delegates by - subclassing QAbstractItemDelegate or QItemDelegate. See - \l{Model/View Programming} for more information. - - QSqlTableModel is optimized to operate on a single table at a - time. If you need a read-write model that operates on an - arbitrary result set, you can subclass QSqlQueryModel and - reimplement \l{QAbstractItemModel::flags()}{flags()} and - \l{QAbstractItemModel::setData()}{setData()} to make it - read-write. The following two functions make fields 1 and 2 of a - query model editable: - - \snippet examples/sql/querymodel/editablesqlmodel.cpp 0 - \codeline - \snippet examples/sql/querymodel/editablesqlmodel.cpp 1 - - The setFirstName() helper function is defined as follows: - - \snippet examples/sql/querymodel/editablesqlmodel.cpp 2 - - The setLastName() function is similar. See the - \l{sql/querymodel}{Query Model} example for the complete source code. - - Subclassing a model makes it possible to customize it in many - ways: You can provide tooltips for the items, change the - background color, provide calculated values, provide different - values for viewing and editing, handle null values specially, and - more. See \l{Model/View Programming} as well as the \l - QAbstractItemView reference documentation for details. - - If all you need is to resolve a foreign key to a more - human-friendly string, you can use QSqlRelationalTableModel. For - best results, you should also use QSqlRelationalDelegate, a - delegate that provides combobox editors for editing foreign keys. - - \image relationaltable.png Editing a foreign key in a relational table - - The \l{sql/relationaltablemodel}{Relational Table Model} example - illustrates how to use QSqlRelationalTableModel in conjunction with - QSqlRelationalDelegate to provide tables with foreign key - support. -*/ - -/*! - \page sql-forms.html - \title Creating Data-Aware Forms - \ingroup qt-sql - - \previouspage Presenting Data in a Table View - \contentspage SQL Programming - - Using the SQL models described above, the contents of a database can - be presented to other model/view components. For some applications, - it is sufficient to present this data using a standard item view, - such as QTableView. However, users of record-based applications often - require a form-based user interface in which data from a specific - row or column in a database table is used to populate editor widgets - on a form. - - Such data-aware forms can be created with the QDataWidgetMapper class, - a generic model/view component that is used to map data from a model - to specific widgets in a user interface. - - QDataWidgetMapper operates on a specific database table, mapping items - in the table on a row-by-row or column-by-column basis. As a result, - using QDataWidgetMapper with a SQL model is as simple as using it with - any other table model. - - \image qdatawidgetmapper-simple.png - - The \l{sql/books}{Books} example shows how information can - be presented for easy access by using QDataWidgetMapper and a set of - simple input widgets. -*/ diff --git a/doc/src/sql/qtsql.qdoc b/doc/src/sql/qtsql.qdoc new file mode 100644 index 0000000000..fb05985874 --- /dev/null +++ b/doc/src/sql/qtsql.qdoc @@ -0,0 +1,18 @@ +/*! + \module QtSql + \title QtSql Module + \ingroup modules + + To include the definitions of the module's classes, use the + following directive: + + \snippet doc/src/snippets/code/doc_src_qtsql.cpp 0 + + To link against the module, add this line to your \l qmake \c + .pro file: + + \snippet doc/src/snippets/code/doc_src_qtsql.pro 1 + + See the \l{SQL Programming} guide for information about using this + module in your applications. +*/ diff --git a/doc/src/sql/sql-programming/qsqldatatype-table.qdoc b/doc/src/sql/sql-programming/qsqldatatype-table.qdoc new file mode 100644 index 0000000000..e5a9bf5c5a --- /dev/null +++ b/doc/src/sql/sql-programming/qsqldatatype-table.qdoc @@ -0,0 +1,570 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page sql-types.html + \title Data Types for Qt-supported Database Systems + \brief Recommended data types for database systems + + \ingroup qt-sql + + \section1 Recommended Data Types for Qt-Supported Database Systems + + This table shows the recommended data types for extracting data from + the databases supported in Qt. Note that types used in Qt are not + necessarily valid as input types to a specific database + system. e.g., A double might work perfectly as input for floating + point records in a particular database, but not necessarily as a + storage format for output from that database, because it would be + stored with 64-bit precision in C++. + + \tableofcontents + + \section2 IBM DB2 Data Types + + \table 90% + \header + \o IBM DB2 data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL + \o 32-bit Single-precision floating point + \o By default mapping to QString + \row + \o DOUBLE PRECISION + \o 64-bit Double-precision floating point + \o By default mapping to QString + \row + \o FLOAT + \o 64-bit Double-precision floating point + \o By default mapping to QString + \row + \o CHAR + \o Fixed-length, null-terminated character string + \o Mapped to QString + \row + \o VARCHAR + \o Null-terminated varying length string + \o Mapped to QString + \row + \o LONG VARCHAR + \o Not null-terminated varying length character string + \o Mapped to QString + \row + \o BLOB + \o Not null-terminated varying binary string with 4-byte string + length indicator + \o Mapped to QByteArray + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o DATE + \o Null-terminated character string of the following format: + yyyy-mm-dd + \o Mapped to QDate + \row + \o TIME + \o Null-terminated character string of the following format: hh.mm.ss + \o Mapped to QTime + \row + \o TIMESTAMP + \o Null-terminated character string of the following format: yyyy-mm-dd-hh.mm.ss.nnnnnn + \o Mapped to QDateTime + \endtable + + \section2 Borland InterBase Data Types + + \table 90% + \header + \o Borland InterBase data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BOOLEAN + \o Boolean + \o bool + \row + \o TINYINT + \o 8 bit signed integer + \o typedef qint8 + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT LONG + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL FLOAT + \o 32-bit floating point + \o By default mapping to QString + \row + \o FLOAT + \o 64-bit floating point + \o By default mapping to QString + \row + \o DOUBLE + \o 64-bit floating point + \o By default mapping to QString + \row + \o DOUBLE PRECISION + \o 64-bit Double-precision floating point + \o By default mapping to QString + \row + \o VARCHAR STRING + \o Character string, Unicode + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o DATE + \o Displays date. Format: 'yyyy-mm-dd' + \o Mapped to QDate + \row + \o TIME + \o Displays time. Format is 'hh:mm:ss' in 24-hour format + \o Mapped to QTime + \row + \o TIMESTAMP + \o Displays a timestamp. Format is 'yyyy-mm-dd hh:mm:ss' + \o Mapped to QDateTime + \endtable + + \section2 MySQL Data Types + + \table 90% + \header + \o MySQL data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o TINYINT + \o 8 bit signed integer + \o typedef qint8 + \row + \o TINYINT UNSIGNED + \o 8 bit unsigned integer + \o typedef quint8 + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o SMALLINT UNSIGNED + \o 16-bit unsigned integer + \o typedef quint16 + \row + \o INT + \o 32-bit signed integer + \o typedef qint32 + \row + \o INT UNSIGNED + \o 32-bit unsigned integer + \o typedef quint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o FLOAT + \o 32-bit Floating Point + \o By default mapping to QString + \row + \o DOUBLE + \o 64-bit Floating Point + \o By default mapping to QString + \row + \o CHAR + \o Character string + \o Mapped to QString + \row + \o VARCHAR + \o Character string + \o Mapped to QString + \row + \o TINYTEXT + \o Character string + \o Mapped to QString + \row + \o TEXT + \o Character string + \o Mapped to QString + \row + \o MEDIUMTEXT + \o Character string + \o Mapped to QString + \row + \o LONGTEXT + \o Character string + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o all BLOB types + \o BLOB + \o Mapped to QByteArray + \row + \o DATE + \o Date without Time + \o Mapped to QDate + \row + \o DATETIME + \o Date and Time + \o Mapped to QDateTime + \row + \o TIMESTAMP + \o Date and Time + \o Mapped to QDateTime + \row + \o TIME + \o Time + \o Mapped to QTime + \row + \o YEAR + \o Year (int) + \o Mapped to QDateTime + \row + \o ENUM + \o Enumeration of Value Set + \o Mapped to QString + \endtable + + \section2 Oracle Call Interface Data Types + + \table 90% + \header + \o Oracle Call Interface data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o NUMBER + \o FLOAT, DOUBLE, PRECISIONc REAL + \o By default mapping to QString + \row + \o NUMBER(38) + \o INTEGER INT SMALLINT + \o typedef qint8/16/32/64 + \row + \o NUMBER(p,s) + \o NUMERIC(p,s) DECIMAL(p,s)a + \o By default mapping to QString + \row + \o NVARCHAR2(n) + \o Character string (NATIONAL CHARACTER VARYING(n) NATIONAL + CHAR VARYING(n) NCHAR VARYING(n)) + \o Mapped to QString + \row + \o NCHAR(n) + \o Character string (NATIONAL CHARACTER(n) NATIONAL CHAR(n) + NCHAR(n)) + \o Mapped to QString + \row + \o CHAR(n) + \o Character string (CHARACTER(n) CHAR(n)) + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o BLOB + \o A binary large object + \o Mapped to QByteArray + \row + \o TIMESTAMP + \o Year, month, and day values of date, as well as hour, minute, + and second values of time + \o Mapped to QDateTime + \endtable + + \section2 ODBC Data Types + + \table 90% + \header + \o ODBC data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BIT + \o Boolean + \o BOOL + \row + \o TINYINT + \o 8 bit integer + \o typedef qint8 + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL + \o 32-bit Single-precision floating point + \o By default mapping to QString + \row + \o FLOAT + \o 64-bit Double floating point + \o By default mapping to QString + \row + \o DOUBLE + \o 64-bit Double floating point + \o By default mapping to QString + \row + \o CHAR + \o Character string + \o Mapped to QString + \row + \o VARCHAR + \o Character string + \o Mapped to QString + \row + \o LONGVARCHAR + \o Character string + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o DATE + \o Character string + \o Mapped to QDate + \row + \o TIME + \o Character Time, Character string + \o Mapped to QTime + \row + \o TIMESTAMP + \o Character Time, Character string + \o Mapped to QDateTime + \endtable + + \section2 PostgreSQL Data Types + + \table 90% + \header + \o PostgreSQL data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BOOLEAN + \o Boolean + \o bool + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL + \o 32-bit variable-precision floating point + \o By default mapping to QString + \row + \o DOUBLE PRECISION + \o 64-bit variable-precision floating point + \o By default mapping to QString + \row + \o DECIMAL VARIABLE + \o user-specified precision, exact + \o Mapped to QString + \row + \o NUMERIC VARIABLE + \o user-specified precision, exact + \o Mapped to QString + \row + \o VARCHAR + \o variable-length character string + \o Mapped to QString + \row + \o CHARACTER + \o Character string of fixed-length + \o Mapped to QString + \row + \o TEXT + \o Character string of variable-length + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o TIMESTAMP + \o 8 bytes, both date and time + \o Mapped to QDateTime + \row + \o TIMESTAMP + \o 8 bytes, both date and time, with time zone + \o Mapped to QDateTime + \row + \o DATE + \o 4 bytes, dates only + \o Mapped to QDate + \row + \o TIME + \o 8 bytes, times of day only 00:00:00.00 - 23:59:59.99 + \o Mapped to QTime + \row + \o TIME + \o 12 bytes times of day only, with time zone 00:00:00.00+12 + \o Mapped to QDateTime + \endtable + + \section2 QSQLITE SQLite version 3 Data Types + + \table 90% + \header + \o QSQLITE SQLite version 3 data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o NULL + \o NULL value. + \o NULL + \row + \o INTEGER + \o Signed integer, stored in 8, 16, 24, 32, 48, or 64-bits + depending on the magnitude of the value. + \o typedef qint8/16/32/64 + \row + \o REAL + \o 64-bit floating point value. + \o By default mapping to QString + \row + \o TEXT + \o Character string (UTF-8, UTF-16BE or UTF-16-LE). + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o BLOB + \o The value is a BLOB of data, stored exactly as it was input. + \o Mapped to QByteArray + \endtable + + \section2 Sybase Adaptive Server Data Types + + \table 90% + \header + \o Sybase Adaptive Server data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BINARY + \o Describes a fixed-length binary value up to 255 bytes in size. + \o Mapped to QByteArray + \row + \o CHAR + \o Character String + \o Mapped to QString + \row + \o DATETIME + \o Date and time. Range: 1753-01-01 00:00:00 through 9999-12-31 23:59:59. + \o Mapped to QDateTime + \row + \o NCHAR + \o Character String of fixed length + \o Mapped to QString + \row + \o NVARACHAR + \o Character String of variable length + \o Mapped to QString + \row + \o VARCHAR + \o Character String of fixed length + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o TIMESTAMP + \o A unique number within a database + \o Mapped to QString + \row + \o SMALLDATETIME + \o Date and time. Range: 1900-01-01 00:00 through 2079-12-31 23:59 + \o Mapped to QDateTime + \row + \o UNICHAR + \o Character String of fixed length.(Unicode) + \o Mapped to QString + \row + \o UNIVARCHAR + \o Character String of variable length.(Unicode) + \o Mapped to QString + \row + \o VARBINARY + \o Describes a variable-length binary value up to 255 bytes in size + \o Mapped to QByteArray + \endtable + + \section2 SQLite Version 2 + + SQLite version 2 is "typeless". This means that you can store any kind of + data you want in any column of any table, regardless of the declared + data type of that column. We recommend that you map the data to QString. +*/ diff --git a/doc/src/sql/sql-programming/sql-driver.qdoc b/doc/src/sql/sql-programming/sql-driver.qdoc new file mode 100644 index 0000000000..40c7c6a23c --- /dev/null +++ b/doc/src/sql/sql-programming/sql-driver.qdoc @@ -0,0 +1,828 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page sql-driver.html + \title SQL Database Drivers + \brief How to configure and install QtSql drivers for supported databases. + + \ingroup qt-sql + + The QtSql module uses driver \l{How to Create Qt + Plugins}{plugins} to communicate with the different database + APIs. Since Qt's SQL Module API is database-independent, all + database-specific code is contained within these drivers. Several + drivers are supplied with Qt and other drivers can be added. The + driver source code is supplied and can be used as a model for + \l{#development}{writing your own drivers}. + + \tableofcontents + + \section1 Supported Databases + + The table below lists the drivers included with Qt. Due to + license incompatibilities with the GPL, not all of the plugins + are provided with Open Source Versions of Qt. + + \table + \header \o Driver name \o DBMS + \row \o \link #QDB2 QDB2\endlink \o IBM DB2 (version 7.1 and above) + \row \o \link #QIBASE QIBASE\endlink \o Borland InterBase + \row \o \link #QMYSQL QMYSQL\endlink \o MySQL + \row \o \link #QOCI QOCI\endlink \o Oracle Call Interface Driver + \row \o \link #QODBC QODBC\endlink + \o Open Database Connectivity (ODBC) - Microsoft SQL Server and other + ODBC-compliant databases + \row \o \link #QPSQL QPSQL\endlink \o PostgreSQL (versions 7.3 and above) + \row \o \link #QSQLITE2 QSQLITE2\endlink \o SQLite version 2 + \row \o \link #QSQLITE QSQLITE\endlink \o SQLite version 3 + \row \o \link #QTDS QTDS\endlink \o Sybase Adaptive Server \note obsolete from Qt 4.7 + \endtable + + SQLite is the in-process database system with the best test coverage + and support on all platforms. Oracle via OCI, and PostreSQL and MySQL + through either ODBC or a native driver are well-tested on Windows and + Linux. The completeness of the support for other systems depends on the + availability and quality of client libraries. + + \bold{Note:} To build a driver plugin you need to have the appropriate + client library for your Database Management System (DBMS). This provides + access to the API exposed by the DBMS, and is typically shipped with it. + Most installation programs also allow you to install "development + libraries", and these are what you need. These libraries are responsible + for the low-level communication with the DBMS. + + \target building + \section1 Building the Drivers Using Configure + + On Unix and Mac OS X, the Qt \c configure script tries to + automatically detect the available client libraries on your + machine. Run \c{configure -help} to see what drivers can be + built. You should get an output similar to this: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 0 + + The \c configure script cannot detect the neccessary libraries + and include files if they are not in the standard paths, so it + may be necessary to specify these paths using the \c -I and \c -L + command-line options. For example, if your MySQL include files + are installed in \c /usr/local/mysql (or in \c{C:\mysql\include} + on Windows), then pass the following parameter to configure: \c + -I/usr/local/mysql (or \c{-I C:\mysql\include} for Windows). + + On Windows the \c -I parameter doesn't accept spaces in + filenames, so use the 8.3 name instead; for example, use + \c{C:\progra~1\mysql} instead of \c{C:\Program Files\mysql}. + + Use the \c{-qt-sql-} parameter to build the database driver + statically into your Qt library or \c{-plugin-sql-} to build + the driver as a plugin. Look at the sections that follow for + additional information about required libraries. + + \target buildingmanually + \section1 Building the Plugins Manually + + \target QMYSQL + \section2 QMYSQL for MySQL 4 and higher + + \section3 QMYSQL Stored Procedure Support + + MySQL 5 introduces stored procedure support at the SQL level, but no + API to control IN, OUT and INOUT parameters. Therefore, parameters + have to be set and read using SQL commands instead of QSqlQuery::bindValue(). + + Example stored procedure: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 1 + + Source code to access the OUT values: + + \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 2 + + \bold{Note:} \c{@outval1} and \c{@outval2} are variables local to the current + connection and will not be affected by queries sent from another host + or connection. + + \section3 Embedded MySQL Server + + The MySQL embedded server is a drop-in replacement for the normal + client library. With the embedded MySQL server, a MySQL server is + not required to use MySQL functionality. + + To use the embedded MySQL server, simply link the Qt plugin to \c + libmysqld instead of libmysqlclient. This can be done by replacing + \c -lmysqlclient_r by \c -lmysqld in the \c qmake command in the + section below. + + Please refer to the MySQL documentation, chapter "libmysqld, the Embedded + MySQL Server Library" for more information about the MySQL embedded server. + + \section3 How to Build the QMYSQL Plugin on Unix and Mac OS X + + You need the MySQL header files and as well as the shared library + \c{libmysqlclient.so}. Depending on your Linux distribution you may + need to install a package which is usually called "mysql-devel". + + Tell \l qmake where to find the MySQL header files and shared + libraries (here it is assumed that MySQL is installed in + \c{/usr/local}) and run \c{make}: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 3 + + After installing Qt, as described in the \l{Installing Qt for X11 + Platforms} document, you also need to install the plugin in the + standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 4 + + \section3 How to Build the QMYSQL Plugin on Windows + + You need to get the MySQL installation files. Run \c SETUP.EXE and + choose "Custom Install". Install the "Libs & Include Files" Module. + Build the plugin as follows (here it is assumed that MySQL is + installed in \c{C:\MySQL}): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 5 + + If you are not using a Microsoft compiler, replace \c nmake with \c + make in the line above. + + \note This database plugin is not supported for Windows CE. + + \note Including \c{"-o Makefile"} as an argument to \l qmake to + tell it where to build the makefile can cause the plugin to be + built in release mode only. If you are expecting a debug version + to be built as well, don't use the \c{"-o Makefile"} option. + + \section3 How to build the MySQL driver for MinGW users + + The following steps have been used successfully for WinXP SP3. In + this example, Qt 4.6.2 is shown. + + \list + + \o Download the following components: + \list + \o \c{MinGW-5.1.6.exe} + \o \c{mingw-utils-0.3.tar.gz} + \o Qt sources, e.g. \c{qt-everywhere-opensource-src-4.6.2.zip} + \o \c{mysql-5.1.35-win32.msi} + \endlist + + \o Install \c{MinGW-5.1.6.exe} in, e.g. \c{C:\MinGW}. + + \o Extract \c{mingw-utils-0.3.tar.gz} into, e.g. \c{C:\MinGW}. + + \o Add the path for \c{MinGW-5.1.6.exe} to your \c{PATH} variable, + e.g. \c{C:\MinGW\bin;} + + \o Extract the Qt sources, (\c{qt-everywhere-opensource-src-4.6.2.zip}), + into, e.g. \c{C:\Qt}. + + \o Add the path for the eventual Qt binary to your \c{PATH} variable, + e.g. \c{C:\Qt\4.6.2\bin;}. + + \o Install MySQL (\c{mysql-5.1.35-win32.msi}), customizing the + components. Select only the headers and libraries. Install in, + e.g. \c{C:\MySQL\MySQL51}. + + \o Open the DOS prompt, go to \c{C:\MySQL\MySQL51\lib\opt}, and run + the following commands: + \list + \o \c{reimp -d libmysql.lib} + \o \c{dlltool -k -d libmysql.def -l libmysql.a} + \endlist + + \o Open the DOS prompt, go to \c{C:\Qt\4.6.2} and run the following commands: + \list + \o \c{configure.exe -debug-and-release -platform win32-g++ -qt-sql-mysql + -l mysql -I C:\MySQL\MySQL51\include -L C:\MySQL\MySQL51\lib\opt} + \o \c{mingw32-make sub-src} + \endlist + This step takes a long time. + + \o Open the DOS prompt, go to + \c{C:\Qt\4.6.2\src\plugins\sqldrivers\mysql} and run the + following command: + \list + \o \c{qmake "INCLUDEPATH+=C:\MySQL\MySQL51\include" "LIBS+=-L. mysql" mysql.pro} + \endlist + + \o Now the following libraries are ready in \c{C:\Qt\4.6.2\plugins\sqldrivers}. + \list + \o \c{libqsqlmysql4.a} + \o \c{libqsqlmysqld4.a} + \o \c{qsqlmysql4.dll} + \o \c{qsqlmysqld4.dll} + \endlist + To use the SDK and QtCreator directly, copy these libraries to + your \c{C:\Qt\...\qt\plugins\sqldrivers\}, and copy + \c{C:\MySQL\MySQL51\lib\opt\libmysql.dll} to your \c{C:\Qt\...\qt\bin\}. + + \endlist + + \target QOCI + \section2 QOCI for the Oracle Call Interface (OCI) + + \section3 General Information about the OCI plugin + + The Qt OCI plugin supports Oracle 9i, 10g and higher. After + connecting to the Oracle server, the plugin will auto-detect the + database version and enable features accordingly. + + It's possible to connect to a Oracle database without a tnsnames.ora file. + This requires that the database SID is passed to the driver as the database + name and that a hostname is given. + + \section3 OCI User Authentication + + The Qt OCI plugin supports authentication using + external credentials (OCI_CRED_EXT). Usually, this means that the database + server will use the user authentication provided by the operating system + instead of its own authentication mechanism. + + Leave the username and password empty when opening a connection with + QSqlDatabase to use the external credentials authentication. + + \section3 OCI BLOB/LOB Support + + Binary Large Objects (BLOBs) can be read and written, but be aware + that this process may require a lot of memory. You should use a forward + only query to select LOB fields (see QSqlQuery::setForwardOnly()). + + Inserting BLOBs should be done using either a prepared query where the + BLOBs are bound to placeholders or QSqlTableModel, which uses a prepared + query to do this internally. + + \section3 How to Build the OCI Plugin on Unix and Mac OS X + + For Oracle 10g, all you need is the "Instant Client Package - Basic" and + "Instant Client Package - SDK". For Oracle prior to 10g, you require + the standard Oracle client and the SDK packages. + + Oracle library files required to build the driver: + + \list + \i \c libclntsh.so (all versions) + \i \c libwtc9.so (only Oracle 9) + \endlist + + Tell \c qmake where to find the Oracle header files and shared + libraries and run make: + + For Oracle version 9: + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 6 + + For Oracle version 10, we assume that you installed the RPM packages of the + Instant Client Package SDK (you need to adjust the version number accordingly): + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 7 + + \bold{Note:} If you are using the Oracle Instant Client package, + you will need to set LD_LIBRARY_PATH when building the OCI SQL plugin + and when running an applicaiton that uses the OCI SQL plugin. You can + avoid this requirement by setting and RPATH and listing all of the + libraries to link to. Here is an example: + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 32 + + If you wish to build the OCI plugin manually with this method the procedure looks like this: + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 33 + + \section3 How to Build the OCI Plugin on Windows + + Choosing the option "Programmer" in the Oracle Client Installer from + the Oracle Client Installation CD is generally sufficient to build the + plugin. For some versions of Oracle Client, you may also need to select + the "Call Interface (OCI)" option if it is available. + + Build the plugin as follows (here it is assumed that Oracle Client is + installed in \c{C:\oracle}): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 8 + + If you are not using a Microsoft compiler, replace \c nmake with \c + make in the line above. + + When you run your application you will also need to add the \c oci.dll + path to your \c PATH environment variable: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 9 + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QODBC + \section2 QODBC for Open Database Connectivity (ODBC) + + \section3 General Information about the ODBC plugin + + ODBC is a general interface that allows you to connect to multiple + DBMSs using a common interface. The QODBC driver allows you to connect + to an ODBC driver manager and access the available data sources. Note + that you also need to install and configure ODBC drivers for the ODBC + driver manager that is installed on your system. The QODBC plugin + then allows you to use these data sources in your Qt applications. + + \bold{Note:} You should use native drivers in preference to the ODBC + driver where they are available. ODBC support can be used as a fallback + for compliant databases if no native drivers are available. + + On Windows an ODBC driver manager should be installed by default. + For Unix systems there are some implementations which must be + installed first. Note that every client that uses your application is + required to have an ODBC driver manager installed, otherwise the + QODBC plugin will not work. + + Be aware that when connecting to an ODBC datasource you must pass in + the name of the ODBC datasource to the QSqlDatabase::setDatabaseName() + function rather than the actual database name. + + The QODBC Plugin needs an ODBC compliant driver manager version 2.0 or + later to work. Some ODBC drivers claim to be version 2.0 compliant, + but do not offer all the necessary functionality. The QODBC plugin + therefore checks whether the data source can be used after a + connection has been established and refuses to work if the check + fails. If you don't like this behavior, you can remove the \c{#define + ODBC_CHECK_DRIVER} line from the file \c{qsql_odbc.cpp}. Do this at + your own risk! + + By default, Qt instructs the ODBC driver to behave as an ODBC 2.x + driver. However, for some \e{driver-manager/ODBC 3.x-driver} + combinations (e.g., \e{unixODBC/MaxDB ODBC}), telling the ODBC + driver to behave as a 2.x driver can cause the driver plugin to + have unexpected behavior. To avoid this problem, instruct the ODBC + driver to behave as a 3.x driver by + \l{QSqlDatabase::setConnectOptions()} {setting the connect option} + \c{"SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3"} before you + \l{QSqlDatabase::open()} {open your database connection}. Note + that this will affect multiple aspects of ODBC driver behavior, + e.g., the SQLSTATEs. Before setting this connect option, consult + your ODBC documentation about behavior differences you can expect. + + If you experience very slow access of the ODBC datasource, make sure + that ODBC call tracing is turned off in the ODBC datasource manager. + + Some drivers don't support scrollable cursors. In that case case only + queries in forwardOnly mode can be used successfully. + + \section3 ODBC Stored Procedure Support + + With Microsoft SQL Server the result set returned by a stored + procedure that uses the return statement, or returns multiple result + sets, will be accessible only if you set the query's forward only + mode to \e forward using \l QSqlQuery::setForwardOnly(). + + \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 10 + + \bold{Note:} The value returned by the stored procedure's return statement + is discarded. + + \section3 ODBC Unicode Support + + The QODBC Plugin will use the Unicode API if UNICODE is defined. On + Windows NT based systems, this is the default. Note that the ODBC + driver and the DBMS must also support Unicode. + + Some driver managers and drivers don't support UNICODE. To use the + QODBC plugin with such drivers it has to be compiled with the + Q_ODBC_VERSION_2 defined. + + For the Oracle 9 ODBC driver (Windows), it is neccessary to check + "SQL_WCHAR support" in the ODBC driver manager otherwise Oracle + will convert all Unicode strings to local 8-bit. + + \section3 How to Build the ODBC Plugin on Unix and Mac OS X + + It is recommended that you use unixODBC. You can find the latest + version and ODBC drivers at \l http://www.unixodbc.org. + You need the unixODBC header files and shared libraries. + + Tell \c qmake where to find the unixODBC header files and shared + libraries (here it is assumed that unixODBC is installed in + \c{/usr/local/unixODBC}) and run \c{make}: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 11 + + \section3 How to Build the ODBC Plugin on Windows + + The ODBC header and include files should already be installed in the + right directories. You just have to build the plugin as follows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 12 + + If you are not using a Microsoft compiler, replace \c nmake with \c + make in the line above. + + \bold{Note:} This database plugin is not officially supported for Windows CE. + + \target QPSQL + \section2 QPSQL for PostgreSQL (Version 7.3 and Above) + + \section3 General Information about the QPSQL driver + + The QPSQL driver supports version 7.3 and higher of the PostgreSQL server. + We recommend that you use a client library from version 7.3.15, 7.4.13, + 8.0.8, 8.1.4 or more recent as these versions contain security fixes, and + as the QPSQL driver might not build with older versions of the client + library depending on your platform. + + For more information about PostgreSQL visit \l http://www.postgresql.org. + + \section3 QPSQL Unicode Support + + The QPSQL driver automatically detects whether the PostgreSQL + database you are connecting to supports Unicode or not. Unicode is + automatically used if the server supports it. Note that the driver + only supports the UTF-8 encoding. If your database uses any other + encoding, the server must be compiled with Unicode conversion + support. + + Unicode support was introduced in PostgreSQL version 7.1 and it will + only work if both the server and the client library have been compiled + with multibyte support. More information about how to set up a + multibyte enabled PostgreSQL server can be found in the PostgreSQL + Administrator Guide, Chapter 5. + + \section3 QPSQL BLOB Support + + Binary Large Objects are supported through the \c BYTEA field type in + PostgreSQL server versions >= 7.1. + + \section3 How to Build the QPSQL Plugin on Unix and Mac OS X + + You need the PostgreSQL client library and headers installed. + + To make \c qmake find the PostgreSQL header files and shared + libraries, run \c qmake the following way (assuming that the + PostgreSQL client is installed in \c{/usr}): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 13 + + After installing Qt, as described in the \l{Installing Qt for X11 Platforms} document, + you also need to install the plugin in the standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 14 + + \section3 How to Build the QPSQL Plugin on Windows + + Install the appropriate PostgreSQL developer libraries for your + compiler. Assuming that PostgreSQL was installed in \c{C:\psql}, + build the plugin as follows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 15 + + Users of MinGW may wish to consult the following online document: + \l{Compiling PostgreSQL On Native Win32 FAQ}. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QTDS + \section2 QTDS for Sybase Adaptive Server + + \note TDS is no longer used by MS Sql Server, and is superceded by + \l{QODBC}{ODBC}. QTDS is obsolete from Qt 4.7. + + \section3 General Information about QTDS + + It is not possible to set the port with QSqlDatabase::setPort() due to limitations in the + Sybase client library. Refer to the Sybase documentation for information on how to set up + a Sybase client configuration file to enable connections to databases on non-default ports. + + \section3 How to Build the QTDS Plugin on Unix and Mac OS X + + Under Unix, two libraries are available which support the TDS protocol: + + \list + \i FreeTDS, a free implementation of the TDS protocol + (\l{http://www.freetds.org}). Note that FreeTDS is not yet stable, + so some functionality may not work as expected. + + \i Sybase Open Client, available from \l{http://www.sybase.com}. + Note for Linux users: Get the Open Client RPM from + \l{http://linux.sybase.com}. + \endlist + + Regardless of which library you use, the shared object file + \c{libsybdb.so} is needed. Set the \c SYBASE environment variable to + point to the directory where you installed the client library and + execute \c{qmake}: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 16 + + \section3 How to Build the QDTS Plugin on Windows + + You can either use the DB-Library supplied by Microsoft or the Sybase + Open Client (\l{http://www.sybase.com}). You must include \c + NTWDBLIB.LIB to build the plugin: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 17 + + By default the Microsoft library is used on Windows, if you want to + force the use of the Sybase Open Client, you must define \c + Q_USE_SYBASE in \c{%QTDIR%\src\sql\drivers\tds\qsql_tds.cpp}. If you + are not using a Microsoft compiler, replace \c nmake with \c make in + the line above. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QDB2 + \section2 QDB2 for IBM DB2 (Version 7.1 and Above) + + \section3 General Information about QDB2 + + The Qt DB2 plugin makes it possible to access IBM DB2 databases. It + has been tested with IBM DB2 v7.1 and 7.2. You must install the IBM + DB2 development client library, which contains the header and library + files necessary for compiling the QDB2 plugin. + + The QDB2 driver supports prepared queries, reading/writing of Unicode + strings and reading/writing of BLOBs. + + We suggest using a forward-only query when calling stored procedures + in DB2 (see QSqlQuery::setForwardOnly()). + + \section3 How to Build the QDB2 Plugin on Unix and Mac OS X + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 18 + + After installing Qt, as described in the \l{Installing Qt for X11 Platforms} document, + you also need to install the plugin in the standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 19 + + \section3 How to Build the QDB2 Plugin on Windows + + The DB2 header and include files should already be installed in the + right directories. You just have to build the plugin as follows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 20 + + If you are not using a Microsoft compiler, replace \c nmake + with \c make in the line above. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QSQLITE2 + \section2 QSQLITE2 for SQLite Version 2 + + The Qt SQLite 2 plugin is offered for compatibility. Whenever + possible, use the \l{#QSQLITE}{version 3 plugin} instead. The + build instructions for version 3 apply to version 2 as well. + + \target QSQLITE + \section2 QSQLITE for SQLite (Version 3 and Above) + + \section3 General Information about QSQLITE + + The Qt SQLite plugin makes it possible to access SQLite + databases. SQLite is an in-process database, which means that it + is not necessary to have a database server. SQLite operates on a + single file, which must be set as the database name when opening + a connection. If the file does not exist, SQLite will try to + create it. SQLite also supports in-memory databases, simply pass + ":memory:" as the database name. + + SQLite has some restrictions regarding multiple users and + multiple transactions. If you try to read/write on a resource from different + transactions, your application might freeze until one transaction commits + or rolls back. The Qt SQLite driver will retry to write to a locked resource + until it runs into a timeout (see \c{QSQLITE_BUSY_TIMEOUT} + at QSqlDatabase::setConnectOptions()). + + In SQLite any column, with the exception of an INTEGER PRIMARY KEY column, + may be used to store any type of value. For instance, a column declared as + INTEGER may contain an integer value in one row and a text value in the + next. This is due to SQLite associating the type of a value with the value + itself rather than with the column it is stored in. A consequence of this + is that the type returned by QSqlField::type() only indicates the field's + recommended type. No assumption of the actual type should be made from + this and the type of the individual values should be checked. + + The driver is locked for updates while a select is executed. This + may cause problems when using QSqlTableModel because Qt's item views + fetch data as needed (with QSqlQuery::fetchMore() in the case of + QSqlTableModel). + + You can find information about SQLite on \l{http://www.sqlite.org}. + + \section3 How to Build the QSQLITE Plugin + + SQLite version 3 is included as a third-party library within Qt. + It can be built by passing the following parameters to the + configure script: \c{-plugin-sql-sqlite} (build as a plugin) or + \c{-qt-sql-sqlite} (linked directly into the Qt library). + + If you don't want to use the SQLite library included with Qt, you + can build it manually (replace \c $SQLITE by the directory where + SQLite resides): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 21 + + After installing Qt, as described in the \l{Installing Qt for X11 Platforms} document, + you also need to install the plugin in the standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 22 + + On Windows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 23 + + \section3 QSQLITE File Format Compatibility + + SQLite minor releases sometimes break file format forward compatibility. + For example, SQLite 3.3 can read database files created with SQLite 3.2, + but databases created with SQLite 3.3 cannot be read by SQLite 3.2. + Please refer to the SQLite documentation and change logs for information about + file format compatibility between versions. + + Qt minor releases usually follow the SQLite minor releases, while Qt patch releases + follow SQLite patch releases. Patch releases are therefore both backward and forward + compatible. + + To force SQLite to use a specific file format, it is neccessary to build and + ship your own database plugin with your own SQLite library as illustrated above. + Some versions of SQLite can be forced to write a specific file format by setting + the \c{SQLITE_DEFAULT_FILE_FORMAT} define when building SQLite. + + \target QIBASE + \section2 QIBASE for Borland InterBase + + \section3 General Information about QIBASE + + The Qt InterBase plugin makes it possible to access the InterBase and + Firebird databases. InterBase can either be used as a client/server or + without a server in which case it operates on local files. The + database file must exist before a connection can be established. Firebird + must be used with a server configuration. + + Note that InterBase requires you to specify the full path to the + database file, no matter whether it is stored locally or on another + server. + + \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 24 + + You need the InterBase/Firebird development headers and libraries + to build this plugin. + + Due to license incompatibilities with the GPL, users of the Qt Open Source + Edition are not allowed to link this plugin to the commercial editions of + InterBase. Please use Firebird or the free edition of InterBase. + + \section3 QIBASE Unicode Support and Text Encoding + + By default the driver connects to the database using UNICODE_FSS. This can + be overridden by setting the ISC_DPB_LC_CTYPE parameter with + QSqlDatabase::setConnectOptions() before opening the connection. + + \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 25 + + If Qt doesn't support the given text encoding the driver will issue a + warning message and connect to the database using UNICODE_FSS. + + Note that if the text encoding set when connecting to the database is + not the same as in the database, problems with transliteration might arise. + + \section3 QIBASE Stored procedures + + InterBase/Firebird return OUT values as result set, so when calling stored + procedure, only IN values need to be bound via QSqlQuery::bindValue(). The + RETURN/OUT values can be retrieved via QSqlQuery::value(). Example: + + \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 26 + + \section3 How to Build the QIBASE Plugin on Unix and Mac OS X + + The following assumes InterBase or Firebird is installed in + \c{/opt/interbase}: + + If you are using InterBase: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 27 + + If you are using Firebird, the Firebird library has to be set explicitly: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 28 + + \section3 How to Build the QIBASE Plugin on Windows + + The following assumes InterBase or Firebird is installed in + \c{C:\interbase}: + + If you are using InterBase: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 29 + + If you are using Firebird, the Firebird library has to be set explicitely: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 30 + + If you are not using a Microsoft compiler, replace \c nmake + with \c make in the line above. + + Note that \c{C:\interbase\bin} must be in the \c PATH. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target troubleshooting + \section1 Troubleshooting + + You should always use client libraries that have been compiled with + the same compiler as you are using for your project. If you cannot get + a source distibution to compile the client libraries yourself, you + must make sure that the pre-compiled library is compatible with + your compiler, otherwise you will get a lot of "undefined symbols" + errors. Some compilers have tools to convert libraries, e.g. Borland + ships the tool \c{COFF2OMF.EXE} to convert libraries that have been + generated with Microsoft Visual C++. + + If the compilation of a plugin succeeds but it cannot be loaded, + make sure that the following requirements are met: + + \list + \i Ensure that you are using a shared Qt library; you cannot use the + plugins with a static build. + \i Ensure that the plugin is in the correct directory. You can use + QApplication::libraryPaths() to determine where Qt looks for plugins. + \i Ensure that the client libraries of the DBMS are available on the + system. On Unix, run the command \c{ldd} and pass the name of the + plugin as parameter, for example \c{ldd libqsqlmysql.so}. You will + get a warning if any of the client libraries couldn't be found. + On Windows, you can use Visual Studio's dependency walker. + \i Compile Qt with \c{QT_DEBUG_COMPONENT} defined to get very verbose + debug output when loading plugins. + \endlist + + Make sure you have followed the guide to \l{Deploying Plugins}. + If you experience plugin load problems and see output like this: + + \snippet doc/src/snippets/code/doc_src_sql-driver.cpp 31 + + the problem is usually that the plugin had the wrong \l{Deploying + Plugins#The Build Key}{build key}. This might require removing an + entry from the \l{Deploying Plugins#The Plugin Cache} {plugin cache}. + + \target development + \section1 How to Write Your Own Database Driver + + QSqlDatabase is responsible for loading and managing database driver + plugins. When a database is added (see QSqlDatabase::addDatabase()), + the appropriate driver plugin is loaded (using QSqlDriverPlugin). + QSqlDatabase relies on the driver plugin to provide interfaces for + QSqlDriver and QSqlResult. + + QSqlDriver is an abstract base class which defines the functionality + of a SQL database driver. This includes functions such as + QSqlDriver::open() and QSqlDriver::close(). QSqlDriver is responsible + for connecting to a database, establish the proper environment, etc. + In addition, QSqlDriver can create QSqlQuery objects appropriate for + the particular database API. QSqlDatabase forwards many of its + function calls directly to QSqlDriver which provides the concrete + implementation. + + QSqlResult is an abstract base class which defines the functionality + of a SQL database query. This includes statements such as \c{SELECT}, + \c{UPDATE}, and \c{ALTER} \c{TABLE}. QSqlResult contains functions + such as QSqlResult::next() and QSqlResult::value(). QSqlResult is + responsible for sending queries to the database, returning result + data, etc. QSqlQuery forwards many of its function calls directly to + QSqlResult which provides the concrete implementation. + + QSqlDriver and QSqlResult are closely connected. When implementing a + Qt SQL driver, both of these classes must to be subclassed and the + abstract virtual methods in each class must be implemented. + + To implement a Qt SQL driver as a plugin (so that it is + recognized and loaded by the Qt library at runtime), the driver + must use the Q_EXPORT_PLUGIN2() macro. Read \l{How to Create Qt + Plugins} for more information on this. You can also check out how + this is done in the SQL plugins that are provided with Qt in + \c{QTDIR/src/plugins/sqldrivers} and \c{QTDIR/src/sql/drivers}. + + The following code can be used as a skeleton for a SQL driver: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 47 + \codeline + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 48 +*/ diff --git a/doc/src/sql/sql-programming/sql-programming.qdoc b/doc/src/sql/sql-programming/sql-programming.qdoc new file mode 100644 index 0000000000..55f97484bb --- /dev/null +++ b/doc/src/sql/sql-programming/sql-programming.qdoc @@ -0,0 +1,609 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group database + \title Database Classes + + \brief Database related classes, e.g. for SQL databases. +*/ + +/*! + \page sql-programming.html + \title SQL Programming + \ingroup qt-sql + \nextpage Connecting to Databases + + \brief Database integration for Qt applications. + + This overview assumes that you have at least a basic knowledge of + SQL. You should be able to understand simple \c SELECT, \c + INSERT, \c UPDATE, and \c DELETE statements. Although the \l + QSqlTableModel class provides an interface to database browsing + and editing that does not require a knowledge of SQL, a basic + understanding of SQL is highly recommended. A standard text + covering SQL databases is \e {An Introduction to Database Systems} + (7th Ed.) by C. J. Date, ISBN 0201385902. + + \section1 Topics: + + \list + \o \l{Database Classes} + \o \l{Connecting to Databases} + \list + \o \l{SQL Database Drivers} + \endlist + \o \l{Executing SQL Statements} + \list + \o \l{Data Types for Qt-supported Database Systems} + \endlist + \o \l{Using the SQL Model Classes} + \o \l{Presenting Data in a Table View} + \o \l{Creating Data-Aware Forms} + \endlist + + \section1 Database Classes + + These classes provide access to SQL databases. + + \annotatedlist database + + The SQL classes are divided into three layers: + + \section2 Driver Layer + + This comprises the classes QSqlDriver, QSqlDriverCreator, + QSqlDriverCreatorBase, QSqlDriverPlugin, and QSqlResult. + + This layer provides the low-level bridge between the specific databases + and the SQL API layer. See \l{SQL Database Drivers} for more information. + + \section2 SQL API Layer + + These classes provide access to databases. Connections + are made using the QSqlDatabase class. Database + interaction is achieved by using the QSqlQuery class. + In addition to QSqlDatabase and QSqlQuery, the SQL API + layer is supported by QSqlError, QSqlField, QSqlIndex, + and QSqlRecord. + + \section2 User Interface Layer + + These classes link the data from a database to data-aware widgets. + They include QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel. + These classes are designed to work with Qt's + \l{Model/View Programming}{model/view framework}. + + Note that to use any of these classes, a QCoreApplication object + must have been instantiated first. +*/ + +/*! + \page sql-connecting.html + \title Connecting to Databases + \ingroup qt-sql + + \contentspage SQL Programming + \previouspage SQL Programming + \nextpage Executing SQL Statements + + To access a database with QSqlQuery or QSqlQueryModel, create and + open one or more database connections. Database connections are + normally identified by connection name, \e{not} by database name. + You can have multiple connections to the same database. + QSqlDatabase also supports the concept of a \e{default} + connection, which is an unnamed connection. When calling QSqlQuery + or QSqlQueryModel member functions that take a connection name + argument, if you don't pass a connection name, the default + connection will be used. Creating a default connection is + convenient when your application only requires one database + connection. + + Note the difference between creating a connection and opening it. + Creating a connection involves creating an instance of class + QSqlDatabase. The connection is not usable until it is opened. The + following snippet shows how to create a \e{default} connection + and then open it: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 26 + + The first line creates the connection object, and the last line + opens it for use. In between, we initialize some connection + information, including the \l{QSqlDatabase::setDatabaseName()} + {database name}, the \l{QSqlDatabase::setHostName()} {host name}, + the \l{QSqlDatabase::setUserName()} {user name}, and the + \l{QSqlDatabase::setPassword()} {password}. In this case, we are + connecting to the MySQL database \c{flightdb} on the host + \c{bigblue}. The \c{"QMYSQL"} argument to + \l{QSqlDatabase::addDatabase()} {addDatabase()} specifies the type + of database driver to use for the connection. The set of database + drivers included with Qt are shown in the table of \l{SQL Database + Drivers#Supported Databases} {supported database drivers}. + + The connection in the snippet will be the \e{default} connection, + because we don't pass the second argument to + \l{QSqlDatabase::addDatabase()} {addDatabase()}, which is the + connection name. For example, here we establish two MySQL database + connections named \c{"first"} and \c{"second"}: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 27 + + After these connections have been initialized, \l{QSqlDatabase::} + {open()} for each one to establish the live connections. If the + \l{QSqlDatabase::} {open()} fails, it returns false. In that case, + call QSqlDatabase::lastError() to get error information. + + Once a connection is established, we can call the static function + QSqlDatabase::database() from anywhere with a connection name to + get a pointer to that database connection. If we don't pass a + connection name, it will return the default connection. For + example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 28 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 29 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 30 + + To remove a database connection, first close the database using + QSqlDatabase::close(), then remove it using the static method + QSqlDatabase::removeDatabase(). +*/ + +/*! + \page sql-sqlstatements.html + \title Executing SQL Statements + \ingroup qt-sql + + \previouspage Connecting to Databases + \contentspage SQL Programming + \nextpage Using the SQL Model Classes + + + The QSqlQuery class provides an interface for executing SQL + statements and navigating through the result set of a query. + + The QSqlQueryModel and QSqlTableModel classes described in the + next section provide a higher-level interface for accessing + databases. If you are unfamiliar with SQL, you might want to skip + directly to the next section (\l{Using the SQL Model Classes}). + + \section2 Executing a Query + + To execute an SQL statement, simply create a QSqlQuery object and + call QSqlQuery::exec() like this: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 31 + + The QSqlQuery constructor accepts an optional QSqlDatabase object + that specifies which database connection to use. In the example + above, we don't specify any connection, so the default connection + is used. + + If an error occurs, \l{QSqlQuery::exec()}{exec()} returns false. + The error is then available as QSqlQuery::lastError(). + + \section2 Navigating the Result Set + + QSqlQuery provides access to the result set one record at a time. + After the call to \l{QSqlQuery::exec()}{exec()}, QSqlQuery's + internal pointer is located one position \e{before} the first + record. We must call QSqlQuery::next() once to advance to the + first record, then \l{QSqlQuery::next()}{next()} again repeatedly + to access the other records, until it returns false. Here's a + typical loop that iterates over all the records in order: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 32 + + The QSqlQuery::value() function returns the value of a field in + the current record. Fields are specified as zero-based indexes. + QSqlQuery::value() returns a QVariant, a type that can hold + various C++ and core Qt data types such as \c int, QString, and + QByteArray. The different database types are automatically mapped + into the closest Qt equivalent. In the code snippet, we call + QVariant::toString() and QVariant::toInt() to convert + variants to QString and \c int. + + For an overview of the recommended types for use with Qt-supported + Databases, please refer to \l{Data Types for Qt-supported Database + Systems} {this table}. + + You can iterate back and forth using QSqlQuery::next(), + QSqlQuery::previous(), QSqlQuery::first(), QSqlQuery::last(), and + QSqlQuery::seek(). The current row index is returned by + QSqlQuery::at(), and the total number of rows in the result set + is avaliable as QSqlQuery::size() for databases that support it. + + To determine whether a database driver supports a given feature, + use QSqlDriver::hasFeature(). In the following example, we call + QSqlQuery::size() to determine the size of a result set of + the underlying database supports that feature; otherwise, we + navigate to the last record and use the query's position to tell + us how many records there are. + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 33 + + If you iterate through a result set only using next() and seek() + with positive values, you can call + QSqlQuery::setForwardOnly(true) before calling exec(). This is an + easy optimization that will speed up the query significantly when + operating on large result sets. + + \section2 Inserting, Updating, and Deleting Records + + QSqlQuery can execute arbitrary SQL statements, not just + \c{SELECT}s. The following example inserts a record into a table + using \c{INSERT}: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 34 + + If you want to insert many records at the same time, it is often + more efficient to separate the query from the actual values being + inserted. This can be done using placeholders. Qt supports two + placeholder syntaxes: named binding and positional binding. + Here's an example of named binding: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 35 + + Here's an example of positional binding: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 36 + + Both syntaxes work with all database drivers provided by Qt. If + the database supports the syntax natively, Qt simply forwards the + query to the DBMS; otherwise, Qt simulates the placeholder syntax + by preprocessing the query. The actual query that ends up being + executed by the DBMS is available as QSqlQuery::executedQuery(). + + When inserting multiple records, you only need to call + QSqlQuery::prepare() once. Then you call + \l{QSqlQuery::bindValue()}{bindValue()} or + \l{QSqlQuery::addBindValue()}{addBindValue()} followed by + \l{QSqlQuery::exec()}{exec()} as many times as necessary. + + Besides performance, one advantage of placeholders is that you + can easily specify arbitrary values without having to worry about + escaping special characters. + + Updating a record is similar to inserting it into a table: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 37 + + You can also use named or positional binding to associate + parameters to actual values. + + Finally, here's an example of a \c DELETE statement: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 38 + + \section2 Transactions + + If the underlying database engine supports transactions, + QSqlDriver::hasFeature(QSqlDriver::Transactions) will return + true. You can use QSqlDatabase::transaction() to initiate a + transaction, followed by the SQL commands you want to execute + within the context of the transaction, and then either + QSqlDatabase::commit() or QSqlDatabase::rollback(). When + using transactions you must start the transaction before you + create your query. + + Example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 39 + + Transactions can be used to ensure that a complex operation is + atomic (for example, looking up a foreign key and creating a + record), or to provide a means of canceling a complex change in + the middle. + + \omit + It would be useful to mention transactions, and the fact that + some databases don't support them. + \endomit +*/ + +/*! + \page sql-model.html + \title Using the SQL Model Classes + \ingroup qt-sql + + \previouspage Executing SQL Statements + \contentspage SQL Programming + \nextpage Presenting Data in a Table View + + In addition to QSqlQuery, Qt offers three higher-level classes + for accessing databases. These classes are QSqlQueryModel, + QSqlTableModel, and QSqlRelationalTableModel. + + \table + \row \o QSqlQueryModel + \o A read-only model based on an arbitrary SQL query. + \row \o QSqlTableModel + \o A read-write model that works on a single table. + \row \o QSqlRelationalTableModel + \o A QSqlTableModel subclass with foreign key support. + \endtable + + These classes derive from QAbstractTableModel (which in turn + inherits from QAbstractItemModel) and make it easy to present + data from a database in an item view class such as QListView and + QTableView. This is explained in detail in the \l{Presenting Data + in a Table View} section. + + Another advantage of using these classes is that it can make your + code easier to adapt to other data sources. For example, if you + use QSqlTableModel and later decide to use XML files to store + data instead of a database, it is essentially just a matter of + replacing one data model with another. + + \section2 The SQL Query Model + + QSqlQueryModel offers a read-only model based on an SQL query. + + Example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 40 + + After setting the query using QSqlQueryModel::setQuery(), you can + use QSqlQueryModel::record(int) to access the individual records. + You can also use QSqlQueryModel::data() and any of the other + functions inherited from QAbstractItemModel. + + There's also a \l{QSqlQueryModel::setQuery()}{setQuery()} + overload that takes a QSqlQuery object and operates on its result + set. This enables you to use any features of QSqlQuery to set up + the query (e.g., prepared queries). + + \section2 The SQL Table Model + + QSqlTableModel offers a read-write model that works on a single + SQL table at a time. + + Example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 41 + + QSqlTableModel is a high-level alternative to QSqlQuery for + navigating and modifying individual SQL tables. It typically + results in less code and requires no knowledge of SQL syntax. + + Use QSqlTableModel::record() to retrieve a row in the table, and + QSqlTableModel::setRecord() to modify the row. For example, the + following code will increase every employee's salary by 10 per + cent: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 42 + + You can also use QSqlTableModel::data() and + QSqlTableModel::setData(), which are inherited from + QAbstractItemModel, to access the data. For example, here's how + to update a record using + \l{QSqlTableModel::setData()}{setData()}: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 43 + + Here's how to insert a row and populate it: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 44 + + Here's how to delete five consecutive rows: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 45 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 46 + + The first argument to QSqlTableModel::removeRows() is the index + of the first row to delete. + + When you're finished changing a record, you should always call + QSqlTableModel::submitAll() to ensure that the changes are + written to the database. + + When and whether you actually \e need to call submitAll() depends + on the table's \l{QSqlTableModel::editStrategy()}{edit strategy}. + The default strategy is QSqlTableModel::OnRowChange, which + specifies that pending changes are applied to the database when + the user selects a different row. Other strategies are + QSqlTableModel::OnManualSubmit (where all changes are cached in + the model until you call submitAll()) and + QSqlTableModel::OnFieldChange (where no changes are cached). + These are mostly useful when QSqlTableModel is used with a view. + + QSqlTableModel::OnFieldChange seems to deliver the promise that + you never need to call submitAll() explicitly. There are two + pitfalls, though: + + \list + \o Without any caching, performance may drop significantly. + \o If you modify a primary key, the record might slip through + your fingers while you are trying to populate it. + \endlist + + \section2 The SQL Relational Table Model + + QSqlRelationalTableModel extends QSqlTableModel to provide + support for foreign keys. A foreign key is a 1-to-1 mapping + between a field in one table and the primary key field of another + table. For example, if a \c book table has a field called \c + authorid that refers to the author table's \c id field, we say + that \c authorid is a foreign key. + + \table + \row \o \inlineimage noforeignkeys.png + \o \inlineimage foreignkeys.png + \endtable + + The screenshot on the left shows a plain QSqlTableModel in a + QTableView. Foreign keys (\c city and \c country) aren't resolved + to human-readable values. The screenshot on the right shows a + QSqlRelationalTableModel, with foreign keys resolved into + human-readable text strings. + + The following code snippet shows how the QSqlRelationalTableModel + was set up: + + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 0 + \codeline + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 1 + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 2 + + See the QSqlRelationalTableModel documentation for details. +*/ + +/*! + \page sql-presenting.html + \title Presenting Data in a Table View + \ingroup qt-sql + + \previouspage Using the SQL Model Classes + \contentspage SQL Programming + \nextpage Creating Data-Aware Forms + + The QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel + classes can be used as a data source for Qt's view classes such + as QListView, QTableView, and QTreeView. In practice, QTableView + is by far the most common choice, because an SQL result set is + essentially a two-dimensional data structure. + + \image relationaltable.png A table view displaying a QSqlTableModel + + The following example creates a view based on an SQL data model: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 17 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 18 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 19 + + If the model is a read-write model (e.g., QSqlTableModel), the + view lets the user edit the fields. You can disable this by + calling + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 20 + + You can use the same model as a data source for multiple views. + If the user edits the model through one of the views, the other + views will reflect the changes immediately. The + \l{sql/tablemodel}{Table Model} example shows how it works. + + View classes display a header at the top to label the columns. To + change the header texts, call + \l{QAbstractItemModel::setHeaderData()}{setHeaderData()} on the + model. The header's labels default to the table's field names. + For example: + + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 3 + + QTableView also has a vertical header on the left with numbers + identifying the rows. If you insert rows programmatically using + QSqlTableModel::insertRows(), the new rows will be marked with an + asterisk (*) until they are submitted using + \l{QSqlTableModel::submitAll()}{submitAll()} or automatically + when the user moves to another record (assuming the + \l{QSqlTableModel::EditStrategy}{edit strategy} is + QSqlTableModel::OnRowChange). + + \image insertrowinmodelview.png Inserting a row in a model + + Likewise, if you remove rows using + \l{QSqlTableModel::removeRows()}{removeRows()}, the rows will be + marked with an exclamation mark (!) until the change is + submitted. + + The items in the view are rendered using a delegate. The default + delegate, QItemDelegate, handles the most common data types (\c + int, QString, QImage, etc.). The delegate is also responsible for + providing editor widgets (e.g., a combobox) when the user starts + editing an item in the view. You can create your own delegates by + subclassing QAbstractItemDelegate or QItemDelegate. See + \l{Model/View Programming} for more information. + + QSqlTableModel is optimized to operate on a single table at a + time. If you need a read-write model that operates on an + arbitrary result set, you can subclass QSqlQueryModel and + reimplement \l{QAbstractItemModel::flags()}{flags()} and + \l{QAbstractItemModel::setData()}{setData()} to make it + read-write. The following two functions make fields 1 and 2 of a + query model editable: + + \snippet examples/sql/querymodel/editablesqlmodel.cpp 0 + \codeline + \snippet examples/sql/querymodel/editablesqlmodel.cpp 1 + + The setFirstName() helper function is defined as follows: + + \snippet examples/sql/querymodel/editablesqlmodel.cpp 2 + + The setLastName() function is similar. See the + \l{sql/querymodel}{Query Model} example for the complete source code. + + Subclassing a model makes it possible to customize it in many + ways: You can provide tooltips for the items, change the + background color, provide calculated values, provide different + values for viewing and editing, handle null values specially, and + more. See \l{Model/View Programming} as well as the \l + QAbstractItemView reference documentation for details. + + If all you need is to resolve a foreign key to a more + human-friendly string, you can use QSqlRelationalTableModel. For + best results, you should also use QSqlRelationalDelegate, a + delegate that provides combobox editors for editing foreign keys. + + \image relationaltable.png Editing a foreign key in a relational table + + The \l{sql/relationaltablemodel}{Relational Table Model} example + illustrates how to use QSqlRelationalTableModel in conjunction with + QSqlRelationalDelegate to provide tables with foreign key + support. +*/ + +/*! + \page sql-forms.html + \title Creating Data-Aware Forms + \ingroup qt-sql + + \previouspage Presenting Data in a Table View + \contentspage SQL Programming + + Using the SQL models described above, the contents of a database can + be presented to other model/view components. For some applications, + it is sufficient to present this data using a standard item view, + such as QTableView. However, users of record-based applications often + require a form-based user interface in which data from a specific + row or column in a database table is used to populate editor widgets + on a form. + + Such data-aware forms can be created with the QDataWidgetMapper class, + a generic model/view component that is used to map data from a model + to specific widgets in a user interface. + + QDataWidgetMapper operates on a specific database table, mapping items + in the table on a row-by-row or column-by-column basis. As a result, + using QDataWidgetMapper with a SQL model is as simple as using it with + any other table model. + + \image qdatawidgetmapper-simple.png + + The \l{sql/books}{Books} example shows how information can + be presented for easy access by using QDataWidgetMapper and a set of + simple input widgets. +*/ diff --git a/doc/src/tutorials/addressbook-fr.qdoc b/doc/src/tutorials/addressbook-fr.qdoc deleted file mode 100644 index 53b3e6fc15..0000000000 --- a/doc/src/tutorials/addressbook-fr.qdoc +++ /dev/null @@ -1,1036 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page tutorials-addressbook-fr.html - - \title Tutoriel "Carnet d'adresses" - \brief Une introduction à la programation d'interface graphique montrant comment construire une application simple avec Qt. - - Ce tutoriel est une introduction à la programmation de GUI (interface utilisateur) - à l'aide des outils fournis par la plateforme multiplate-forme Qt. - - \image addressbook-tutorial-screenshot.png - - Ce tutoriel va nous amener à découvrir quelques technologies fondamentales fournies - par Qt, tel que: - - \list - \o Les Widgets et leur mise en page à l'aide des layouts - \o Les signaux et slots - \o Les structures de données de collections - \o Les entrées/sorties - \endlist - - Si c'est votre premier contact avec Qt, lisez \l{How to Learn Qt}{Comment apprendre Qt} - si ce n'est déjà fait. - - Le code source du tutoriel est distribué avec Qt dans le dossier \c examples/tutorials/addressbook - - Les chapitres du tutoriel: - - \list 1 - \o \l{tutorials/addressbook-fr/part1}{Conception de l'interface utilisateur} - \o \l{tutorials/addressbook-fr/part2}{Ajouter des adresses} - \o \l{tutorials/addressbook-fr/part3}{Navigation entre les éléments} - \o \l{tutorials/addressbook-fr/part4}{éditer et supprimer des adresses} - \o \l{tutorials/addressbook-fr/part5}{Ajout d'une fonction de recherche} - \o \l{tutorials/addressbook-fr/part6}{Sauvegarde et chargement} - \o \l{tutorials/addressbook-fr/part7}{Fonctionnalités avancées} - \endlist - - La petite application que nous développerons ici ne possède pas tous les éléments - des interfaces dernier cri, elle va nous permettre d'utiliser les techniques de base - utilisées dans les applications plus complexes. - - Lorsque vous aurez terminé ce tutoriel, nous vous recommandons de poursuivre avec l'exemple - "\l{mainwindows/application}{Application}", qui présente une interface simple utilisant - les menus et barres d'outils, la barre d'état, etc. - -*/ - -/*! - \page tutorials-addressbook-fr-part1.html - - \example tutorials/addressbook-fr/part1 - \title Carnet d'adresses 1 - Conception de l'interface utilisateur - - La première partie de ce tutoriel traite de la conception d'une interface graphique - (GUI) basique, que l'on utilisera pour l'application Carnet d'adresses. - - La première étape dans la création d'applications graphiques est la conception de - l'interface utilisateur. Dans ce chapitre, nous verrons comment créer les labels - et champs de saisie nécessaires à l'implementation d'un carnet d'adresses de base. - Le résultat attendu est illustré par la capture d'écran ci-dessous. - - \image addressbook-tutorial-part1-screenshot.png - - Nous allons avoir besoin de deux objets QLabel, \c nameLabel et \c addressLabel, - ainsi que deux champs de saisie: un objet QLineEdit, \c nameLine, et un objet - QTextEdit, \c addressText, afin de permettre à l'utilisateur d'entrer le nom d'un - contact et son adresse. Les widgets utilisés ainsi que leur placement sont visibles ci-dessous. - - \image addressbook-tutorial-part1-labeled-screenshot.png - - Trois fichiers sont nécessaires à l'implémentation de ce carnet d'adresses: - - \list - \o \c{addressbook.h} - le fichier de définition (header) pour la classe \c AddressBook, - \o \c{addressbook.cpp} - le fichier source, qui comprend l'implémentation de la classe - \c AddressBook - \o \c{main.cpp} - le fichier qui contient la méthode \c main() , et - une instance de la classe \c AddressBook. - \endlist - - \section1 Programmation en Qt - héritage - - - Lorsque l'on écrit des programmes avec Qt, on a généralement recours à - l'héritage depuis des objets Qt, afin d'y ajouter des fonctionnalités. - C'est l'un des concepts fondamentaux de la création de widgets personnalisés - ou de collections de widgets. Utiliser l'héritage afin de compléter - ou modifier le comportement d'un widget présente les avantages suivants: - - \list - \o La possibilité d'implémenter des méthodes virtuelles et des méthodes - virtuelles pures pour obtenir exactement ce que l'on souhaite, avec la possibilité - d'utiliser l'implémentation de la classe mère si besoin est. - \o Cela permet l'encapsulation partielle de l'interface utilisateur dans une classe, - afin que les autres parties de l'application n'aient pas à se soucier de chacun des - widgets qui forment l'interface utilisateur. - \o La classe fille peut être utilisée pour créer de nombreux widgets personnalisés - dans une même application ou bibliothèque, et le code de la classe fille peut être - réutilisé dans d'autres projets - \endlist - - Comme Qt ne fournit pas de widget standard pour un carnet d'adresses, nous - partirons d'une classe de widget Qt standard et y ajouterons des fonctionnalités. - La classe \c AddressBook crée dans ce tutoriel peut être réutilisée si on a besoin d'un - widget carnet d'adresses basique. - - - \section1 La classe AddressBook - - Le fichier \l{tutorials/addressbook-fr/part1/addressbook.h}{\c addressbook.h} permet de - définir la classe \c AddressBook. - - On commence par définir \c AddressBook comme une classe fille de QWidget et déclarer - un constructeur. On utilise également la macro Q_OBJECT pour indiquer que la classe - exploite les fonctionnalités de signaux et slots offertes par Qt ainsi que - l'internationalisation, bien que nous ne les utilisions pas à ce stade. - - \snippet tutorials/addressbook-fr/part1/addressbook.h class definition - - La classe contient les déclarations de \c nameLine et \c addressText, - les instances privées de QLineEdit et QTextEdit mentionnées précédemment. - Vous verrez, dans les chapitres à venir que les informations contenues - dans \c nameLine et \c addressText sont nécessaires à de nombreuses méthodes - du carnet d'adresses. - - Il n'est pas nécessaire de déclarer les objets QLabel que nous allons utiliser - puisque nous n'aurons pas besoin d'y faire référence après leur création. - La façon dont Qt gère la parenté des objets est traitée dans la section suivante. - - La macro Q_OBJECT implémente des fonctionnalités parmi les plus avancées de Qt. - Pour le moment, il est bon de voir la macro Q_OBJECT comme un raccourci nous - permettant d'utiliser les méthodes \l{QObject::}{tr()} et \l{QObject::}{connect()}. - - Nous en avons maintenant terminé avec le fichier \c addressbook.h et allons - passer à l'implémentation du fichier \c addressbook.cpp. - - \section1 Implémentation de la classe AddressBook - - Le constructeur de la classe \c{AddressBook} prend en paramètre un QWidget, \e parent. - Par convention, on passe ce paramètre au constructeur de la classe mère. - Ce concept de parenté, où un parent peut avoir un ou plusieurs enfants, est utile - pour regrouper les Widgets avec Qt. Par exemple, si vous détruisez le parent, - tous ses enfants seront détruits égalament. - - - \snippet tutorials/addressbook/part1/addressbook.cpp constructor and input fields - - à l'intérieur de ce constructeur, on déclare et instancie deux objets locaux - QLabel, \c nameLabel et \c addressLabel, de même on instancie \c nameLine et - \c addressText. La méthode \l{QObject::tr()}{tr()} renvoie une version traduite - de la chaîne de caractères, si elle existe; dans le cas contraire, elle renvoie - la chaîne elle même. On peut voir cette méthode comme un marqueur \tt{}, permettant de repérer les objets QString à considérer - pour traduire une application. Vous remarquerez, dans les chapitres à venir - comme dans les \l{Qt Examples}{exemples Qt}, qu'elle est utilisée chaque fois - que l'on utilise une chaîne susceptible d'être traduite. - - Lorsque l'on programme avec Qt, il est utile de savoir comment fonctionnent les - agencements ou layouts. Qt fournit trois classes principales de layouts pour - contrôler le placement des widgets: QHBoxLayout, QVBoxLayout et QGridLayout. - - \image addressbook-tutorial-part1-labeled-layout.png - - On utilise un QGridLayout pour positionner nos labels et champs de saisie de manière - structurée. QGridLayout divise l'espace disponible en une grille, et place les - widgets dans les cellules que l'on spécifie par les numéros de ligne et de colonne. - Le diagramme ci-dessus présente les cellules et la position des widgets, et cette - organisation est obtenue à l'aide du code suivant: - - \snippet tutorials/addressbook/part1/addressbook.cpp layout - - On remarque que le label \c AddressLabel est positionné en utilisant Qt::AlignTop - comme argument optionnel. Ceci est destiné à assurer qu'il ne sera pas centré - verticalement dans la cellule (1,0). Pour un aperçu rapide des layouts de Qt, - consultez la section \l{Layout Management}. - - Afin d'installer l'objet layout dans un widget, il faut appeler la méthode - \l{QWidget::setLayout()}{setLayout()} du widget en question: - - \snippet tutorials/addressbook/part1/addressbook.cpp setting the layout - - Enfin, on initialise le titre du widget à "Simple Address Book" - - \section1 Exécution de l'application - - Un fichier séparé, \c main.cpp, est utilisé pour la méthode \c main(). Dans cette - fonction, on crée une instance de QApplication, \c app. QApplication se charge de - des ressources communes à l'ensemble de l'application, tel que les polices de - caractères et le curseur par défaut, ainsi que de l'exécution de la boucle d'évènements. - De ce fait, il y a toujours un objet QApplication dans toute application graphique en Qt. - - \snippet tutorials/addressbook/part1/main.cpp main function - - On construit un nouveau widget \c AddressBook sur la pile et on invoque - sa méthode \l{QWidget::show()}{show()} pour l'afficher. - Cependant, le widget ne sera pas visible tant que la boucle d'évènements - n'aura pas été lancée. On démarre la boucle d'évènements en appelant la - méthode \l{QApplication::}{exec()} de l'application; le résultat renvoyé - par cette méthode est lui même utilisé comme valeur de retour pour la méthode - \c main(). - On comprend maintenant pourquoi \c AddressBook a été créé sur la pile: à la fin - du programme, l'objet sort du scope de la fonction \c main() et tous ses widgets enfants - sont supprimés, assurant ainsi qu'il n'y aura pas de fuites de mémoire. -*/ - -/*! - \page tutorials-addressbook-fr-part2.html - - \example tutorials/addressbook-fr/part2 - \title Carnet d'adresses 2 - Ajouter des adresses - - La prochaine étape pour créer notre carnet d'adresses est d'ajouter un soupçon - d'interactivité. - - \image addressbook-tutorial-part2-add-contact.png - - Nous allons fournir un bouton que l'utilisateur peut - cliquer pour ajouter un nouveau contact. Une structure de données est aussi - nécessaire afin de pouvoir stocker les contacts en mémoire. - - \section1 Définition de la classe AddressBook - - Maintenant que nous avons mis en place les labels et les champs de saisie, - nous ajoutons les boutons pour compléter le processus d'ajout d'un contact. - Cela veut dire que notre fichier \c addressbook.h a maintenant trois - objets QPushButton et trois slots publics correspondant. - - \snippet tutorials/addressbook/part2/addressbook.h slots - - Un slot est une méthode qui répond à un signal. Nous allons - voir ce concept en détail lorsque nous implémenterons la classe \c{AddressBook}. - Pour une explication détaillée du concept de signal et slot, vous pouvez - vous référer au document \l{Signals and Slots}. - - Les trois objets QPushButton \c addButton, \c submitButton et \c cancelButton - sont maintenant inclus dans la déclaration des variables privées, avec - \c nameLine et \c addressText du chapitre précédent. - - \snippet tutorials/addressbook/part2/addressbook.h pushbutton declaration - - Nous avons besoin d'un conteneur pour stocker les contacts du carnet - d'adresses, de façon à pouvoir les énumérer et les afficher. - Un objet QMap, \c contacts, est utilisé pour ça, car il permet de stocker - des paires clé-valeur: le nom du contact est la \e{clé} et l'adresse du contact - est la \e{valeur}. - - \snippet tutorials/addressbook/part2/addressbook.h remaining private variables - - Nous déclarons aussi deux objects QString privés: \c oldName et \c oldAddress. - Ces objets sont nécessaires pour conserver le nom et l'adresse du dernier contact - affiché avant que l'utilisateur ne clique sur le bouton "Add". Grâce à ces variables - si l'utilisateur clique sur "Cancel", il est possible de revenir - à l'affichage du dernier contact. - - \section1 Implémentation de la classe AddressBook - - Dans le constructeur de \c AddressBook, \c nameLine et - \c addressText sont mis en mode lecture seule, de façon à autoriser l'affichage - mais pas la modification du contact courant. - - \dots - \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 1 - \dots - \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 2 - - Ensuite, nous instancions les boutons \c addButton, \c submitButton, et - \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp pushbutton declaration - - Le bouton \c addButton est affiché en invoquant la méthode \l{QPushButton::show()} - {show()}, tandis que \c submitButton et \c cancelButton sont cachés en invoquant - \l{QPushButton::hide()}{hide()}. Ces deux boutons ne seront affichés que lorsque - l'utilisateur cliquera sur "Add", et ceci est géré par la méthode \c addContact() - décrite plus loin. - - \snippet tutorials/addressbook/part2/addressbook.cpp connecting signals and slots - - Nous connectons le signal \l{QPushButton::clicked()}{clicked()} de chaque bouton - au slot qui gèrera l'action. - L'image ci-dessous illustre ceci: - - \image addressbook-tutorial-part2-signals-and-slots.png - - Ensuite, nous arrangeons proprement les boutons sur la droite du widget - AddressBook, et nous utilisons un QVBoxLayout pour les aligner verticalement. - - \snippet tutorials/addressbook/part2/addressbook.cpp vertical layout - - La methode \l{QBoxLayout::addStretch()}{addStretch()} est utilisée pour - assurer que les boutons ne sont pas répartis uniformément, mais regroupés - dans la partie supperieure du widget. La figure ci-dessous montre la différence - si \l{QBoxLayout::addStretch()}{addStretch()} est utilisé ou pas. - - \image addressbook-tutorial-part2-stretch-effects.png - - Ensuite nous ajoutons \c buttonLayout1 à \c mainLayout, en utilisant - \l{QGridLayout::addLayout()}{addLayout()}. Ceci nous permet d'imbriquer les - mises en page puisque \c buttonLayout1 est maintenant un enfant de \c mainLayout. - - \snippet tutorials/addressbook/part2/addressbook.cpp grid layout - - Les coordonnées du layout global ressemblent maintenant à ça: - - \image addressbook-tutorial-part2-labeled-layout.png - - Dans la méthode \c addContact(), nous stockons les détails du dernier - contact affiché dans \c oldName et \c oldAddress. Ensuite, nous - vidons ces champs de saisie et nous désactivons le mode - lecture seule. Le focus est placé sur \c nameLine et on affiche - \c submitButton et \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp addContact - - La méthode \c submitContact() peut être divisée en trois parties: - - \list 1 - \o Nous extrayons les détails du contact depuis \c nameLine et \c addressText - et les stockons dans des objets QString. Nous les validons pour s'assurer - que l'utilisateur n'a pas cliqué sur "Add" avec des champs de saisie - vides; sinon un message est affiché avec QMessageBox pour rappeller à - l'utilisateur que les deux champs doivent être complétés. - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part1 - - \o Ensuite, nous vérifions si le contact existe déjà. Si aucun contacts - existant n'entre en conflit avec le nouveau, nous l'ajoutons à - \c contacts et nous affichons un QMessageBox pour informer l'utilisateur - que le contact a été ajouté. - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part2 - - Si le contact existe déjà, nous affichons un QMessageBox pour informer - l'utilisateur du problème. - Notre objet \c contacts est basé sur des paires clé-valeur formés par - le nom et l'adresse, nous voulons nous assurer que la \e clé est unique. - - \o Une fois que les deux vérifications précédentes ont été traitées, - nous restaurons les boutons à leur état normal à l'aide du code - suivant: - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part3 - - \endlist - - La capture d'écran ci-dessous montre l'affichage fournit par un objet - QMessageBox, utilisé ici pour afficher un message d'information - à l'utilisateur: - - \image addressbook-tutorial-part2-add-successful.png - - La méthode \c cancel() restaure les détails du dernier contact, active - \c addButton, et cache \c submitButton et \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp cancel - - L'idée générale pour augmenter la flexibilité lors de l'ajout d'un - contact est de donner la possiblité de cliquer sur "Add" - ou "Cancel" à n'importe quel moment. - L'organigramme ci-dessous reprend l'ensemble des interactions dévelopées - jusqu'ici: - - \image addressbook-tutorial-part2-add-flowchart.png -*/ - -/*! - \page tutorials-addressbook-fr-part3.html - - \example tutorials/addressbook-fr/part3 - \title Carnet d'adresses 3 - Navigation entre les éléments - - L'application "Carnet d'adresses" est maintenant à moitié terminée. Il - nous faut maintenant ajouter quelques fonctions pour naviguer entre - les contacts. Avant de commencer, il faut se décider sur le type de structure de - données le plus approprié pour stocker les contacts. - - Dans le chapitre 2, nous avons utilisé un QMap utilisant des paires clé-valeur, - avec le nom du contact comme \e clé, et l'adresse du contact comme \e valeur. - Cela fonctionnait bien jusqu'ici, mais pour ajouter la navigation entre les - entrées, quelques améliorations sont nécessaires. - - Nous améliorerons le QMap en le faisant ressembler à une structure de données - similaire à une liste liée, où tous les éléments sont connectés, y compris - le premier et le dernier élément. La figure ci-dessous illustre cette structure - de donnée. - - \image addressbook-tutorial-part3-linkedlist.png - - \section1 Définition de la classe AddressBook - - Pour ajouter les fonctions de navigation au carnet d'adresses, nous avons - besoin de deux slots supplémentaires dans notre classe \c AddressBook: - \c next() et \c previous(). Ceux-ci sont ajoutés au fichier addressbook.h: - - \snippet tutorials/addressbook/part3/addressbook.h navigation functions - - Nous avons aussi besoin de deux nouveaux objets QPushButton, nous ajoutons - donc les variables privées \c nextButton et \c previousButton. - - \snippet tutorials/addressbook/part3/addressbook.h navigation pushbuttons - - \section1 Implémentation de la classe AddressBook - - A l'intérieur du constructeur de \c AddressBook, dans \c addressbook.cpp, nous - instancions \c nextButton et \c previousButton et nous les désactivons - par défaut. Nous faisons ceci car la navigation ne doit être activée - que lorsqu'il y a plus d'un contact dans le carnet d'adresses. - - \snippet tutorials/addressbook/part3/addressbook.cpp navigation pushbuttons - - Nous connectons alors ces boutons à leur slots respectifs: - - \snippet tutorials/addressbook/part3/addressbook.cpp connecting navigation signals - - L'image ci-dessous montre l'interface utilisateur que nous allons créer. - Remarquez que cela ressemble de plus en plus à l'interface du programme - complet. - - \image addressbook-tutorial-part3-screenshot.png - - Nous suivons les conventions pour les fonctions \c next() et \c previous() - en plaçant \c nextButton à droite et \c previousButton à gauche. Pour - faire cette mise en page intuitive, nous utilisons un QHBoxLayout pour - placer les widgets côte à côte: - - \snippet tutorials/addressbook/part3/addressbook.cpp navigation layout - - L'objet QHBoxLayout, \c buttonLayout2, est ensuite ajouté à \c mainLayout. - - \snippet tutorials/addressbook/part3/addressbook.cpp adding navigation layout - - La figure ci-dessous montre les systèmes de coordonnées pour les widgets du - \c mainLayout. - \image addressbook-tutorial-part3-labeled-layout.png - - Dans notre méthode \c addContact(), nous avons desactivé ces boutons - pour être sûr que l'utilisateur n'utilise pas la navigation lors de - l'ajout d'un contact. - - \snippet tutorials/addressbook/part3/addressbook.cpp disabling navigation - - Dans notre méthode \c submitContact(), nous activons les boutons de - navigation, \c nextButton et \c previousButton, en fonction de la - taille de \c contacts. Commen mentionné plus tôt, la navigation n'est - activée que si il y a plus d'un contact dans le carnet d'adresses. - Les lignes suivantes montrent comment faire cela: - - \snippet tutorials/addressbook/part3/addressbook.cpp enabling navigation - - Nous incluons aussi ces lignes de code dans le bouton \c cancel(). - - Souvenez vous que nous voulons émuler une liste-liée ciruculaire à - l'aide de l'objet QMap, \c contacts. Pour faire cela, nous obtenons un itérateur - sur \c contact dans la méthode \c next(), et ensuite: - - \list - \o Si l'itérateur n'est pas à la fin de \c contacts, nous l'incrémentons - \o Si l'itérateur est à la fin de \c contacts, nous changeons sa position - jusqu'au début de \c contacts. Cela donne l'illusion que notre QMap - fonctionne comme une liste circulaire. - \endlist - - \snippet tutorials/addressbook/part3/addressbook.cpp next() function - - Une fois que nous avons itéré jusqu'à l'objet recherché dans \c contacts, - nous affichons son contenu sur \c nameLine et \c addressText. - - De la même façon, pour la méthode \c previous(), nous obtenons un - itérateur sur \c contacts et ensuite: - - \list - \o Si l'itérateur est à la fin de \c contacts, on réinitialise - l'affichage et on retourne. - \o Si l'itérateur est au début de \c contacts, on change sa - position jusqu'à la fin - \o Ensuite, on décrémente l'itérateur - \endlist - - \snippet tutorials/addressbook/part3/addressbook.cpp previous() function - - à nouveau, nous affichons le contenu de l'objet courant dans \c contacts. - -*/ - -/*! - - \page tutorials-addressbook-fr-part4.html - - \example tutorials/addressbook-fr/part4 - \title Carnet d'Adresses 4 - éditer et supprimer des adresses - - - Dans ce chapitre, nous verrons comment modifier les données des contacts - contenus dans l'application carnet d'adresses. - - - \image addressbook-tutorial-screenshot.png - - Nous avons maintenant un carnet d'adresses qui ne se contente pas de - lister des contacts de façon ordonnée, mais permet également la - navigation. Il serait pratique d'inclure des fonctions telles qu'éditer et - supprimer, afin que les détails associés à un contact puissent être - modifiés lorsque c'est nécessaire. Cependant, cela requiert une légère - modification, sous la forme d'énumérations. Au chapitre précédent, nous avions deux - modes: \c {AddingMode} et \c {NavigationMode}, mais ils n'étaient pas - définis en tant qu'énumérations. Au lieu de ça, on activait et désactivait les - boutons correspondants manuellement, au prix de multiples redondances dans - le code. - - Dans ce chapitre, on définit l'énumération \c Mode avec trois valeurs possibles. - - \list - \o \c{NavigationMode}, - \o \c{AddingMode}, et - \o \c{EditingMode}. - \endlist - - \section1 Définition de la classe AddressBook - - Le fichier \c addressbook.h est mis a jour pour contenir l'énumération \c Mode : - - \snippet tutorials/addressbook/part4/addressbook.h Mode enum - - On ajoute également deux nouveaux slots, \c editContact() et - \c removeContact(), à notre liste de slots publics. - - \snippet tutorials/addressbook/part4/addressbook.h edit and remove slots - - Afin de basculer d'un mode à l'autre, on introduit la méthode - \c updateInterface() pour contrôller l'activation et la désactivation de - tous les objets QPushButton. On ajoute également deux nouveaux boutons, - \c editButton et \c removeButton, pour les fonctions d'édition - et de suppression mentionnées plus haut. - - \snippet tutorials/addressbook/part4/addressbook.h updateInterface() declaration - \dots - \snippet tutorials/addressbook/part4/addressbook.h buttons declaration - \dots - \snippet tutorials/addressbook/part4/addressbook.h mode declaration - - Enfin, on déclare \c currentMode pour garder une trace du mode - actuellement utilisé. - - \section1 Implémentation de la classe AddressBook - - Il nous faut maintenant implémenter les fonctionnalités de changement de - mode de l'application carnet d'adresses. Les boutons \c editButton et - \c removeButton sont instanciés et désactivés par défaut, puisque le - carnet d'adresses démarre sans aucun contact en mémoire. - - \snippet tutorials/addressbook/part4/addressbook.cpp edit and remove buttons - - Ces boutons sont ensuite connectés à leurs slots respectifs, - \c editContact() et \c removeContact(), avant d'être ajoutés à - \c buttonLayout1. - - \snippet tutorials/addressbook/part4/addressbook.cpp connecting edit and remove - \dots - \snippet tutorials/addressbook/part4/addressbook.cpp adding edit and remove to the layout - - La methode \c editContact() place les anciens détails du contact dans - \c oldName et \c oldAddress, avant de basculer vers le mode - \c EditingMode. Dans ce mode, les boutons \c submitButton et - \c cancelButton sont tous deux activés, l'utilisateur peut par conséquent - modifier les détails du contact et cliquer sur l'un de ces deux boutons - par la suite. - - \snippet tutorials/addressbook/part4/addressbook.cpp editContact() function - - La méthode \c submitContact() a été divisée en deux avec un bloc - \c{if-else}. On teste \c currentMode pour voir si le mode courant est - \c AddingMode. Si c'est le cas, on procède à l'ajout. - - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function beginning - \dots - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part1 - - Sinon, on s'assure que \c currentMode est en \c EditingMode. Si c'est le - cas, on compare \c oldName et \c name. Si le nom a changé, on supprime - l'ancien contact de \c contacts et on insère le contact mis a jour. - - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part2 - - Si seule l'adresse a changé (i.e. \c oldAddress n'est pas identique à - \c address), on met à jour l'adresse du contact. Enfin on règle - \c currentMode à \c NavigationMode. C'est une étape importante puisque - c'est cela qui réactive tous les boutons désactivés. - - Afin de retirer un contact du carnet d'adresses, on implémente la méthode - \c removeContact(). Cette méthode vérifie que le contact est présent dans - \c contacts. - - \snippet tutorials/addressbook/part4/addressbook.cpp removeContact() function - - Si c'est le cas, on affiche une boîte de dialogue QMessageBox, demandant - confirmation de la suppression à l'utilisateur. Une fois la confirmation - effectuée, on appelle \c previous(), afin de s'assurer que l'interface - utilisateur affiche une autre entrée, et on supprime le contact en - utilisant le méthode \l{QMap::remove()}{remove()} de \l{QMap}. Dans un - souci pratique, on informe l'utilisateur de la suppression par le biais - d'une autre QMessageBox. Les deux boîtes de dialogue utilisées dans cette - méthode sont représentées ci-dessous. - - \image addressbook-tutorial-part4-remove.png - - \section2 Mise à jour de l'Interface utilisateur - - On a évoqué plus haut la méthode \c updateInterface() comme moyen - d'activer et de désactiver les différents boutons de l'interface en - fonction du mode. Cette méthode met à jour le mode courant selon - l'argument \c mode qui lui est passé, en l'assignant à \c currentMode, - avant de tester sa valeur. - - Chacun des boutons est ensuite activé ou désactivé, en fonction du mode. - Le code source pour les cas \c AddingMode et \c EditingMode est visible - ci-dessous: - - \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 1 - - Dans le cas de \c NavigationMode, en revanche, des tests conditionnels - sont passés en paramètre de QPushButton::setEnabled(). Ceci permet de - s'assurer que les boutons \c editButton et \c removeButton ne sont activés - que s'il existe au moins un contact dans le carnet d'adresses; - \c nextButton et \c previousButton ne sont activés que lorsqu'il existe - plus d'un contact dans le carnet d'adresses. - - \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 2 - - En effectuant les opérations de réglage du mode et de mise à jour de - l'interface utilisateur au sein de la même méthode, on est à l'abri de - l'éventualité où l'interface utilisateur se "désynchronise" de l'état - interne de l'application. - -*/ - -/*! - \page tutorials-addressbook-fr-part5.html - - \example tutorials/addressbook-fr/part5 - \title Carnet d'adresse 5 - Ajout d'une fonction de recherche - - Dans ce chapitre, nous allons voir les possibilités pour rechercher - des contacts dans le carnet d'adresse. - - \image addressbook-tutorial-part5-screenshot.png - - Plus nous ajoutons des contacts dans l'application, plus - il devient difficile de naviguer avec les boutons \e Next et \e Previous. - Dans ce cas, une fonction de recherche serait plus efficace pour rechercher - les contacts. - La capture d'écran ci-dessus montre le bouton de recherche \e Find et sa position - dans le paneau de bouton. - - Lorsque l'utilisateur clique sur le bouton \e Find, il est courant d'afficher - une boîte de dialogue qui demande à l'utilisateur d'entrer un nom de contact. - Qt fournit la classe QDialog, que nous sous-classons dans ce chapitre pour - implémenter la class \c FindDialog. - - \section1 Définition de la classe FindDialog - - \image addressbook-tutorial-part5-finddialog.png - - Pour sous-classer QDialog, nous commençons par inclure le header de - QDialog dans le fichier \c finddialog.h. De plus, nous déclarons les - classes QLineEdit et QPushButton car nous utilisons ces widgets dans - notre classe dialogue. - - Tout comme dans la classe \c AddressBook, la classe \c FindDialog utilise - la macro Q_OBJECT et son constructeur est défini de façon à accepter - un QWidget parent, même si cette boîte de dialogue sera affichée dans une - fenêtre séparée. - - \snippet tutorials/addressbook/part5/finddialog.h FindDialog header - - Nous définissons la méthode publique \c getFindText() pour être utilisée - par les classes qui instancient \c FindDialog, ce qui leur permet d'obtenir - le texte entré par l'utilisateur. Un slot public, \c findClicked(), est - défini pour prendre en charge le texte lorsque l'utilisateur clique sur - le bouton \gui Find. - - Finalement, nous définissons les variables privées \c findButton, - \c lineEdit et \c findText, qui correspondent respectivement au bouton - \gui Find, au champ de texte dans lequel l'utilisateur tape le texte - à rechercher, et à une variable interne stockant le texte pour une - utilisation ultérieure. - - \section1 Implémentation de la classe FindDialog - - Dans le constructeur de \c FindDialog, nous instancions les objets des - variables privées \c lineEdit, \c findButton et \c findText. Nous utilisons ensuite - un QHBoxLayout pour positionner les widgets. - - \snippet tutorials/addressbook/part5/finddialog.cpp constructor - - Nous mettons en place la mise en page et le titre de la fenêtre, et - nous connectons les signaux aux slots. Remarquez que le signal - \l{QPushButton::clicked()}{clicked()} de \c{findButton} est connecté - à \c findClicked() et \l{QDialog::accept()}{accept()}. Le slot - \l{QDialog::accept()}{accept()} fourni par le QDialog ferme - la boîte de dialogue et lui donne le code de retour \l{QDialog::}{Accepted}. - Nous utilisons cette fonction pour aider la méthode \c findContact() de la classe - \c{AddressBook} à savoir si l'objet \c FindDialog a été fermé. Ceci sera - expliqué plus loin lorsque nous verrons la méthode \c findContact(). - - \image addressbook-tutorial-part5-signals-and-slots.png - - Dans \c findClicked(), nous validons le champ de texte pour nous - assurer que l'utilisateur n'a pas cliqué sur le bouton \gui Find sans - avoir entré un nom de contact. Ensuite, nous stockons le texte du champ - d'entrée \c lineEdit dans \c findText. Et finalement nous vidons le - contenu de \c lineEdit et cachons la boîte de dialogue. - - \snippet tutorials/addressbook/part5/finddialog.cpp findClicked() function - - La variable \c findText a un accesseur publique associé: \c getFindText(). - Étant donné que nous ne modifions \c findText directement que dans le - constructeur et la méthode \c findClicked(), nous ne créons pas - de manipulateurs associé à \c getFindText(). - Puisque \c getFindText() est publique, les classes instanciant et - utilisant \c FindDialog peuvent toujours accéder à la chaîne de - caractères que l'utilisateur a entré et accepté. - - \snippet tutorials/addressbook/part5/finddialog.cpp getFindText() function - - \section1 Définition de la classe AddressBook - - Pour utiliser \c FindDialog depuis la classe \c AddressBook, nous - incluons \c finddialog.h dans le fichier \c addressbook.h. - - \snippet tutorials/addressbook/part5/addressbook.h include finddialog's header - - Jusqu'ici, toutes les fonctionnalités du carnet d'adresses ont un - QPushButton et un slot correspondant. De la même façon, pour la - fonctionnalité \gui Find, nous avons \c findButton et \c findContact(). - - Le \c findButton est déclaré comme une variable privée et la - méthode \c findContact() est déclarée comme un slot public. - - \snippet tutorials/addressbook/part5/addressbook.h findContact() declaration - \dots - \snippet tutorials/addressbook/part5/addressbook.h findButton declaration - - Finalement, nous déclarons la variable privée \c dialog que nous allons - utiliser pour accéder à une instance de \c FindDialog. - - \snippet tutorials/addressbook/part5/addressbook.h FindDialog declaration - - Une fois que nous avons instancié la boîte de dialogue, nous voulons l'utiliser - plus qu'une fois. Utiliser une variable privée nous permet d'y référer - à plus d'un endroit dans la classe. - - \section1 Implémentation de la classe AddressBook - - Dans le constructeur de \c AddressBook, nous instancions nos objets privés, - \c findbutton et \c findDialog: - - \snippet tutorials/addressbook/part5/addressbook.cpp instantiating findButton - \dots - \snippet tutorials/addressbook/part5/addressbook.cpp instantiating FindDialog - - Ensuite, nous connectons le signal \l{QPushButton::clicked()}{clicked()} de - \c{findButton} à \c findContact(). - - \snippet tutorials/addressbook/part5/addressbook.cpp signals and slots for find - - Maintenant, tout ce qui manque est le code de notre méthode \c findContact(): - - \snippet tutorials/addressbook/part5/addressbook.cpp findContact() function - - Nous commençons par afficher l'instance de \c FindDialog, \c dialog. - L'utilisateur peut alors entrer le nom du contact à rechercher. Lorsque - l'utilisateur clique sur le bouton \c findButton, la boîte de dialogue est - masquée et le code de retour devient QDialog::Accepted. Ce code de retour - vient remplir la condition du premier if. - - Ensuite, nous extrayons le texte que nous utiliserons pour la recherche, - il s'agit ici de \c contactName obtenu à l'aide de la méthode \c getFindText() - de \c FindDialog. Si le contact existe dans le carnet d'adresse, nous - l'affichons directement. Sinon, nous affichons le QMessageBox suivant pour - indiquer que la recherche à échouée. - - \image addressbook-tutorial-part5-notfound.png -*/ - -/*! - \page tutorials-addressbook-part6.html - - \example tutorials/addressbook-fr/part6 - \title Carnet d'Adresses 6 - Sauvegarde et chargement - - Ce chapitre couvre les fonctionnalités de gestion des fichiers de Qt que - l'on utilise pour écrire les procédures de sauvegarde et chargement pour - l'application carnet d'adresses. - - \image addressbook-tutorial-part6-screenshot.png - - Bien que la navigation et la recherche de contacts soient des - fonctionnalités importantes, notre carnet d'adresses ne sera pleinement - utilisable qu'une fois que l'on pourra sauvegarder les contacts existants - et les charger à nouveau par la suite. - Qt fournit de nombreuses classes pour gérer les \l{Input/Output and - Networking}{entrées et sorties}, mais nous avons choisi de nous contenter d'une - combinaison de deux classes simples à utiliser ensemble: QFile et QDataStream. - - Un objet QFile représente un fichier sur le disque qui peut être lu, et - dans lequel on peut écrire. QFile est une classe fille de la classe plus - générique QIODevice, qui peut représenter différents types de - périphériques. - - Un objet QDataStream est utilisé pour sérialiser des données binaires - dans le but de les passer à un QIODevice pour les récupérer dans le - futur. Pour lire ou écrire dans un QIODevice, il suffit d'ouvrir le - flux, avec le périphérique approprié en paramètre, et d'y lire ou - écrire. - - \section1 Définition de la classe AddressBook - - On déclare deux slots publics, \c saveToFile() et \c loadFromFile(), - ainsi que deux objets QPushButton, \c loadButton et \c saveButton. - - \snippet tutorials/addressbook/part6/addressbook.h save and load functions declaration - \dots - \snippet tutorials/addressbook/part6/addressbook.h save and load buttons declaration - - \section1 Implémentation de la classe AddressBook - - Dans notre constructeur, on instancie \c loadButton et \c saveButton. - Idéalement, l'interface serait plus conviviale avec des boutons - affichant "Load contacts from a file" et "Save contacts to a file". Mais - compte tenu de la dimension des autres boutons, on initialise les labels - des boutons à \gui{Load...} et \gui{Save...}. Heureusement, Qt offre une - façon simple d'ajouter des info-bulles avec - \l{QWidget::setToolTip()}{setToolTip()}, et nous l'exploitons de la façon - suivante pour nos boutons: - - \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 1 - \dots - \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 2 - - Bien qu'on ne cite pas le code correspondant ici, nous ajoutons ces deux boutons au - layout de droite, \c button1Layout, comme pour les fonctionnalités précédentes, et - nous connectons leurs signaux - \l{QPushButton::clicked()}{clicked()} à leurs slots respectifs. - - Pour la sauvegarde, on commence par récupérer le nom de fichier - \c fileName, en utilisant QFileDialog::getSaveFileName(). C'est une - méthode pratique fournie par QFileDialog, qui ouvre une boîte de - dialogue modale et permet à l'utilisateur d'entrer un nom de fichier ou - de choisir un fichier \c{.abk} existant. Les fichiers \c{.abk} - correspondent à l'extension choisie pour la sauvegarde des contacts de - notre carnet d'adresses. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part1 - - La boîte de dialogue affichée est visible sur la capture d'écran ci- - dessous. - - \image addressbook-tutorial-part6-save.png - - Si \c fileName n'est pas vide, on crée un objet QFile, \c file, à partir - de \c fileName. QFile fonctionne avec QDataStream puisqu'il dérive de - QIODevice. - - Ensuite, on essaie d'ouvrir le fichier en écriture, ce qui correspond au - mode \l{QIODevice::}{WriteOnly}. Si cela échoue, on en informe - l'utilisateur avec une QMessageBox. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part2 - - Dans le cas contraire, on instancie un objet QDataStream, \c out, afin - d'écrire dans le fichier ouvert. QDataStream nécessite que la même - version de flux soit utilisée pour la lecture et l'écriture. On s'assure - que c'est le cas en spécifiant explicitement d'utiliser la - \l{QDataStream::Qt_4_5}{version introduite avec Qt 4.5} avant de - sérialiser les données vers le fichier \c file. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part3 - - Pour le chargement, on récupère également \c fileName en utilisant - QFileDialog::getOpenFileName(). Cette méthode est l'homologue de - QFileDialog::getSaveFileName() et affiche également une boîte de - dialogue modale permettant à l'utilisateur d'entrer un nom de fichier ou - de selectionner un fichier \c{.abk} existant, afin de le charger dans le - carnet d'adresses. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part1 - - Sous Windows, par exemple, cette méthode affiche une boîte de dialogue - native pour la sélection de fichier, comme illustré sur la capture - d'écran suivante: - - \image addressbook-tutorial-part6-load.png - - Si \c fileName n'est pas vide, on utilise une fois de plus un objet - QFile, \c file, et on tente de l'ouvrir en lecture, avec le mode - \l{QIODevice::}{ReadOnly}. De même que précédemment dans notre - implémentation de \c saveToFile(), si cette tentative s'avère - infructueuse, on en informe l'utilisateur par le biais d'une - QMessageBox. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part2 - - Dans le cas contraire, on instancie un objet QDataStream, \c in, en - spécifiant la version à utiliser comme précédemment, et on lit les - informations sérialisées vers la structure de données \c contacts. Notez - qu'on purge \c contacts avant d'y mettre les informations lues afin de - simplifier le processus de lecture de fichier. Une façon plus avancée de - procéder serait de lire les contacts dans un objet QMap temporaire, et - de copier uniquement les contacts n'existant pas encore dans - \c contacts. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part3 - - Pour afficher les contacts lus depuis le fichier, on doit d'abord - valider les données obtenues afin de s'assurer que le fichier lu - contient effectivement des entrées de carnet d'adresses. Si c'est le - cas, on affiche le premier contact; sinon on informe l'utilisateur du - problème par une QMessageBox. Enfin, on met à jour l'interface afin - d'activer et de désactiver les boutons de façon appropriée. -*/ - -/*! - \page tutorials-addressbook-fr-part7.html - - \example tutorials/addressbook-fr/part7 - \title Carnet d'adresse 7 - Fonctionnalités avancées - - Ce chapitre couvre quelques fonctionnalités additionnelles qui - feront de notre carnet d'adresses une application plus pratique - pour une utilisation quotidienne. - - \image addressbook-tutorial-part7-screenshot.png - - Bien que notre application carnet d'adresses soit utile en tant que telle, - il serait pratique de pouvoir échanger les contacts avec d'autres applications. - Le format vCard est un un format de fichier populaire pour échanger - ce type de données. - Dans ce chapitre, nous étendrons notre carnet d'adresses pour permettre - d'exporter des contacts dans des fichiers vCard \c{.vcf}. - - \section1 Définition de la classe AddressBook - - Nous ajoutons un objet QPushButton, \c exportButton, et un slot - public correspondant, \c exportAsVCard(), à notre classe \c AddressBook - dans le fichier \c addressbook.h. - - \snippet tutorials/addressbook/part7/addressbook.h exportAsVCard() declaration - \dots - \snippet tutorials/addressbook/part7/addressbook.h exportButton declaration - - \section1 Implémentation de la classe AddressBook - - Dans le constructeur de \c AddressBook, nous connectons le signal - \l{QPushButton::clicked()}{clicked()} de \c{exportButton} au slot - \c exportAsVCard(). - Nous ajoutons aussi ce bouton à \c buttonLayout1, le layout responsable - du groupe de boutons sur la droite. - - Dans la méthode \c exportAsVCard(), nous commençons par extraire le - nom du contact dans \n name. Nous déclarons \c firstname, \c lastName et - \c nameList. - Ensuite, nous cherchons la position du premier espace blanc de \c name. - Si il y a un espace, nous séparons le nom du contact en \c firstName et - \c lastName. Finalement, nous remplaçons l'espace par un underscore ("_"). - Si il n'y a pas d'espace, nous supposons que le contact ne comprend que - le prénom. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part1 - - Comme pour la méthode \c saveToFile(), nous ouvrons une boîte de dialogue - pour donner la possibilité à l'utilisateur de choisir un emplacement pour - le fichier. Avec le nom de fichier choisi, nous créons une instance de QFile - pour y écrire. - - Nous essayons d'ouvrir le fichier en mode \l{QIODevice::}{WriteOnly}. Si - cela échoue, nous affichons un QMessageBox pour informer l'utilisateur - à propos de l'origine du problème et nous quittons la méthode. Sinon, nous passons le - fichier comme paramètre pour créer un objet QTextStream, \c out. De la même façon que - QDataStream, la classe QTextStream fournit les fonctionnalités pour - lire et écrire des fichiers de texte. Grâce à celà, le fichier \c{.vcf} - généré pourra être ouvert et édité à l'aide d'un simple éditeur de texte. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part2 - - Nous écrivons ensuite un fichier vCard avec la balise \c{BEGIN:VCARD}, - suivit par \c{VERSION:2.1}. - Le nom d'un contact est écrit à l'aide de la balise \c{N:}. Pour la balise - \c{FN:}, qui remplit le titre du contact, nous devons vérifier si le contact - à un nom de famille défini ou non. Si oui, nous utilions les détails de - \c nameList pour remplir le champ, dans le cas contraire on écrit uniquement le contenu - de \c firstName. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part3 - - Nous continuons en écrivant l'adresse du contact. Les points-virgules - dans l'adresse sont échappés à l'aide de "\\", les retours de ligne sont - remplacés par des points-virgules, et les vigules sont remplacées par des espaces. - Finalement nous écrivons les balises \c{ADR;HOME:;} suivies par l'adresse - et la balise \c{END:VCARD}. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part4 - - À la fin de la méthode, un QMessageBox est affiché pour informer l'utilisateur - que la vCard a été exportée avec succès. - - \e{vCard est une marque déposée de \l{http://www.imc.org} - {Internet Mail Consortium}}. -*/ diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc deleted file mode 100644 index d75e2cac2a..0000000000 --- a/doc/src/tutorials/addressbook.qdoc +++ /dev/null @@ -1,981 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page tutorials-addressbook.html - - \title Address Book Tutorial - \brief An introduction to GUI programming, showing how to put together a - simple yet fully-functioning application. - - This tutorial is an introduction to GUI programming with the Qt - cross-platform framework. - - \image addressbook-tutorial-screenshot.png - - \omit - It doesn't cover everything; the emphasis is on teaching the programming - philosophy of GUI programming, and Qt's features are introduced as needed. - Some commonly used features are never used in this tutorial. - \endomit - - In this tutorial, you will learn about some of the basic - components of Qt, including: - - \list - \o Widgets and layout managers - \o Container classes - \o Signals and slots - \o Input and output devices - \endlist - - If you are new to Qt, we recommend reading \l{How to Learn Qt} first. - - Tutorial contents: - - \list 1 - \o \l{tutorials/addressbook/part1}{Designing the User Interface} - \o \l{tutorials/addressbook/part2}{Adding Addresses} - \o \l{tutorials/addressbook/part3}{Navigating between Entries} - \o \l{tutorials/addressbook/part4}{Editing and Removing Addresses} - \o \l{tutorials/addressbook/part5}{Adding a Find Function} - \o \l{tutorials/addressbook/part6}{Loading and Saving} - \o \l{tutorials/addressbook/part7}{Additional Features} - \endlist - - The tutorial source code is located in \c{examples/tutorials/addressbook}. - - Although this little application does not look much like a - fully-fledged modern GUI application, it uses many of the basic - elements that are used in more complex applications. After you - have worked through this tutorial, we recommend reading the - \l{mainwindows/application}{Application} example, which presents a - small GUI application, with menus, toolbars, a status bar, and so - on. -*/ - -/*! - \page tutorials-addressbook-part1.html - - \example tutorials/addressbook/part1 - \title Part 1 - Designing the User Interface - - This first part covers the design of the basic graphical user - interface (GUI) for our address book application. - - The first step in creating a GUI program is to design the user - interface. Here the our goal is to set up the labels and input - fields to implement a basic address book. The figure below is a - screenshot of the expected output. - - \image addressbook-tutorial-part1-screenshot.png - - We require two QLabel objects, \c nameLabel and \c addressLabel, as well - as two input fields, a QLineEdit object, \c nameLine, and a QTextEdit - object, \c addressText, to enable the user to enter a contact's name and - address. The widgets used and their positions are shown in the figure - below. - - \image addressbook-tutorial-part1-labeled-screenshot.png - - There are three files used to implement this address book: - - \list - \o \c{addressbook.h} - the definition file for the \c AddressBook - class, - \o \c{addressbook.cpp} - the implementation file for the - \c AddressBook class, and - \o \c{main.cpp} - the file containing a \c main() function, with - an instance of \c AddressBook. - \endlist - - \section1 Qt Programming - Subclassing - - When writing Qt programs, we usually subclass Qt objects to add - functionality. This is one of the essential concepts behind creating - custom widgets or collections of standard widgets. Subclassing to - extend or change the behavior of a widget has the following advantages: - - \list - \o We can write implementations of virtual or pure virtual functions to - obtain exactly what we need, falling back on the base class's implementation - when necessary. - \o It allows us to encapsulate parts of the user interface within a class, - so that the other parts of the application don't need to know about the - individual widgets in the user interface. - \o The subclass can be used to create multiple custom widgets in the same - application or library, and the code for the subclass can be reused in other - projects. - \endlist - - Since Qt does not provide a specific address book widget, we subclass a - standard Qt widget class and add features to it. The \c AddressBook class - we create in this tutorial can be reused in situations where a basic address - book widget is needed. - - \section1 Defining the AddressBook Class - - The \l{tutorials/addressbook/part1/addressbook.h}{\c addressbook.h} file is - used to define the \c AddressBook class. - - We start by defining \c AddressBook as a QWidget subclass and declaring - a constructor. We also use the Q_OBJECT macro to indicate that the class - uses internationalization and Qt's signals and slots features, even - if we do not use all of these features at this stage. - - \snippet tutorials/addressbook/part1/addressbook.h class definition - - The class holds declarations of \c nameLine and \c addressText, - the private instances of QLineEdit and QTextEdit mentioned - earlier. The data stored in \c nameLine and \c addressText will - be needed for many of the address book functions. - - We don't include declarations of the QLabel objects we will use - because we will not need to reference them once they have been - created. The way Qt tracks the ownership of objects is explained - in the next section. - - The Q_OBJECT macro itself implements some of the more advanced features of Qt. - For now, it is useful to think of the Q_OBJECT macro as a shortcut which allows - us to use the \l{QObject::}{tr()} and \l{QObject::}{connect()} functions. - - We have now completed the \c addressbook.h file and we move on to - implement the corresponding \c addressbook.cpp file. - - \section1 Implementing the AddressBook Class - - The constructor of \c AddressBook accepts a QWidget parameter, \a parent. - By convention, we pass this parameter to the base class's constructor. - This concept of ownership, where a parent can have one or more children, - is useful for grouping widgets in Qt. For example, if you delete a parent, - all of its children will be deleted as well. - - \snippet tutorials/addressbook/part1/addressbook.cpp constructor and input fields - - In this constructor, the QLabel objects \c nameLabel and \c - addressLabel are instantiated, as well as \c nameLine and \c - addressText. The \l{QObject::tr()}{tr()} function returns a - translated version of the string, if there is one - available. Otherwise it returns the string itself. This function - marks its QString parameter as one that should be translated into - other languages. It should be used wherever a translatable string - appears. - - When programming with Qt, it is useful to know how layouts work. - Qt provides three main layout classes: QHBoxLayout, QVBoxLayout - and QGridLayout to handle the positioning of widgets. - - \image addressbook-tutorial-part1-labeled-layout.png - - We use a QGridLayout to position our labels and input fields in a - structured manner. QGridLayout divides the available space into a grid and - places widgets in the cells we specify with row and column numbers. The - diagram above shows the layout cells and the position of our widgets, and - we specify this arrangement using the following code: - - \snippet tutorials/addressbook/part1/addressbook.cpp layout - - Notice that \c addressLabel is positioned using Qt::AlignTop as an - additional argument. This is to make sure it is not vertically centered in - cell (1,0). For a basic overview on Qt Layouts, refer to the - \l{Layout Management} documentation. - - In order to install the layout object onto the widget, we have to invoke - the widget's \l{QWidget::setLayout()}{setLayout()} function: - - \snippet tutorials/addressbook/part1/addressbook.cpp setting the layout - - Lastly, we set the widget's title to "Simple Address Book". - - \section1 Running the Application - - A separate file, \c main.cpp, is used for the \c main() function. Within - this function, we instantiate a QApplication object, \c app. QApplication - is responsible for various application-wide resources, such as the default - font and cursor, and for running an event loop. Hence, there is always one - QApplication object in every GUI application using Qt. - - \snippet tutorials/addressbook/part1/main.cpp main function - - We construct a new \c AddressBook widget on the stack and invoke - its \l{QWidget::show()}{show()} function to display it. - However, the widget will not be shown until the application's event loop - is started. We start the event loop by calling the application's - \l{QApplication::}{exec()} function; the result returned by this function - is used as the return value from the \c main() function. At this point, - it becomes apparent why we instanciated \c AddressBook on the stack: It - will now go out of scope. Therefore, \c AddressBook and all its child widgets - will be deleted, thus preventing memory leaks. -*/ - -/*! - \page tutorials-addressbook-part2.html - - \example tutorials/addressbook/part2 - \title Part 2 - Adding Addresses - - The next step in creating the address book is to implement some - user interactions. - - \image addressbook-tutorial-part2-add-contact.png - - We will provide a push button that the user can click to add a new contact. - Also, some form of data structure is needed to store these contacts in an - organized way. - - \section1 Defining the AddressBook Class - - Now that we have the labels and input fields set up, we add push buttons to - complete the process of adding a contact. This means that our - \c addressbook.h file now has three QPushButton objects declared and three - corresponding public slots. - - \snippet tutorials/addressbook/part2/addressbook.h slots - - A slot is a function that responds to a particular signal. We will discuss - this concept in further detail when implementing the \c AddressBook class. - However, for an overview of Qt's signals and slots concept, you can refer - to the \l{Signals and Slots} document. - - Three QPushButton objects (\c addButton, \c submitButton, and - \c cancelButton) are now included in our private variable declarations, - along with \c nameLine and \c addressText. - - \snippet tutorials/addressbook/part2/addressbook.h pushbutton declaration - - We need a container to store our address book contacts, so that we can - traverse and display them. A QMap object, \c contacts, is used for this - purpose as it holds a key-value pair: the contact's name as the \e key, - and the contact's address as the \e{value}. - - \snippet tutorials/addressbook/part2/addressbook.h remaining private variables - - We also declare two private QString objects, \c oldName and \c oldAddress. - These objects are needed to hold the name and address of the contact that - was last displayed, before the user clicked \gui Add. So, when the user clicks - \gui Cancel, we can revert to displaying the details of the last contact. - - \section1 Implementing the AddressBook Class - - Within the constructor of \c AddressBook, we set the \c nameLine and - \c addressText to read-only, so that we can only display but not edit - existing contact details. - - \dots - \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 1 - \dots - \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 2 - - Then, we instantiate our push buttons: \c addButton, \c submitButton, and - \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp pushbutton declaration - - The \c addButton is displayed by invoking the \l{QPushButton::show()} - {show()} function, while the \c submitButton and \c cancelButton are - hidden by invoking \l{QPushButton::hide()}{hide()}. These two push - buttons will only be displayed when the user clicks \gui Add and this is - handled by the \c addContact() function discussed below. - - \snippet tutorials/addressbook/part2/addressbook.cpp connecting signals and slots - - We connect the push buttons' \l{QPushButton::clicked()}{clicked()} signal - to their respective slots. The figure below illustrates this. - - \image addressbook-tutorial-part2-signals-and-slots.png - - Next, we arrange our push buttons neatly to the right of our address book - widget, using a QVBoxLayout to line them up vertically. - - \snippet tutorials/addressbook/part2/addressbook.cpp vertical layout - - The \l{QBoxLayout::addStretch()}{addStretch()} function is used to ensure - the push buttons are not evenly spaced, but arranged closer to the top of - the widget. The figure below shows the difference between using - \l{QBoxLayout::addStretch()}{addStretch()} and not using it. - - \image addressbook-tutorial-part2-stretch-effects.png - - We then add \c buttonLayout1 to \c mainLayout, using - \l{QGridLayout::addLayout()}{addLayout()}. This gives us nested layouts - as \c buttonLayout1 is now a child of \c mainLayout. - - \snippet tutorials/addressbook/part2/addressbook.cpp grid layout - - Our layout coordinates now look like this: - - \image addressbook-tutorial-part2-labeled-layout.png - - In the \c addContact() function, we store the last displayed contact - details in \c oldName and \c oldAddress. Then we clear these input - fields and turn off the read-only mode. The focus is set on \c nameLine - and we display \c submitButton and \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp addContact - - The \c submitContact() function can be divided into three parts: - - \list 1 - \o We extract the contact's details from \c nameLine and \c addressText - and store them in QString objects. We also validate to make sure that the - user did not click \gui Submit with empty input fields; otherwise, a - QMessageBox is displayed to remind the user for a name and address. - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part1 - - \o We then proceed to check if the contact already exists. If it does not - exist, we add the contact to \c contacts and we display a QMessageBox to - inform the user that the contact has been added. - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part2 - - If the contact already exists, again, we display a QMessageBox to inform - the user about this, preventing the user from adding duplicate contacts. - Our \c contacts object is based on key-value pairs of name and address, - hence, we want to ensure that \e key is unique. - - \o Once we have handled both cases mentioned above, we restore the push - buttons to their normal state with the following code: - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part3 - - \endlist - - The screenshot below shows the QMessageBox object we use to display - information messages to the user. - - \image addressbook-tutorial-part2-add-successful.png - - The \c cancel() function restores the last displayed contact details and - enables \c addButton, as well as hides \c submitButton and - \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp cancel - - The general idea behind adding a contact is to give the user the - flexibility to click \gui Submit or \gui Cancel at any time. The flowchart below - further explains this concept: - - \image addressbook-tutorial-part2-add-flowchart.png -*/ - -/*! - \page tutorials-addressbook-part3.html - - \example tutorials/addressbook/part3 - \title Part 3 - Navigating between Entries - - The address book is now about half complete. We should add the - capability to navigate among the contacts, but first we must - decide what sort of a data structure we need for containing these - contacts. - - In the previous section, we used a QMap of key-value pairs with - the contact's name as the \e key, and the contact's address as the - \e value. This works well for our case. However, in order to - navigate and display each entry, a little bit of enhancement is - needed. - - We enhance the QMap by making it replicate a data structure similar to a - circularly-linked list, where all elements are connected, including the - first element and the last element. The figure below illustrates this data - structure. - - \image addressbook-tutorial-part3-linkedlist.png - - \section1 Defining the AddressBook Class - - To add navigation functions to the address book, we must add two - more slots to the \c AddressBook class: \c next() and \c - previous() to the \c addressbook.h file: - - \snippet tutorials/addressbook/part3/addressbook.h navigation functions - - We also require another two QPushButton objects, so we declare \c nextButton - and \c previousButton as private variables: - - \snippet tutorials/addressbook/part3/addressbook.h navigation pushbuttons - - \section1 Implementing the AddressBook Class - - In the \c AddressBook constructor in \c addressbook.cpp, we instantiate - \c nextButton and \c previousButton and disable them by default. This is - because navigation is only enabled when there is more than one contact - in the address book. - - \snippet tutorials/addressbook/part3/addressbook.cpp navigation pushbuttons - - We then connect these push buttons to their respective slots: - - \snippet tutorials/addressbook/part3/addressbook.cpp connecting navigation signals - - The image below is the expected graphical user interface. - - \image addressbook-tutorial-part3-screenshot.png - - We follow basic conventions for \c next() and \c previous() functions by - placing the \c nextButton on the right and the \c previousButton on the - left. In order to achieve this intuitive layout, we use QHBoxLayout to - place the widgets side-by-side: - - \snippet tutorials/addressbook/part3/addressbook.cpp navigation layout - - The QHBoxLayout object, \c buttonLayout2, is then added to \c mainLayout. - - \snippet tutorials/addressbook/part3/addressbook.cpp adding navigation layout - - The figure below shows the coordinates of the widgets in \c mainLayout. - \image addressbook-tutorial-part3-labeled-layout.png - - Within our \c addContact() function, we have to disable these buttons so - that the user does not attempt to navigate while adding a contact. - - \snippet tutorials/addressbook/part3/addressbook.cpp disabling navigation - - Also, in our \c submitContact() function, we enable the navigation - buttons, \c nextButton and \c previousButton, depending on the size - of \c contacts. As mentioned earlier, navigation is only enabled when - there is more than one contact in the address book. The following lines - of code demonstrates how to do this: - - \snippet tutorials/addressbook/part3/addressbook.cpp enabling navigation - - We also include these lines of code in the \c cancel() function. - - Recall that we intend to emulate a circularly-linked list with our QMap - object, \c contacts. So, in the \c next() function, we obtain an iterator - for \c contacts and then: - - \list - \o If the iterator is not at the end of \c contacts, we increment it - by one. - \o If the iterator is at the end of \c contacts, we move it to the - beginning of \c contacts. This gives us the illusion that our QMap is - working like a circularly-linked list. - \endlist - - \snippet tutorials/addressbook/part3/addressbook.cpp next() function - - Once we have iterated to the correct object in \c contacts, we display - its contents on \c nameLine and \c addressText. - - Similarly, for the \c previous() function, we obtain an iterator for - \c contacts and then: - - \list - \o If the iterator is at the end of \c contacts, we clear the - display and return. - \o If the iterator is at the beginning of \c contacts, we move it to - the end. - \o We then decrement the iterator by one. - \endlist - - \snippet tutorials/addressbook/part3/addressbook.cpp previous() function - - Again, we display the contents of the current object in \c contacts. - -*/ - -/*! - \page tutorials-addressbook-part4.html - - \example tutorials/addressbook/part4 - \title Part 4 - Editing and Removing Addresses - - Now we look at ways to modify the contents of contacts stored in - the address book. - - \image addressbook-tutorial-screenshot.png - - We now have an address book that not only holds contacts in an - organized manner, but also allows navigation. It would be - convenient to include edit and remove functions so that a - contact's details can be changed when needed. However, this - requires a little improvement, in the form of enums. We defined - two modes: \c{AddingMode} and \c{NavigationMode}, but they were - not defined as enum values. Instead, we enabled and disabled the - corresponding buttons manually, resulting in multiple lines of - repeated code. - - Here we define the \c Mode enum with three different values: - - \list - \o \c{NavigationMode}, - \o \c{AddingMode}, and - \o \c{EditingMode}. - \endlist - - \section1 Defining the AddressBook Class - - The \c addressbook.h file is updated to contain the \c Mode enum: - - \snippet tutorials/addressbook/part4/addressbook.h Mode enum - - We also add two new slots, \c editContact() and \c removeContact(), to - our current list of public slots. - - \snippet tutorials/addressbook/part4/addressbook.h edit and remove slots - - In order to switch between modes, we introduce the \c updateInterface() function - to control the enabling and disabling of all QPushButton objects. We also - add two new push buttons, \c editButton and \c removeButton, for the edit - and remove functions mentioned earlier. - - \snippet tutorials/addressbook/part4/addressbook.h updateInterface() declaration - \dots - \snippet tutorials/addressbook/part4/addressbook.h buttons declaration - \dots - \snippet tutorials/addressbook/part4/addressbook.h mode declaration - - Lastly, we declare \c currentMode to keep track of the enum's current mode. - - \section1 Implementing the AddressBook Class - - We now implement the mode-changing features of the address - book. The \c editButton and \c removeButton are instantiated and - disabled by default. The address book starts with zero contacts - in memory. - - \snippet tutorials/addressbook/part4/addressbook.cpp edit and remove buttons - - These buttons are then connected to their respective slots, \c editContact() - and \c removeContact(), and we add them to \c buttonLayout1. - - \snippet tutorials/addressbook/part4/addressbook.cpp connecting edit and remove - \dots - \snippet tutorials/addressbook/part4/addressbook.cpp adding edit and remove to the layout - - The \c editContact() function stores the contact's old details in - \c oldName and \c oldAddress, before switching the mode to \c EditingMode. - In this mode, the \c submitButton and \c cancelButton are both enabled, - hence, the user can change the contact's details and click either button. - - \snippet tutorials/addressbook/part4/addressbook.cpp editContact() function - - The \c submitContact() function has been divided in two with an \c{if-else} - statement. We check \c currentMode to see if it's in \c AddingMode. If it is, - we proceed with our adding process. - - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function beginning - \dots - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part1 - - Otherwise, we check to see if \c currentMode is in \c EditingMode. If it - is, we compare \c oldName with \c name. If the name has changed, we remove - the old contact from \c contacts and insert the newly updated contact. - - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part2 - - If only the address has changed (i.e., \c oldAddress is not the same as \c address), - we update the contact's address. Lastly, we set \c currentMode to - \c NavigationMode. This is an important step as it re-enables all the - disabled push buttons. - - To remove a contact from the address book, we implement the - \c removeContact() function. This function checks to see if the contact - exists in \c contacts. - - \snippet tutorials/addressbook/part4/addressbook.cpp removeContact() function - - If it does, we display a QMessageBox, to confirm the removal with the - user. Once the user has confirmed, we call \c previous() to ensure that the - user interface shows another contact, and we remove the contact using \l{QMap}'s - \l{QMap::remove()}{remove()} function. As a courtesy, we display a QMessageBox - to inform the user. Both the message boxes used in this function are shown below: - - \image addressbook-tutorial-part4-remove.png - - \section2 Updating the User Interface - - We mentioned the \c updateInterface() function earlier as a means to - enable and disable the push buttons depending on the current mode. - The function updates the current mode according to the \c mode argument - passed to it, assigning it to \c currentMode before checking its value. - - Each of the push buttons is then enabled or disabled, depending on the - current mode. The code for \c AddingMode and \c EditingMode is shown below: - - \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 1 - - For \c NavigationMode, however, we include conditions within the parameters - of the QPushButton::setEnabled() function. This is to ensure that - \c editButton and \c removeButton are enabled when there is at least one - contact in the address book; \c nextButton and \c previousButton are only - enabled when there is more than one contact in the address book. - - \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 2 - - By setting the mode and updating the user interface in the same - function, we avoid the possibility of the user interface getting - out of sync with the internal state of the application. - */ - -/*! - \page tutorials-addressbook-part5.html - - \example tutorials/addressbook/part5 - \title Part 5 - Adding a Find Function - - Here we look at ways to locate contacts and addresses in the - address book. - - \image addressbook-tutorial-part5-screenshot.png - - As we add contacts to our address book, it becomes tedious to - navigate the list with the \e Next and \e Previous buttons. A \e - Find function would be more efficient. The screenshot above shows - the \e Find button and its position on the panel of buttons. - - When the user clicks on the \e Find button, it is useful to - display a dialog that prompts for a contact's name. Qt provides - QDialog, which we subclass here to implement a \c FindDialog - class. - - \section1 Defining the FindDialog Class - - \image addressbook-tutorial-part5-finddialog.png - - In order to subclass QDialog, we first include the header for QDialog in - the \c finddialog.h file. Also, we use forward declaration to declare - QLineEdit and QPushButton since we will be using those widgets in our - dialog class. - - As in our \c AddressBook class, the \c FindDialog class includes - the Q_OBJECT macro and its constructor is defined to accept a parent - QWidget, even though the dialog will be opened as a separate window. - - \snippet tutorials/addressbook/part5/finddialog.h FindDialog header - - We define a public function, \c getFindText(), to be used by classes that - instantiate \c FindDialog. This function allows these classes to obtain the - search string entered by the user. A public slot, \c findClicked(), is also - defined to handle the search string when the user clicks the \gui Find - button. - - Lastly, we define the private variables, \c findButton, \c lineEdit - and \c findText, corresponding to the \gui Find button, the line edit - into which the user types the search string, and an internal string - used to store the search string for later use. - - \section1 Implementing the FindDialog Class - - Within the constructor of \c FindDialog, we set up the private variables, - \c lineEdit, \c findButton and \c findText. We use a QHBoxLayout to - position the widgets. - - \snippet tutorials/addressbook/part5/finddialog.cpp constructor - - We set the layout and window title, as well as connect the signals to their - respective slots. Notice that \c{findButton}'s \l{QPushButton::clicked()} - {clicked()} signal is connected to to \c findClicked() and - \l{QDialog::accept()}{accept()}. The \l{QDialog::accept()}{accept()} slot - provided by QDialog hides the dialog and sets the result code to - \l{QDialog::}{Accepted}. We use this function to help \c{AddressBook}'s - \c findContact() function know when the \c FindDialog object has been - closed. We will explain this logic in further detail when discussing the - \c findContact() function. - - \image addressbook-tutorial-part5-signals-and-slots.png - - In \c findClicked(), we validate \c lineEdit to ensure that the user - did not click the \gui Find button without entering a contact's name. Then, we set - \c findText to the search string, extracted from \c lineEdit. After that, - we clear the contents of \c lineEdit and hide the dialog. - - \snippet tutorials/addressbook/part5/finddialog.cpp findClicked() function - - The \c findText variable has a public getter function, \c getFindText(), - associated with it. Since we only ever set \c findText directly in both the - constructor and in the \c findClicked() function, we do not create a - setter function to accompany \c getFindText(). - Because \c getFindText() is public, classes instantiating and using - \c FindDialog can always access the search string that the user has - entered and accepted. - - \snippet tutorials/addressbook/part5/finddialog.cpp getFindText() function - - \section1 Defining the AddressBook Class - - To ensure we can use \c FindDialog from within our \c AddressBook class, we - include \c finddialog.h in the \c addressbook.h file. - - \snippet tutorials/addressbook/part5/addressbook.h include finddialog's header - - So far, all our address book features have a QPushButton and a - corresponding slot. Similarly, for the \gui Find feature we have - \c findButton and \c findContact(). - - The \c findButton is declared as a private variable and the - \c findContact() function is declared as a public slot. - - \snippet tutorials/addressbook/part5/addressbook.h findContact() declaration - \dots - \snippet tutorials/addressbook/part5/addressbook.h findButton declaration - - Lastly, we declare the private variable, \c dialog, which we will use to - refer to an instance of \c FindDialog. - - \snippet tutorials/addressbook/part5/addressbook.h FindDialog declaration - - Once we have instantiated a dialog, we will want to use it more than once; - using a private variable allows us to refer to it from more than one place - in the class. - - \section1 Implementing the AddressBook Class - - Within the \c AddressBook class's constructor, we instantiate our private - objects, \c findButton and \c findDialog: - - \snippet tutorials/addressbook/part5/addressbook.cpp instantiating findButton - \dots - \snippet tutorials/addressbook/part5/addressbook.cpp instantiating FindDialog - - Next, we connect the \c{findButton}'s - \l{QPushButton::clicked()}{clicked()} signal to \c findContact(). - - \snippet tutorials/addressbook/part5/addressbook.cpp signals and slots for find - - Now all that is left is the code for our \c findContact() function: - - \snippet tutorials/addressbook/part5/addressbook.cpp findContact() function - - We start out by displaying the \c FindDialog instance, \c dialog. This is - when the user enters a contact name to look up. Once the user clicks - the dialog's \c findButton, the dialog is hidden and the result code is - set to QDialog::Accepted. This ensures that - our \c if statement is always true. - - We then proceed to extract the search string, which in this case is - \c contactName, using \c{FindDialog}'s \c getFindText() function. If the - contact exists in our address book, we display it immediately. Otherwise, - we display the QMessageBox shown below to indicate that their search - failed. - - \image addressbook-tutorial-part5-notfound.png -*/ - -/*! - \page tutorials-addressbook-part6.html - - \example tutorials/addressbook/part6 - \title Part 6 - Loading and Saving - - This part covers the Qt file handling features we use to write - loading and saving routines for the address book. - - \image addressbook-tutorial-part6-screenshot.png - - Although browsing and searching the contact list are useful - features, our address book is not complete until we can save - existing contacts and load them again at a later time. - - Qt provides a number of classes for \l{Input/Output and Networking} - {input and output}, but we have chosen to use two which are simple to use - in combination: QFile and QDataStream. - - A QFile object represents a file on disk that can be read from and written - to. QFile is a subclass of the more general QIODevice class which - represents many different kinds of devices. - - A QDataStream object is used to serialize binary data so that it can be - stored in a QIODevice and retrieved again later. Reading from a QIODevice - and writing to it is as simple as opening the stream - with the respective - device as a parameter - and reading from or writing to it. - - - \section1 Defining the AddressBook Class - - We declare two public slots, \c saveToFile() and \c loadFromFile(), as well - as two QPushButton objects, \c loadButton and \c saveButton. - - \snippet tutorials/addressbook/part6/addressbook.h save and load functions declaration - \dots - \snippet tutorials/addressbook/part6/addressbook.h save and load buttons declaration - - \section1 Implementing the AddressBook Class - - In our constructor, we instantiate \c loadButton and \c saveButton. - Ideally, it would be more user-friendly to set the push buttons' labels - to "Load contacts from a file" and "Save contacts to a file". However, due - to the size of our other push buttons, we set the labels to \gui{Load...} - and \gui{Save...}. Fortunately, Qt provides a simple way to set tooltips with - \l{QWidget::setToolTip()}{setToolTip()} and we use it in the following way - for our push buttons: - - \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 1 - \dots - \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 2 - - Although it is not shown here, just like the other features we implemented, - we add the push buttons to the layout panel on the right, \c buttonLayout1, - and we connect the push buttons' \l{QPushButton::clicked()}{clicked()} - signals to their respective slots. - - For the saving feature, we first obtain \c fileName using - QFileDialog::getSaveFileName(). This is a convenience function provided - by QFileDialog, which pops up a modal file dialog and allows the user to - enter a file name or select any existing \c{.abk} file. The \c{.abk} file - is our Address Book extension that we create when we save contacts. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part1 - - The file dialog that pops up is displayed in the screenshot below: - - \image addressbook-tutorial-part6-save.png - - If \c fileName is not empty, we create a QFile object, \c file, with - \c fileName. QFile works with QDataStream as QFile is a QIODevice. - - Next, we attempt to open the file in \l{QIODevice::}{WriteOnly} mode. - If this is unsuccessful, we display a QMessageBox to inform the user. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part2 - - Otherwise, we instantiate a QDataStream object, \c out, to write the open - file. QDataStream requires that the same version of the stream is used - for reading and writing. We ensure that this is the case by setting the - version used to the \l{QDataStream::Qt_4_5}{version introduced with Qt 4.5} - before serializing the data to \c file. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part3 - - For the loading feature, we also obtain \c fileName using - QFileDialog::getOpenFileName(). This function, the counterpart to - QFileDialog::getSaveFileName(), also pops up the modal file dialog and - allows the user to enter a file name or select any existing \c{.abk} file - to load it into the address book. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part1 - - On Windows, for example, this function pops up a native file dialog, as - shown in the following screenshot. - - \image addressbook-tutorial-part6-load.png - - If \c fileName is not empty, again, we use a QFile object, \c file, and - attempt to open it in \l{QIODevice::}{ReadOnly} mode. Similar to our - implementation of \c saveToFile(), if this attempt is unsuccessful, we - display a QMessageBox to inform the user. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part2 - - Otherwise, we instantiate a QDataStream object, \c in, set its version as - above and read the serialized data into the \c contacts data structure. - The \c contacts object is emptied before data is read into it to simplify - the file reading process. A more advanced method would be to read the - contacts into a temporary QMap object, and copy over non-duplicate contacts - into \c contacts. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part3 - - To display the contacts that have been read from the file, we must first - validate the data obtained to ensure that the file we read from actually - contains address book contacts. If it does, we display the first contact; - otherwise, we display a QMessageBox to inform the user about the problem. - Lastly, we update the interface to enable and disable the push buttons - accordingly. -*/ - -/*! - \page tutorials-addressbook-part7.html - - \example tutorials/addressbook/part7 - \title Part 7 - Additional Features - - This part covers some additional features that make the address - book more convenient for the frequent user. - - \image addressbook-tutorial-part7-screenshot.png - - Although our address book is useful in isolation, it would be - better if we could exchange contact data with other applications. - The vCard format is a popular file format that can be used for - this purpose. Here we extend our address book client to allow - contacts to be exported to vCard \c{.vcf} files. - - \section1 Defining the AddressBook Class - - We add a QPushButton object, \c exportButton, and a corresponding public - slot, \c exportAsVCard() to our \c AddressBook class in the - \c addressbook.h file. - - \snippet tutorials/addressbook/part7/addressbook.h exportAsVCard() declaration - \dots - \snippet tutorials/addressbook/part7/addressbook.h exportButton declaration - - \section1 Implementing the AddressBook Class - - Within the \c AddressBook constructor, we connect \c{exportButton}'s - \l{QPushButton::clicked()}{clicked()} signal to \c exportAsVCard(). - We also add this button to our \c buttonLayout1, the layout responsible - for our panel of buttons on the right. - - In our \c exportAsVCard() function, we start by extracting the contact's - name into \c name. We declare \c firstName, \c lastName and \c nameList. - Next, we look for the index of the first white space in \c name. If there - is a white space, we split the contact's name into \c firstName and - \c lastName. Then, we replace the space with an underscore ("_"). - Alternately, if there is no white space, we assume that the contact only - has a first name. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part1 - - As with the \c saveToFile() function, we open a file dialog to let the user - choose a location for the file. Using the file name chosen, we create an - instance of QFile to write to. - - We attempt to open the file in \l{QIODevice::}{WriteOnly} mode. If this - process fails, we display a QMessageBox to inform the user about the - problem and return. Otherwise, we pass the file as a parameter to a - QTextStream object, \c out. Like QDataStream, the QTextStream class - provides functionality to read and write plain text to files. As a result, - the \c{.vcf} file generated can be opened for editing in a text editor. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part2 - - We then write out a vCard file with the \c{BEGIN:VCARD} tag, followed by - the \c{VERSION:2.1} tag. The contact's name is written with the \c{N:} - tag. For the \c{FN:} tag, which fills in the "File as" property of a vCard, - we have to check whether the contact has a last name or not. If the contact - does, we use the details in \c nameList to fill it. Otherwise, we write - \c firstName only. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part3 - - We proceed to write the contact's address. The semicolons in the address - are escaped with "\\", the newlines are replaced with semicolons, and the - commas are replaced with spaces. Lastly, we write the \c{ADR;HOME:;} - tag, followed by \c address and then the \c{END:VCARD} tag. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part4 - - In the end, a QMessageBox is displayed to inform the user that the vCard - has been successfully exported. - - \e{vCard is a trademark of the \l{http://www.imc.org} - {Internet Mail Consortium}}. -*/ diff --git a/doc/src/tutorials/modelview.qdoc b/doc/src/tutorials/modelview.qdoc deleted file mode 100644 index 9cbba47b60..0000000000 --- a/doc/src/tutorials/modelview.qdoc +++ /dev/null @@ -1,897 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page modelview.html - \ingroup tutorials - \startpage {index.html}{Qt Reference Documentation} - - \title Model/View Tutorial - \brief An introduction to ModelView programming - - Every UI developer should know about ModelView programming and the goal of - this tutorial is to provide you with an easily understandable introduction - to this topic. - - Table, list and tree widgets are components frequently used in GUIs. There - are 2 different ways how these widgets can access their data. The - traditional way involves widgets which include internal containers for - storing data. This approach is very intuitive, however, in many non-trivial - applications, it leads to data synchronization issues. - The second approach is model/view programming, in - which widgets do not maintain internal data containers. They access external - data through a standardized interface and therefore avoid data duplication. - This may seem complicated at first, but once you take a closer look, it is - not only easy to grasp, but the many benefits of model/view programming also - become clearer. - - \image treeview.png - - In the process, we will learn about some basic technologies provided by Qt, - such as: - - \list - \o The difference between standard and model/view widgets - \o Adapters betweeen forms and models - \o Developing a simple model/view application - \o Predefined models - \o Intermediate topics such as: - \list - \o Tree views - \o Selection - \o Delegates - \o Debugging with model test - \endlist - \endlist - - You will also learn whether your new application can be written easier with - model/view programming or if classic widgets will work just as well. - - This tutorial includes example code for you to edit and integrate into your - project. The tutorial's source code is located in Qt's - \c examples/tutorials/modelview directory. - - For more detailed information you may also want to look at the - \l{model-view-programming.html}{reference documentation} - - If you are completely new to Qt, please read \l{How to Learn Qt} if you - have not already done so. - - - \section1 1. Introduction - - Model/View is a technology used to separate data from views in widgets that - handle data sets. Standard widgets are not designed for separating data - from views and this is why Qt 4 has two different types of widgets. Both - types of widgets look the same, but they interact with data differently. - - \table - \row - \o Standard widgets use data that is part of the widget. - \o \image standardwidget.png - \row - \o View classes operate on external data (the model) - \o \image modelview.png - \endtable - - \section2 1.1 Standard Widgets - - Let's have a closer look at a standard table widget. A table widget is a 2D - array of the data elements that the user can change. The table widget can be - integrated into a program flow by reading and writing the data elements that - the table widget provides. - This method is very intuitive and useful in many applications, but displaying - and editing a database table with a standard table widget can be problematic. - Two copies of the data have to be coordinated: one outside the - widget; one inside the widget. The developer is responsible for - synchronizing both versions. Besides this, the tight coupling of presentation and data - makes it harder to write unit tests. - - \section2 1.2 Model/View to the Rescue - - Model/view stepped up to provide a solution that uses a more versatile - architecture. Model/view eliminates the data consistency problems that may - occur with standard widgets. Model/view also makes it easier to use more - than one view of the same data because one model can be passed on to many - views. The most important difference is that model/view widgets do not store - data behind the table cells. In fact, they operate directly from your data. - Since view classes do not know your data's structure, you need to provide a - wrapper to make your data conform to the QAbstractItemModel interface. A - view uses this interface to read from and write to your data. Any instance - of a class that implements QAbstractItemModel is said to be a model. Once - the view receives a pointer to a model, it will read and display its content - and be its editor. - - \section2 1.3 Overview of the Model/View Widgets - - Here is an overview of the model/view widgets and their corresponding - standard widgets. - - \table - \header - \o Widget - \o Standard Widget\br - (an item based convenience class) - \o Model/View View Class\br - (for use with external data) - \row - \o \inlineimage listview.png - \o \l QListWidget - \o \l QListView - \row - \o \inlineimage tableview.png - \o \l QTableWidget - \o \l QTableView - \row - \o \inlineimage treeview.png - \o \l QTreeWidget - \o \l QTreeView - \row - \o \inlineimage columnview.png - \o - \o \l QColumnView shows a tree as a hierarchy of lists - \row - \o \inlineimage modelview-combobox.png - \o {2, 1} \l QComboBox can work as both a view class and also - as a traditional widget - \endtable - - \section2 1.4 Using Adapters between Forms and Models - - Having adapters between forms and models can come in handy. - - We can edit data stored in tables directly from within the table itself, but - it's much more comfortable to edit data in text fields. There is no direct - model/view counterpart that separates data and views for widgets that - operate on one value (QLineEdit, QCheckBox ...) instead of a dataset, so we - need an adapter in order to connect the form to the source of data. - - \l QDataWidgetMapper is a great solution because it maps form widgets to a - table row and makes it very easy to build forms for database tables. - - \image widgetmapper.png - - Another example of an adapter is \l QCompleter. Qt has \l QCompleter for - providing auto-completions in Qt widgets such as \l QComboBox and, as shown - below, \l QLineEdit. \l QCompleter uses a model as its data source. - - \image qcompleter.png - - - \section1 2. A Simple Model/View Application - If you want to develop a model/view application, where should you start? - We recommend starting with a simple example and extending it step-by-step. - This makes understanding the architecture a lot easier. Trying to understand - the model/view architecture in detail before invoking the IDE has proven - to be less convenient for many developers. It is substantially easier to - start with a simple model/view application that has demo data. Give it a - try! Simply replace the data in the examples below with your own. - - Below are 7 very simple and independent applications that show different - sides of model/view programming. The source code can be found inside the - \c{examples/tutorials/modelview} directory. - - \section2 2.1 A Read Only Table - - We start with an application that uses a QTableView to show data. We will - add editing capabilities later. - - (file source: examples/tutorials/modelview/1_readonly/main.cpp) - \snippet examples/tutorials/modelview/1_readonly/main.cpp Quoting ModelView Tutorial - - We have the usual \l {modelview-part2-main-cpp.html}{main()} function: - - Here is the interesting part: We create an instance of MyModel and use - \l{QTableView::setModel()}{tableView.setModel(&myModel);} to pass a - pointer of it to to \l{QTableView}{tableView}. \l{QTableView}{tableView} - will invoke the methods of the pointer it has received to find out two - things: - - \list - \o How many rows and columns should be displayed. - \o What content should be printed into each cell. - \endlist - - The model needs some code to respond to this. - - We have a table data set, so let's start with QAbstractTableModel since it - is easier to use than the more general QAbstractItemModel. - - (file source: examples/tutorials/modelview/1_readonly/mymodel.h) - \snippet examples/tutorials/modelview/1_readonly/mymodel.h Quoting ModelView Tutorial - - QAbstractTableModel requires the implementation of three abstract methods. - - (file source: examples/tutorials/modelview/1_readonly/mymodel.cpp) - \snippet examples/tutorials/modelview/1_readonly/mymodel.cpp Quoting ModelView Tutorial - - The number of rows and columns is provided by - \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and - \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. When the view - has to know what the cell's text is, it calls the method - \l{QAbstractItemModel::data()}{MyModel::data()}. Row and column information - is specified with parameter \c index and the role is set to - \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are covered in the next - section. In our example, the data that should be displayed is generated. In - a real application, \c MyModel would have a member called \c MyData, which - serves as the target for all reading and writing operations. - - This small example demonstrates the passive nature of a model. The model - does not know when it will be used or which data is needed. It simply - provides data each time the view requests it. - - What happens when the model's data needs to be changed? How does the view - realize that data has changed and needs to be read again? The model has to - emit a signal that indicates what range of cells has changed. This will be - demonstrated in section 2.3. - - \section2 2.2 Extending the Read Only Example with Roles - - In addition to controlling what text the view displays, the model also - controls the text's appearance. When we slightly change the model, we get - the following result: \image readonlytable_role.png - - In fact, nothing except for the \l{QAbstractItemModel::}{data()} method - needs to be changed to set fonts, background colour, alignment and a - checkbox. - Below is the \l{QAbstractItemModel::data()}{data()} method that produces the - result shown above. The difference is that this time we use parameter int - role to return different pieces of information depending on its value. - - (file source: examples/tutorials/modelview/2_formatting/mymodel.cpp) - \snippet examples/tutorials/modelview/2_formatting/mymodel.cpp Quoting ModelView Tutorial - - Each formatting property will be requested from the model with a separate - call to the \l{QAbstractItemModel::data()}{data()} method. The \c role - parameter is used to let the model know which property is being requested: - - \table - \header - \o \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} - \o Meaning - \o Type - \row - \o \l{Qt::ItemDataRole}{}Qt::DisplayRole - \o text - \o QString - \row - \o \l{Qt::ItemDataRole}{Qt::FontRole} - \o font - \o QFont - \row - \o \l{Qt::ItemDataRole}{BackgroundRole} - \o brush for the background of the cell - \o QBrush - \row - \o \l{Qt::ItemDataRole}{Qt::TextAlignmentRole} - \o text alignment - \o \l{Qt::AlignmentFlag}{enum Qt::AlignmentFlag} - \row - \o {1, 3} \l{Qt::ItemDataRole}{Qt::CheckStateRole} - \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()}, - - sets checkboxes with \l{Qt::CheckState}{Qt::Checked} - - or \l{Qt::CheckState}{Qt::Unchecked} - \o {1, 3} \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} - \endtable - - Refer to the Qt namespace documentation to learn more about the - \l{Qt::ItemDataRole}{Qt::ItemDataRole} enum's capabilities. - - Now we need to determine how using a separated model impacts the - application's performance, so let's trace how often the view calls the - \l{QAbstractItemModel::}{data()} method. In order to track how often the - view calls the model, we have put a debug statement in the - \l{QAbstractItemModel::}{data()} method, which logs onto the error output - stream. In our small example, \l{QAbstractItemModel::}{data()} will be - called 42 times. - Each time you hover the cursor over the field, - \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for - each cell. That's why it is important to make sure that your data is - available when \l{QAbstractItemModel::}{data()} is invoked and expensive - lookup operations are cached. - - \section2 2.3 A Clock inside a Table Cell - - \image clock.png - - We still have a read only table, but this time the content changes every - second because we are showing the current time. - - (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) - \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_QVariant - - Something is missing to make the clock tick. We need to tell the view every - second that the time has changed and that it needs to be read again. We do - this with a timer. In the constructor, we set its interval to 1 second and - connect its timeout signal. - - (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) - \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_a - - Here is the corresponding slot: - - (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) - \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_b - - We ask the view to read the data in the top left cell again by emitting the - \l{QAbstractItemModel::}{dataChanged()} signal. Note that we did not - explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to the - view. This happened automatically when we called \l{QTableView::}{setModel()}. - - \section2 2.4 Setting up Headers for Columns and Rows - - Headers can be hidden via a view method: \c{tableView->verticalHeader()->hide();} - \image modelview-header.png - - The header content, however, is set via the model, so we reimplement the - \l{QAbstractItemModel::headerData()}{headerData()} method: - - (file source: examples/tutorials/modelview/4_headers/mymodel.cpp) - \snippet examples/tutorials/modelview/4_headers/mymodel.cpp quoting mymodel_c - - Note that method \l{QAbstractItemModel::headerData()}{headerData()} also has - a parameter role which has the same meaning as in - \l{QAbstractItemModel::data()}{MyModel::data()}. - - \section2 2.5 The Minimal Editing Example - - In this example, we are going to build an application that automatically - populates a window title with content by repeating values entered into table - cells. To be able to access the window title easily we put the QTableView in - a QMainWindow. - - The model decides whether editing capabilities are available. We only have - to modify the model in order for the available editing capabilities to be - enabled. This is done by reimplementing the following virtual methods: - \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}. - - (file source: examples/tutorials/modelview/5_edit/mymodel.h) - \snippet examples/tutorials/modelview/5_edit/mymodel.h Quoting ModelView Tutorial - - We use \c the two-dimensional array QString \c m_gridData to store our data. - This makes \c m_gridData the core of \c MyModel. The rest of \c MyModel acts - like a wrapper and adapts \c m_gridData to the QAbstractItemModel - interface. We have also introduced the \c editCompleted() signal, which - makes it possible to transfer the modified text to the window title. - - (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) - \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_e - - \l{QAbstractItemModel::setData()}{setData()} will be called each time the - user edits a cell. The \c index parameter tells us which field has been - edited and \c value provides the result of the editing process. The role - will always be set to \l Qt::EditRole because our cells only contain text. - If a checkbox were present and user permissions are set to allow the - checkbox to be selected, calls would also be made with the role set to - \l Qt::CheckStateRole. - - (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) - \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_f - - Various properties of a cell can be adjusted with - \l{QAbstractItemModel::flags()}{flags()}. - - Returning \l{Qt::ItemFlag}{Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled} - is enough to show an editor that a cell can be selected. - - If editing one cell modifies more data than the data in that particular - cell, the model must emit a \l{QAbstractItemModel::}{dataChanged()} signal - in order for the data that has been changed to be read. - - - \section1 3. Intermediate Topics - - \section2 3.1 TreeView - - You can convert the example above into an application with a tree view. - Simply replace QTableView with QTreeView, which results in a read/write - tree. No changes have to be made to the model. The tree won't have any - hierarchies because there aren't any hierarchies in the model itself. - - \image dummy_tree.png - - QListView, QTableView and QTreeView all use a model abstraction, which is a - merged list, table and tree. This makes it possible to use several different - types of view classes from the same model. - - \image list_table_tree.png - - This is how our example model looks so far: - - \image example_model.png - - We want to present a real tree. We have wrapped our data in the examples - above in order to make a model. This time we use QStandardItemModel, which - is a container for hierarchical data that also implements - QAbstractItemModel. To show a tree, QStandardItemModel must be populated - with \l{QStandardItem}s, which are able to hold all the standard properties - of items like text, fonts, checkboxes or brushes. - - \image tree_2_with_algorithm.png - - (file source: examples/tutorials/modelview/6_treeview/mainwindow.cpp) - \snippet examples/tutorials/modelview/6_treeview/mainwindow.cpp Quoting ModelView Tutorial - - We simply instantiate a QStandardItemModel and add a couple of - \l{QStandardItem}{QStandardItems} to the constructor. We can then make a - hierarchical data structure because a QStandardItem can hold other - \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within - the view. - - \section2 3.2 Working with Selections - - We want to access a selected item's content in order to output it into the - window title together with the hierarchy level. - - \image selection2.png - - So let's create a couple of items: - - (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) - \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_a - - Views manage selections within a separate selection model, which can be - retrieved with the \l{QAbstractItemView::}{selectionModel()} method. We - retrieve the selection Model in order to connect a slot to its - \l{QAbstractItemView::}{selectionChanged()} signal. - - (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) - \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_b - - We get the model index that corresponds to the selection by calling - \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()} - and we get the the field's string by using the model index. Then we just - calculate the item's \c hierarchyLevel. Top level items do not have parents - and the \l{QAbstractItemModel::}{parent()} method will return a default - constructed \l{QModelIndex}{QModelIndex()}. This is why we use the - \l{QAbstractItemModel::}{parent()} method to iterate to the top level while - counting the steps performed during iteration. - - The selection model (as shown above) can be retrieved, but it can also be - set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This - is how it's possible to have 3 view classes with synchronised selections - because only one instance of a selection model is used. To share a selection - model between 3 views use \l{QAbstractItemView::}{selectionModel()} and - assign the result to the second and third view class with - \l{QAbstractItemView::}{setSelectionModel()}. - - \section2 3.3 Predefined Models - - The typical way to use model/view is to wrap specific data to make it usable - with view classes. Qt, however, also provides predefined models for common - underlying data structures. If one of the available data structures is - suitable for your application, a predefined model can be a good choice. - - \table - \row - \o QStringListModel - \o Stores a list of strings - \row - \o QStandardItemModel - \o Stores arbitrary hierarchical items - \row - \o QFileSystemModel\br - QDirModel - \o Encapsulate the local file system - \row - \o QSqlQueryModel - \o Encapsulate an SQL result set - \row - \o QSqlTableModel - \o Encapsulates an SQL table - \row - \o QSqlRelationalTableModel - \o Encapsulates an SQL table with foreign keys - \row - \o QSortFilterProxyModel - \o Sorts and/or filters another model - - \endtable - - \section2 3.4 Delegates - - In all examples so far, data is presented as text or a checkbox in a cell - and is edited as text or a checkbox. The component that provides these - presentation and editing services is called a \e delegate. We are only just - beginning to work with the delegate because the view uses a default - delegate. But imagine that we want to have a different editor (e.g., a - slider or a drop down list) Or imagine that we want to present data as - graphics. - Let's take a look at an example called \l{Star Delegate Example}{Star - Delegate}, in which stars are used to show a rating: - - \image stardelegate.png - - The view has a \l{QAbstractItemView::}{setItemDelegate()} method that - replaces the default delegate and installs a custom delegate. - A new delegate can be written by creating a class that inherits from - QStyledItemDelegate. In order to write a delegate that displays stars and - has no input capabilities, we only need to override 2 methods. - - \code - class StarDelegate : public QStyledItemDelegate - { - Q_OBJECT - public: - StarDelegate(QWidget *parent = 0); - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const; - }; - \endcode - - \l{QStyledItemDelegate::}{paint()} draws stars depending on the content of - the underlying data. The data can be looked up by calling - \l{QModelIndex::data()}{index.data()}. The delegate's - \l{QAbstractItemDelegate::}{sizeHint()} method is used to obtain each - star's dimensions, so the the cell will provide enough height and width to - accommodate the stars. - - Writing custom delegates is the right choice if you want to show your data - with a custom graphical representation inside the grid of the view class. If - you want to leave the grid, you would not use a custom delegate but a custom - view class. - - Other references to delegates in Qt Documentation: - - \list - \o \l{Spin Box Delegate Example} - \o \l{QAbstractItemDelegate}{QAbstractItemDelegate Class Reference} - \o \l{QSqlRelationalDelegate}{QSqlRelationalDelegate Class Reference} - \o \l{QStyledItemDelegate}{QStyledItemDelegate Class Reference} - \o \l{QItemDelegate}{QItemDelegate Class Reference} - \endlist - - - \section2 3.5 Debugging with ModelTest - - The passive nature of models provides new challenges for programmers. - Inconsistencies in the model can cause the application to crash. Since the - model is hit by numerous calls from the view, it is hard to find out which - call has crashed the application and which operation has introduced the - problem. - - Qt Labs provides software called - \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest}, - which checks models while your programming is running. Every time the model - is changed, ModelTest scans the model and reports errors with an assert. - This is especially important for tree models, since their hierarchical - nature leaves many possibilities for subtle inconsistencies. - - Unlike view classes, ModelTest uses out of range indexes to test the model. - This means your application may crash with ModelTest even if it runs - perfectly without it. So you also need to handle all of the indexes that are - out of range when using ModelTest. - - - \section1 4. Good Sources of Additional Information - - \section2 4.1 Books - - Model/View programming is covered quite extensively in the documentation of - Qt but also in several good books. - - \list 1 - \o \bold{C++ GUI Programming with Qt 4} / Jasmin Blanchette, Mark Summerfield, - \e{Prentice Hall, 2nd edition}, ISBN 0-13-235416-0. Also available in - German: \bold{C++ GUI Programmierung mit Qt 4: Die offizielle Einführung}, - \e{Addison-Wesley}, ISBN 3-827327-29-6 - \o \bold{The Book of Qt4, The Art of Building Qt Applications} / Daniel Molkentin, - \e{Open Source Press}, ISBN 1-59327-147-6. - Translated from \bold{Qt 4, Einführung in die Applikationsentwicklung}, - \e{Open Source Press}, ISBN 3-937514-12-0. - \o \bold{Foundations of Qt Development} / Johan Thelin, \e{Apress}, ISBN 1-59059-831-8. - \o \bold{Advanced Qt Programming} / Mark Summerfield, \e{Prentice Hall}, ISBN 0-321-63590-6. - This book covers Model/View programming on more than 150 pages. - \endlist - - More information about these books is available on the - \l{Books about Qt Programming}{Qt Web site}. - - The following list provides an overview of example programs contained in the first three - books listed above. Some of them make very good templates for developing similar - applications. - - \table - \header - \o Example name - \o View class used - \o Model used - \o Aspects covered - \o - \row - \o Team Leaders - \o QListview - \o QStringListModel - \o - \o Book 1, Chapter 10, Figure 10.6 - \row - \o Directory Viewer - \o QTreeView - \o QDirModel - \o - \o Book 1, Chapter 10, Figure 10.7 - \row - \o Color Names - \o QListView - \o QSortFilterProxyModel - applied to QStringListModel - \o - \o Book 1, Chapter 10, Figure 10.8 - \row - \o Currencies - \o QTableView - \o custom model based on - QAbstractTableModel - \o Read only - \o Book 1, Chapter 10, Figure 10.10 - \row - \o Cities - \o QTableView - \o Custom model based on - QAbstractTableModel - \o Read / write - \o Book 1, Chapter 10, Figure 10.12 - \row - \o Boolean Parser - \o QTreeView - \o Custom model based on - QAbstractItemModel - \o Read only - \o Book 1, Chapter 10, Figure 10.14 - \row - \o Track Editor - \o {2, 1} QTableWidget - \o Custom delegate providing a custom editor - \o Book 1, Chapter 10, Figure 10.15 - - \row - \o Four directory views - \o QListView - QTableView - QTreeView - \o QDirModel - \o Demonstrates the use of multiple views - \o Book2, Chapter 8.2 - \row - \o Address Book - \o QListView - QTableView - QTreeView - \o Custom model based on - QAbstractTableModel - \o Read / write - \o Book2, Chapter 8.4 - \row - \o Address Book with sorting - \o - \o QProxyModel - \o Introducing sort and filter capabilities - \o Book2, Chapter 8.5 - \row - \o Address Book - with checkboxes - \o - \o - \o Introducing checkboxes in model/view - \o Book2, Chapter 8.6 - \row - \o Address Book with transposed grid - \o - \o Custom proxy Model based on QAbstractProxyModel - \o Introducing a custom model - \o Book2, Chapter 8.7 - \row - \o Address Book with drag and drop - \o - \o - \o Introducing drag and drop support - \o Book2, Chapter 8.8 - \row - \o Address Book with custom editor - \o - \o - \o Introducing custom delegates - \o Book2, Chapter 8.9 - \row - \o Views - \o QListView - QTableView - QTreeView - \o QStandardItemModel - \o Read only - \o Book 3, Chapter 5, figure 5-3 - \row - \o Bardelegate - \o QTableView - \o - \o Custom delegate for presentation based on QAbstractItemDelegate - \o Book 3, Chapter 5, figure 5-5 - \row - \o Editdelegate - \o QTableView - \o - \o Custom delegate for editing based on QAbstractItemDelegate - \o Book 3, Chapter 5, figure 5-6 - \row - \o Singleitemview - \o Custom view based on QAbstractItemView - \o - \o Custom view - \o Book 3, - Chapter 5, - figure 5-7 - \row - \o listmodel - \o QTableView - \o Custom Model based on QAbstractTableModel - \o Read only - \o Book 3, Chapter 5, Figure 5-8 - \row - \o treemodel - \o QTreeView - \o Custom Model based on QAbstractItemModel - \o Read only - \o Book 3, Chapter 5, Figure 5-10 - \row - \o edit integers - \o QListView - \o Custom Model based on QAbstractListModel - \o Read / write - \o Book 3, Chapter 5, Listing 5-37, Figure 5-11 - \row - \o sorting - \o QTableView - \o QSortFilterProxyModel applied to QStringListModel - \o Demonstrates sorting - \o Book 3, Chapter 5, Figure 5-12 - \endtable - - - \section2 4.2 Qt Documentation - - Qt 5.0 comes with 19 examples for model/view. - The examples can be found on the \l{Item Views Examples} page. - - \table - \header - \o Example name - \o View class used - \o Model used - \o Aspects covered - \row - \o Address Book - \o QTableView - \o QAbstractTableModel - QSortFilterProxyModel - \o Usage of QSortFilterProxyModel to generate different - subsets from one data pool - \row - \o Basic Sort/Filter Model - \o QTreeView - \o QStandardItemModel - QSortFilterProxyModel - \o - \row - \o Chart - \o Custom view - \o QStandardItemModel - \o Designing custom views that cooperate with selection models - \row - \o Color Editor Factory - \o {2, 1} QTableWidget - \o Enhancing the standard delegate with a new custom editor to choose colours - \row - \o Combo Widget Mapper - \o QDataWidgetMapper to map QLineEdit, QTextEdit and QComboBox - \o QStandardItemModel - \o Shows how a QComboBox can serve as a view class - \row - \o Custom Sort/Filter Model - \o QTreeView - \o QStandardItemModel - QSortFilterProxyModel - \o Subclass QSortFilterProxyModel for advanced sorting and filtering - \row - \o Dir View - \o QTreeView - \o QDirModel - \o Very small example to demonstrate how to assign a model to a view - \row - \o Editable Tree Model - \o QTreeView - \o Custom tree model - \o Comprehensive example for working with trees, demonstrates - editing cells and tree structure with an underlying custom - model - \row - \o Fetch More - \o QListView - \o Custom list model - \o Dynamically changing model - \row - \o Frozen Column - \o QTableView - \o QStandardItemModel - \o - \row - \o Interview - \o Multiple - \o Custom item model - \o Multiple views - \row - \o Pixelator - \o QTableView - \o Custom table model - \o Implementation of a custom delegate - \row - \o Puzzle - \o QListView - \o Custom list model - \o Model/view with drag and drop - \row - \o Simple DOM Model - \o QTreeView - \o Custom tree model - \o Read only example for a custom tree model - \row - \o Simple Tree Model - \o QTreeView - \o Custom tree model - \o Read only example for a custom tree model - \row - \o Simple Widget Mapper - \o QDataWidgetMapper to map QLineEdit, QTextEdit and QSpinBox - \o QStandardItemModel - \o Basic QDataWidgetMapper usage - \row - \o Spin Box Delegate - \o QTableView - \o QStandardItemModel - \o Custom delegate that uses a spin box as a cell editor - \row - \o Spreadsheet - \o {2, 1} QTableView - \o Custom delegates - \row - \o Star Delegate - \o {2, 1} QTableWidget - \o Comprehensive custom delegate example. - \endtable - - A \l{Model/View Programming}{reference document} for model/view technology - is also available. -*/ - -/*! - \page modelview-part2-main-cpp.html - \title main.cpp - \quotefile tutorials/modelview/1_readonly/main.cpp -*/ diff --git a/doc/src/tutorials/threads.qdoc b/doc/src/tutorials/threads.qdoc deleted file mode 100644 index 09707f5dfc..0000000000 --- a/doc/src/tutorials/threads.qdoc +++ /dev/null @@ -1,572 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page thread-basics.html - \ingroup tutorials - \startpage {index.html}{Qt Reference Documentation} - - \title Threading Basics - \brief An introduction to threads - - \section1 What Are Threads? - - Threads are about doing things in parallel, just like processes. So how do - threads differ from processes? While you are making calculations on a - spreadsheet, there may also be a media player running on the same desktop - playing your favorite song. Here is an example of two processes working in - parallel: one running the spreadsheet program; one running a media player. - Multitasking is a well known term for this. A closer look at the media - player reveals that there are again things going on in parallel within one - single process. While the media player is sending music to the audio driver, - the user interface with all its bells and whistles is being constantly - updated. This is what threads are for \mdash concurrency within one single - process. - - So how is concurrency implemented? Parallel work on single core CPUs is an - illusion which is somewhat similar to the illusion of moving images in - cinema. - For processes, the illusion is produced by interrupting the processor's - work on one process after a very short time. Then the processor moves on to - the next process. In order to switch between processes, the current program - counter is saved and the next processor's program counter is loaded. This - is not sufficient because the same needs to be done with registers and - certain architecture and OS specific data. - - Just as one CPU can power two or more processes, it is also possible to let - the CPU run on two different code segments of one single process. When a - process starts, it always executes one code segment and therefore the - process is said to have one thread. However, the program may decide to - start a second thread. Then, two different code sequences are processed - simultaneously inside one process. Concurrency is achieved on single core - CPUs by repeatedly saving program counters and registers then loading the - next thread's program counters and registers. No cooperation from the - program is required to cycle between the active threads. A thread may be in - any state when the switch to the next thread occurs. - - The current trend in CPU design is to have several cores. A typical - single-threaded application can make use of only one core. However, a - program with multiple threads can be assigned to multiple cores, making - things happen in a truly concurrent way. As a result, distributing work - to more than one thread can make a program run much faster on multicore - CPUs because additional cores can be used. - - \section2 GUI Thread and Worker Thread - - As mentioned, each program has one thread when it is started. This thread - is called the "main thread" (also known as the "GUI thread" in Qt - applications). The Qt GUI must run in this thread. All widgets and several - related classes, for example QPixmap, don't work in secondary threads. - A secondary thread is commonly referred to as a "worker thread" because it - is used to offload processing work from the main thread. - - \section2 Simultaneous Access to Data - - Each thread has its own stack, which means each thread has its own call - history and local variables. Unlike processes, threads share the same - address space. The following diagram shows how the building blocks of - threads are located in memory. Program counter and registers of inactive - threads are typically kept in kernel space. There is a shared copy of the - code and a separate stack for each thread. - - \image threadvisual-example.png "Thread visualization" - - If two threads have a pointer to the same object, it is possible that both - threads will access that object at the same time and this can potentially - destroy the object's integrity. It's easy to imagine the many things that - can go wrong when two methods of the same object are executed - simultaneously. - - Sometimes it is necessary to access one object from different threads; - for example, when objects living in different threads need to communicate. - Since threads use the same address space, it is easier and faster for - threads to exchange data than it is for processes. Data does not have to be - serialized and copied. Passing pointers is possible, but there must be a - strict coordination of what thread touches which object. Simultaneous - execution of operations on one object must be prevented. There are several - ways of achieving this and some of them are described below. - - So what can be done safely? All objects created in a thread can be used - safely within that thread provided that other threads don't have references - to them and objects don't have implicit coupling with other threads. Such - implicit coupling may happen when data is shared between instances as with - static members, singletons or global data. Familiarize yourself with the - concept of \l{Reentrancy and Thread-Safety}{thread safe and reentrant} - classes and functions. - - \section1 Using Threads - - There are basically two use cases for threads: - - \list - \o Make processing faster by making use of multicore processors. - \o Keep the GUI thread or other time critical threads responsive by - offloading long lasting processing or blocking calls to other threads. - \endlist - - \section2 When to Use Alternatives to Threads - - Developers need to be very careful with threads. It is easy to start other - threads, but very hard to ensure that all shared data remains consistent. - Problems are often hard to find because they may only show up once in a - while or only on specific hardware configurations. Before creating threads - to solve certain problems, possible alternatives should be considered. - - \table - \header - \o Alternative - \o Comment - \row - \o QEventLoop::processEvents() - \o Calling QEventLoop::processEvents() repeatedly during a - time-consuming calculation prevents GUI blocking. However, this - solution doesn't scale well because the call to processEvents() may - occur too often, or not often enough, depending on hardware. - \row - \o QTimer - \o Background processing can sometimes be done conveniently using a - timer to schedule execution of a slot at some point in the future. - A timer with an interval of 0 will time out as soon as there are no - more events to process. - \row - \o QSocketNotifier QNetworkAccessManager QIODevice::readyRead() - \o This is an alternative to having one or multiple threads, each with - a blocking read on a slow network connection. As long as the - calculation in response to a chunk of network data can be executed - quickly, this reactive design is better than synchronous waiting in - threads. Reactive design is less error prone and energy efficient - than threading. In many cases there are also performance benefits. - \endtable - - In general, it is recommended to only use safe and tested paths and to - avoid introducing ad-hoc threading concepts. QtConcurrent provides an easy - interface for distributing work to all of the processor's cores. The - threading code is completely hidden in the QtConcurrent framework, so you - don't have to take care of the details. However, QtConcurrent can't be used - when communication with the running thread is needed, and it shouldn't be - used to handle blocking operations. - - \section2 Which Qt Thread Technology Should You Use? - - Sometimes you want to do more than just running a method in the context of - another thread. You may want to have an object which lives in another - thread that provides a service to the GUI thread. Maybe you want another - thread to stay alive forever to poll hardware ports and send a signal to - the GUI thread when something noteworthy has happened. Qt provides - different solutions for developing threaded applications. The right - solution depends on the purpose of the new thread as well as on the - thread's lifetime. - - \table - \header - \o Lifetime of thread - \o Development task - \o Solution - \row - \o One call - \o Run one method within another thread and quit the thread when the - method is finished. - \o Qt provides different solutions: - \list - \o Write a function and run it with QtConcurrent::run() - \o Derive a class from QRunnable and run it in the global thread - pool with QThreadPool::globalInstance()->start() - \o Derive a class from QThread, reimplement the QThread::run() - method and use QThread::start() to run it. - \endlist - - \row - \o One call - \o Operations are to be performed on all items of a container. - Processing should be performed using all available cores. A common - example is to produce thumbnails from a list of images. - \o QtConcurrent provides the \l{QtConcurrent::}{map()} function for - applying operations on every container element, - \l{QtConcurrent::}{filter()} for selecting container elements, and - the option of specifying a reduce function for combining the - remaining elements. - \row - \o One call - \o A long running operation has to be put in another thread. During the - course of processing, status information should be sent to the GUI - thread. - \o Use QThread, reimplement run and emit signals as needed. Connect the - signals to the GUI thread's slots using queued signal/slot - connections. - - \row - \o Permanent - \o Have an object living in another thread and let it perform different - tasks upon request. - This means communication to and from the worker thread is required. - \o Derive a class from QObject and implement the necessary slots and - signals, move the object to a thread with a running event loop and - communicate with the object over queued signal/slot connections. - \row - \o Permanent - \o Have an object living in another thread, let the object perform - repeated tasks such as polling a port and enable communication with - the GUI thread. - \o Same as above but also use a timer in the worker thread to implement - polling. However, the best solution for polling is to avoid it - completely. Sometimes using QSocketNotifier is an alternative. - \endtable - - - \section1 Qt Thread Basics - - QThread is a very convenient cross platform abstraction of native platform - threads. Starting a thread is very simple. Let us look at a short piece of - code that generates another thread which says hello in that thread and then - exits. - - \snippet examples/tutorials/threads/hellothread/hellothread.h 1 - - We derive a class from QThread and reimplement the \l{QThread::}{run()} - method. - - \snippet examples/tutorials/threads/hellothread/hellothread.cpp 1 - - The run method contains the code that will be run in a separate thread. In - this example, a message containing the thread ID will be printed. - QThread::start() will call the method in another thread. - - \snippet examples/tutorials/threads/hellothread/main.cpp 1 - - To start the thread, our thread object needs to be instantiated. The - \l{QThread::}{start()} method creates a new thread and calls the - reimplemented \l{QThread::}{run()} method in this new thread. Right after - \l{QThread::}{start()} is called, two program counters walk through the - program code. The main function starts with only the GUI thread running and - it should terminate with only the GUI thread running. Exiting the program - when another thread is still busy is a programming error, and therefore, - wait is called which blocks the calling thread until the - \l{QThread::}{run()} method has completed. - - This is the result of running the code: - - \badcode - hello from GUI thread 3079423696 - hello from worker thread 3076111216 - \endcode - - - \section2 QObject and Threads - - A QObject is said to have a \e{thread affinity} or, in other words, that it - lives in a certain thread. This means that, at creation time, QObject saves - a pointer to the current thread. This information becomes relevant when an - event is posted with \l{QCoreApplication::}{postEvent()}. The event will be - put in the corresponding thread's event loop. If the thread where the - QObject lives doesn't have an event loop, the event will never be delivered. - - To start an event loop, \l{QThread::}{exec()} must be called inside - \l{QThread::}{run()}. Thread affinity can be changed using - \l{QObject::}{moveToThread()}. - - As mentioned above, developers must always be careful when calling objects' - methods from other threads. Thread affinity does not change this situation. - Qt documentation marks several methods as thread-safe. - \l{QCoreApplication::}{postEvent()} is a noteworthy example. A thread-safe - method may be called from different threads simultaneously. - - In cases where there is usually no concurrent access to methods, calling - non-thread-safe methods of objects in other threads may work thousands - of times before a concurrent access occurs, causing unexpected behavior. - Writing test code does not entirely ensure thread correctness, but it is - still important. - On Linux, Valgrind and Helgrind can help detect threading errors. - - The anatomy of QThread is quite interesting: - - \list - \o QThread does not live in the new thread where \l{QThread::}{run()} is - executed. It lives in the old thread. - \o Most QThread methods are the thread's control interface and are meant to - be called from the old thread. Do not move this interface to the newly - created thread using \l{QObject::}{moveToThread()}; i.e., calling - \l{QObject::moveToThread()}{moveToThread(this)} is regarded as bad - practice. - \o \l{QThread::}{exec()} and the static methods - \l{QThread::}{usleep()}, \l{QThread::}{msleep()}, - \l{QThread::}{sleep()} are meant to be called from the newly created - thread. - \o Additional members defined in the QThread subclass are - accessible by both threads. The developer is responsible for - coordinating access. A typical strategy is to set the members before - \l{QThread::}{start()} is called. Once the worker thread is running, - the main thread should not touch the additional members anymore. After - the worker has terminated, the main thread can access the additional - members again. This is a convenient strategy for passing parameters to a - thread before it is started as well as for collecting the result once it - has terminated. - \endlist - - A QObject's parent must always be in the same thread. This has a surprising - consequence for objects generated within the \l{QThread::}{run()} method: - - \code - void HelloThread::run() - { - QObject *object1 = new QObject(this); //error, parent must be in the same thread - QObject object2; // OK - QSharedPointer object3(new QObject); // OK - } - \endcode - - \section2 Using a Mutex to Protect the Integrity of Data - - A mutex is an object that has \l{QMutex::}{lock()} and \l{QMutex::}{unlock()} - methods and remembers if it is already locked. A mutex is designed to be - called from multiple threads. \l{QMutex::}{lock()} returns immediately if - the mutex is not locked. The next call from another thread will find the - mutex in a locked state and then \l{QMutex::}{lock()} will block the thread - until the other thread calls \l{QMutex::}{unlock()}. This functionality can - make sure that a code section will be executed by only one thread at a time. - - The following line sketches how a mutex can be used to make a method - thread-safe: - - \code - void Worker::work() - { - this->mutex.lock(); // first thread can pass, other threads will be blocked here - doWork(); - this->mutex.unlock(); - } - \endcode - - What happens if one thread does not unlock a mutex? The result can be a - frozen application. In the example above, an exception might be thrown and - \c{mutex.unlock()} will never be reached. To prevent problems like this, - QMutexLocker should be used. - - \code - void Worker::work() - { - QMutexLocker locker(&mutex); // Locks the mutex and unlocks when locker exits the scope - doWork(); - } - \endcode - - This looks easy, but mutexes introduce a new class of problems: deadlocks. - A deadlock happens when a thread waits for a mutex to become unlocked, but - the mutex remains locked because the owning thread is waiting for the first - thread to unlock it. The result is a frozen application. Mutexes can be - used to make a method thread safe. Most Qt methods aren't thread safe - because there is always a performance penalty when using mutexes. - - It isn't always possible to lock and unlock a mutex in a method. Sometimes - the need to lock spans several calls. For example, modifying a container - with an iterator requires a sequence of several calls which should not be - interrupted by other threads. In such a scenario, locking can be achieved - with a mutex that is kept outside of the object to be manipulated. With an - external mutex, the duration of locking can be adjusted to the needs of the - operation. One disadvantage is that external mutexes aid locking, but do - not enforce it because users of the object may forget to use it. - - \section2 Using the Event Loop to Prevent Data Corruption - - The event loops of Qt are a very valuable tool for inter-thread - communication. Every thread may have its own event loop. A safe way of - calling a slot in another thread is by placing that call in another - thread's event loop. This ensures that the target object finishes the - method that is currently running before another method is started. - - So how is it possible to put a method invocation in an event loop? Qt has - two ways of doing this. One way is via queued signal-slot connections; the - other way is to post an event with QCoreApplication::postEvent(). A queued - signal-slot connection is a signal slot connection that is executed - asynchronously. The internal implementation is based on posted events. The - arguments of the signal are put into the event loop and the signal method - returns immediately. - - The connected slot will be executed at a time which depends on what else is - in the event loop. - - Communication via the event loop eliminates the deadlock problem we face - when using mutexes. This is why we recommend using the event loop rather - than locking an object using a mutex. - - \section2 Dealing with Asynchronous Execution - - One way to obtain a worker thread's result is by waiting for the thread - to terminate. In many cases, however, a blocking wait isn't acceptable. The - alternative to a blocking wait are asynchronous result deliveries with - either posted events or queued signals and slots. This generates a certain - overhead because an operation's result does not appear on the next source - line, but in a slot located somewhere else in the source file. Qt - developers are used to working with this kind of asynchronous behavior - because it is much similar to the kind of event-driven programming used in - GUI applications. - - \section1 Examples - - This tutorial comes with examples for Qt's three basic ways of working with - threads. Two more examples show how to communicate with a running thread - and how a QObject can be placed in another thread, providing service to the - main thread. - - \list - \o Using QThread as shown \l{Qt thread basics}{above} - \o \l{Example 1: Using the Thread Pool}{Using the global QThreadPool} - \o \l{Example 2: Using QtConcurrent}{Using QtConcurrent} - \o \l{Example 3: Clock}{Communication with the GUI thread} - \o \l{Example 4: A Permanent Thread}{A permanent QObject in another thread - provides service to the main thread} - \endlist - - The following examples can all be compiled and run independently. The source can - be found in the examples directory: examples/tutorials/threads/ - - \section2 Example 1: Using the Thread Pool - - Creating and destroying threads frequently can be expensive. To avoid the - cost of thread creation, a thread pool can be used. A thread pool is a - place where threads can be parked and fetched. We can write the same - "hello thread" program as \l{Qt Thread Basics}{above} using the global - thread pool. We derive a class from QRunnable. The code we want to run in - another thread needs to be placed in the reimplemented QRunnable::run() - method. - - \snippet examples/tutorials/threads/hellothreadpool/hellothreadpool.cpp 1 - - We instantiate Work in main(), locate the global thread pool and use the - QThreadPool::start() method. Now the thread pool runs our worker in another - thread. Using the thread pool has a performance advantage because threads - are not destroyed after they have finished running. They are kept in a pool - and wait to be used again later. - - \section2 Example 2: Using QtConcurrent - - \snippet examples/tutorials/threads/helloconcurrent/helloconcurrent.cpp 1 - - We write a global function hello() to implement the work. QtConcurrent::run() - is used to run the function in another thread. The result is a QFuture. - QFuture provides a method called \l{QFuture::}{waitForFinished()}, which - blocks until the calculation is completed. The real power of QtConcurrent - becomes visible when data can be made available in a container. QtConcurrent - provides several functions that are able to process itemized data on all - available cores simultaneously. The use of QtConcurrent is very similar to - applying an STL algorithm to an STL container. - \l{examples-threadandconcurrent.html}{QtConcurrent Map} is a very short and - clear example about how a container of images can be scaled on all available - cores. The image scaling example uses the blocking variants of the functions - used. For every blocking function there is also a non-blocking, asynchronous - counterpart. Getting results asynchronously is implemented with QFuture and - QFutureWatcher. - - \section2 Example 3: Clock - - \image thread_clock.png "clock" - - We want to produce a clock application. The application has a GUI and a - worker thread. The worker thread checks every 10 milliseconds what time it - is. If the formatted time has changed, the result will be sent to the GUI - thread where it is displayed. - - Of course, this is an overly complicated way of designing a clock and, - actually, a separate thread is unnecessary. We would be better off placing - the timer in the main thread because the calculation made in the timer slot - is very short-lived. This example is purely for instructional use and shows - how to communicate from a worker thread to a GUI thread. Note that - communication in this direction is easy. We only need to add a signal - to QThread and make a queued signal/slot connection to the main thread. - Communication from the GUI to the worker thread is shown in the next - example. - - \snippet examples/tutorials/threads/clock/main.cpp 1 - - We've connected the \c clockThread with the label. The connection must be a - queued signal-slot connection because we want to put the call in the event - loop. - - \snippet examples/tutorials/threads/clock/clockthread.h 1 - - We have derived a class from QThread and declared the \c sendTime() signal. - - \snippet examples/tutorials/threads/clock/clockthread.cpp 1 - - The trickiest part of this example is that the timer is connected to its - slot via a direct connection. A default connection would produce a queued - signal-slot connection because the connected objects live in different - threads; remember that QThread does not live in the thread it creates. - - Still it is safe to access ClockThread::timerHit() from the worker thread - because ClockThread::timerHit() is private and only touches local variables - and a private member that isn't touched by public methods. - QDateTime::currentDateTime() isn't marked as thread-safe in Qt - documentation, however we can get away with using it in this small - example because we know that the QDateTime::currentDateTime() static - method isn't used in any other threads. - - \section2 Example 4: A Permanent Thread - - This example shows how it is possible to have a QObject in a worker thread - that accepts requests from the GUI thread, does polling using a timer and - continuously reports results back to the GUI thread. The actual work - including the polling must be implemented in a class derived from QObject. - We have called this class \c WorkerObject in the code shown below. The - thread-specific code is hidden in a class called \c Thread, derived from - QThread. - \c Thread has two additional public members. The \c launchWorker() member - takes the worker object and moves it to another thread with a started event - loop. - The call blocks for a very short moment until the thread creation operation - is completed, allowing the worker object to be used again on the next line. - The \c Thread class's code is short but somewhat involved, so we only show - how to use the class. - - \snippet examples/tutorials/threads/movedobject/main.cpp 1 - - QMetaObject::invokeMethod() calls a slot via the event loop. The worker - object's methods should not be called directly after the object has been - moved to another thread. We let the worker thread do some work and polling, - and use a timer to shut the application down after 3 seconds. Shutting the - worker down needs some care. We call \c{Thread::stop()} to exit the event - loop. We wait for the thread to terminate and, after this has occurred, we - delete the worker. - - \section1 Digging Deeper - - Threading is a very complicated subject. Qt offers more classes for - threading than we have presented in this tutorial. The following materials - can help you go into the subject in more depth: - - \list - \o Good video tutorials about threads with Qt can be found in the material - from the \l{Training Day at Qt Developer Days 2009}. - \o The \l{Thread Support in Qt} document is a good starting point into - the reference documentation. - \o Qt comes with several additional examples for - \l{Threading and Concurrent Programming Examples}{QThread and QtConcurrent}. - \o Several good books describe how to work with Qt threads. The most - extensive coverage can be found in \e{Advanced Qt Programming} by Mark - Summerfield, Prentice Hall - roughly 70 of 500 pages cover QThread and - QtConcurrent. - \endlist -*/ diff --git a/doc/src/tutorials/widgets-tutorial.qdoc b/doc/src/tutorials/widgets-tutorial.qdoc deleted file mode 100644 index a90c01447a..0000000000 --- a/doc/src/tutorials/widgets-tutorial.qdoc +++ /dev/null @@ -1,249 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page widgets-tutorial.html - \ingroup tutorials - \title Widgets Tutorial - \brief This tutorial covers basic usage of widgets and layouts, showing how - they are used to build GUI applications. - - \section1 Introduction - - Widgets are the basic building blocks for graphical user interface - (GUI) applications built with Qt. Each GUI component (e.g. - buttons, labels, text editor) is a \l{QWidget}{widget} that is - placed somewhere within a user interface window, or is displayed - as an independent window. Each type of widge is provided by a - subclass of QWidget, which is itself a subclass of QObject. - - QWidget is not an abstract class. It can be used as a container - for other widgets, and it can be subclassed with minimal effort to - create new, custom widgets. QWidget is often used to create a - window inside which other \l{QWidget}s are placed. - - As with \l{QObject}s, \l{QWidget}s can be created with parent - objects to indicate ownership, ensuring that objects are deleted - when they are no longer used. With widgets, these parent-child - relationships have an additional meaning: Each child widget is - displayed within the screen area occupied by its parent widget. - This means that when you delete a window widget, all the child - widgets it contains are also deleted. - - \section1 Writing a main Function - - Many of the GUI examples provided with Qt follow the pattern of - having a \c{main.cpp} file, which contains the standard code to - initialize the application, plus any number of other source/header - files that contain the application logic and custom GUI components. - - A typical \c main() function in \c{main.cpp} looks like this: - - \snippet doc/src/snippets/widgets-tutorial/template.cpp main.cpp body - - First, a QApplication object is constructed, which can be - configured with arguments passed in from the command line. After - the widgets have been created and shown, QApplication::exec() is - called to start Qt's event loop. Control passes to Qt until this - function returns. Finally, \c{main()} returns the value returned - by QApplication::exec(). - - \section1 Simple widget examples - - Each of theses simple widget examples is written entirely within - the \c main() function. - - \list - \o \l {tutorials/widgets/toplevel} {Creating a window} - - \o \l {tutorials/widgets/childwidget} {Creating child widgets} - - \o \l {tutorials/widgets/windowlayout} {Using layouts} - - \o \l {tutorials/widgets/nestedlayouts} {Nested layouts} - \endlist - - \section1 Real world widget examples - - In these \l{Widget examples} {more advanced examples}, the code - that creates the widgets and layouts is stored in other files. For - example, the GUI for a main window may be created in the - constructor of a QMainWindow subclass. - - \section1 Building The Examples - - If you installed a binary package to get Qt, or if you compiled Qt - yourself, the examples described in this tutorial should already - be built and ready to run. If you wish to modify and recompile - them, follow these steps: - - \list 1 - - \o From a command prompt, enter the directory containing the - example you have modified. - - \o Type \c qmake and press \key{Return}. If this doesn't work, - make sure that the executable is on your path, or enter its - full location. - - \o On Linux/Unix and Mac OS X, type \c make and press - \key{Return}; on Windows with Visual Studio, type \c nmake and - press \key{Return}. - - \endlist - - An executable file is created in the current directory. On - Windows, this file may be located in a \c debug or \c release - subdirectory. You can run this executable to see the example code - at work. -*/ - -/*! - \example tutorials/widgets/toplevel - \title Widgets Tutorial - Creating a Window - - If a widget is created without a parent, it is treated as a window, or - \e{top-level widget}, when it is shown. Since it has no parent object to - ensure that it is deleted when no longer needed, it is up to the - developer to keep track of the top-level widgets in an application. - - In the following example, we use QWidget to create and show a window with - a default size: - - \div {class="qt-code"} - \table - \row - \o \snippet tutorials/widgets/toplevel/main.cpp main program - \o \inlineimage widgets-tutorial-toplevel.png - \endtable - \enddiv - - To create a real GUI, we need to place widgets inside the window. To do - this, we pass a QWidget instance to a widget's constructor, as we will - demonstrate in the next part of this tutorial. - -*/ - -/*! - \example tutorials/widgets/childwidget - \title Widgets Tutorial - Child Widgets - - We can add a child widget to the window created in the previous example by - passing \c window as the parent to its constructor. In this case, we add a - button to the window and place it in a specific location: - - \div {class="qt-code"} - \table - \row - \o \snippet tutorials/widgets/childwidget/main.cpp main program - \o \inlineimage widgets-tutorial-childwidget.png - \endtable - \enddiv - - The button is now a child of the window and will be deleted when the - window is destroyed. Note that hiding or closing the window does not - automatically destroy it. It will be destroyed when the example exits. -*/ - -/*! - \example tutorials/widgets/windowlayout - \title Widgets Tutorial - Using Layouts - - Usually, child widgets are arranged inside a window using layout objects - rather than by specifying positions and sizes explicitly. Here, we - construct a label and line edit widget that we would like to arrange - side-by-side. - - \div {class="qt-code"} - \table - \row - \o \snippet tutorials/widgets/windowlayout/main.cpp main program - \o \inlineimage widgets-tutorial-windowlayout.png - \endtable - \enddiv - - The \c layout object we construct manages the positions and sizes of - widgets supplied to it with the \l{QHBoxLayout::}{addWidget()} function. - The layout itself is supplied to the window itself in the call to - \l{QWidget::}{setLayout()}. Layouts are only visible through the effects - they have on the widgets (and other layouts) they are responsible for - managing. - - In the example above, the ownership of each widget is not immediately - clear. Since we construct the widgets and the layout without parent - objects, we would expect to see an empty window and two separate windows - containing a label and a line edit. However, when we tell the layout to - manage the label and line edit and set the layout on the window, both the - widgets and the layout itself are ''reparented'' to become children of - the window. -*/ - -/*! - \example tutorials/widgets/nestedlayouts - \title Widgets Tutorial - Nested Layouts - - Just as widgets can contain other widgets, layouts can be used to provide - different levels of grouping for widgets. Here, we want to display a - label alongside a line edit at the top of a window, above a table view - showing the results of a query. - - We achieve this by creating two layouts: \c{queryLayout} is a QHBoxLayout - that contains QLabel and QLineEdit widgets placed side-by-side; - \c{mainLayout} is a QVBoxLayout that contains \c{queryLayout} and a - QTableView arranged vertically. - - \div {class="qt-code"} - \table - \row - \o \snippet tutorials/widgets/nestedlayouts/main.cpp first part - \snippet tutorials/widgets/nestedlayouts/main.cpp last part - \o \inlineimage widgets-tutorial-nestedlayouts.png - \endtable - \enddiv - - Note that we call the \c{mainLayout}'s \l{QBoxLayout::}{addLayout()} - function to insert the \c{queryLayout} above the \c{resultView} table. - - We have omitted the code that sets up the model containing the data shown - by the QTableView widget, \c resultView. For completeness, we show this below. - - As well as QHBoxLayout and QVBoxLayout, Qt also provides QGridLayout - and QFormLayout classes to help with more complex user interfaces. - These can be seen if you run \l{Qt Designer}. - - \section1 Setting up the Model - - In the code above, we did not show where the table's data came from - because we wanted to concentrate on the use of layouts. Here, we see - that the model holds a number of items corresponding to rows, each of - which is set up to contain data for two columns. - - \snippet tutorials/widgets/nestedlayouts/main.cpp set up the model - - The use of models and views is covered in the - \l{Item Views Examples} and in the \l{Model/View Programming} overview. -*/ diff --git a/doc/src/widgets-and-layouts/focus.qdoc b/doc/src/widgets-and-layouts/focus.qdoc deleted file mode 100644 index 316893edc4..0000000000 --- a/doc/src/widgets-and-layouts/focus.qdoc +++ /dev/null @@ -1,186 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page focus.html - \title Keyboard Focus - \brief Keyboard focus management and handling. - \ingroup frameworks-technologies - - \keyword keyboard focus - - Qt's widgets handle keyboard focus in the ways that have become - customary in GUIs. - - The basic issue is that the user's key strokes can be directed at any - of several windows on the screen, and any of several widgets inside - the intended window. When the user presses a key, they expect it to go - to the right place, and the software must try to meet this - expectation. The system must determine which application the key stroke - is directed at, which window within that application, and which widget - within that window. - - \section1 Focus Motion - - The customs which have evolved for directing keyboard focus to a - particular widget are these: - - \list 1 - - \o The user presses \key Tab (or \key Shift+Tab). - \o The user clicks a widget. - \o The user presses a keyboard shortcut. - \o The user uses the mouse wheel. - \o The user moves the focus to a window, and the application must - determine which widget within the window should get the focus. - \endlist - - Each of these motion mechanisms is different, and different types of - widgets receive focus in only some of them. We'll cover each of them - in turn. - - \section2 Tab or Shift+Tab - - Pressing \key Tab is by far the most common way to move focus - using the keyboard. (Sometimes in data-entry applications Enter - does the same as \key{Tab}; this can easily be achieved in Qt by - implementing an \l{The Event System}{event filter}.) - - Pressing \key Tab, in all window systems in common use today, - moves the keyboard focus to the next widget in a circular - per-window list. \key Tab moves focus along the circular list in - one direction, \key Shift+Tab in the other. The order in which - \key Tab presses move from widget to widget is called the tab order. - - You can customize the tab order using QWidget::setTabOrder(). (If - you don't, \key Tab generally moves focus in the order of widget - construction.) \l{Qt Designer} provides a means of visually - changing the tab order. - - Since pressing \key Tab is so common, most widgets that can have focus - should support tab focus. The major exception is widgets that are - rarely used, and where there is some keyboard accelerator or error - handler that moves the focus. - - For example, in a data entry dialog, there might be a field that - is only necessary in one per cent of all cases. In such a dialog, - \key Tab could skip this field, and the dialog could use one of - these mechanisms: - - \list 1 - - \o If the program can determine whether the field is needed, it can - move focus there when the user finishes entry and presses \gui OK, or when - the user presses Enter after finishing the other fields. Alternately, - include the field in the tab order but disable it. Enable it if it - becomes appropriate in view of what the user has set in the other - fields. - - \o The label for the field can include a keyboard shortcut that moves - focus to this field. - - \endlist - - Another exception to \key Tab support is text-entry widgets that - must support the insertion of tabs; almost all text editors fall - into this class. Qt treats \key Ctrl+Tab as \key Tab and \key - Ctrl+Shift+Tab as \key Shift+Tab, and such widgets can - reimplement QWidget::event() and handle Tab before calling - QWidget::event() to get normal processing of all other keys. - However, since some systems use \key Ctrl+Tab for other purposes, - and many users aren't aware of \key Ctrl+Tab anyway, this isn't a - complete solution. - - \section2 The User Clicks a Widget - - This is perhaps even more common than pressing \key Tab on - computers with a mouse or other pointing device. - - Clicking to move the focus is slightly more powerful than \key - Tab. While it moves the focus \e to a widget, for editor widgets - it also moves the text cursor (the widget's internal focus) to - the spot where the mouse is clicked. - - Since it is so common and people are used to it, it's a good idea to - support it for most widgets. However, there is also an important - reason to avoid it: you may not want to remove focus from the widget - where it was. - - For example, in a word processor, when the user clicks the 'B' (bold) - tool button, what should happen to the keyboard focus? Should it - remain where it was, almost certainly in the editing widget, or should - it move to the 'B' button? - - We advise supporting click-to-focus for widgets that support text - entry, and to avoid it for most widgets where a mouse click has a - different effect. (For buttons, we also recommend adding a keyboard - shortcut: QAbstractButton and its subclasses make this very easy.) - - In Qt, only the QWidget::setFocusPolicy() function affects - click-to-focus. - - \section2 The User Presses a Keyboard Shortcut - - It's not unusual for keyboard shortcuts to move the focus. This - can happen implicitly by opening modal dialogs, but also - explicitly using focus accelerators such as those provided by - QLabel::setBuddy(), QGroupBox, and QTabBar. - - We advise supporting shortcut focus for all widgets that the user - may want to jump to. For example, a tab dialog can have keyboard - shortcuts for each of its pages, so the user can press e.g. \key - Alt+P to step to the \underline{P}rinting page. It is easy to - overdo this: there are only a few keys, and it's also important - to provide keyboard shortcuts for commands. \key Alt+P is also - used for Paste, Play, Print, and Print Here in the \l{Standard - Accelerator Keys} list, for example. - - \section2 The User Rotates the Mouse Wheel - - On Microsoft Windows, mouse wheel usage is always handled by the - widget that has keyboard focus. On Mac OS X and X11, it's handled by - the widget that gets other mouse events. - - The way Qt handles this platform difference is by letting widgets move - the keyboard focus when the wheel is used. With the right focus policy - on each widget, applications can work idiomatically correctly on - Windows, Mac OS X, and X11. - - \section2 The User Moves the Focus to This Window - - In this situation the application must determine which widget within - the window should receive the focus. - - This can be simple: If the focus has been in this window before, - then the last widget to have focus should regain it. Qt does this - automatically. - - If focus has never been in this window before and you know where - focus should start out, call QWidget::setFocus() on the widget - which should receive focus before you call QWidget::show() it. If - you don't, Qt will pick a suitable widget. -*/ diff --git a/doc/src/widgets-and-layouts/gallery-cde.qdoc b/doc/src/widgets-and-layouts/gallery-cde.qdoc deleted file mode 100644 index 6d6fea7d1e..0000000000 --- a/doc/src/widgets-and-layouts/gallery-cde.qdoc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-cde.html - - \title CDE Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "cde" style. - -\section2 Buttons - -\table 100% -\row -\o \image cde-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image cde-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\o \image cde-pushbutton.png - \image cde-toolbutton.png - \caption The QPushButton widget provides a command button. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image cde-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image cde-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image cde-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image cde-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image cde-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image cde-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image cde-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image cde-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image cde-label.png - The QLabel widget provides a text or image display. -\o \image cde-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image cde-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image cde-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image cde-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image cde-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image cde-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image cde-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image cde-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image cde-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image cde-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image cde-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image cde-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image cde-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image cde-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable - -*/ diff --git a/doc/src/widgets-and-layouts/gallery-cleanlooks.qdoc b/doc/src/widgets-and-layouts/gallery-cleanlooks.qdoc deleted file mode 100644 index 603650bc4b..0000000000 --- a/doc/src/widgets-and-layouts/gallery-cleanlooks.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-cleanlooks.html - - \title Cleanlooks Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "cleanlooks" style. - -\section2 Buttons - -\table 100% -\row -\o \image cleanlooks-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image cleanlooks-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image cleanlooks-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image cleanlooks-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image cleanlooks-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image cleanlooks-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image cleanlooks-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image cleanlooks-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image cleanlooks-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image cleanlooks-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image cleanlooks-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image cleanlooks-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image cleanlooks-label.png - The QLabel widget provides a text or image display. -\o \image cleanlooks-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image cleanlooks-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image cleanlooks-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image cleanlooks-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image cleanlooks-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image cleanlooks-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image cleanlooks-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image cleanlooks-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image cleanlooks-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image cleanlooks-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image cleanlooks-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image cleanlooks-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image cleanlooks-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image cleanlooks-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-gtk.qdoc b/doc/src/widgets-and-layouts/gallery-gtk.qdoc deleted file mode 100644 index ce6a773776..0000000000 --- a/doc/src/widgets-and-layouts/gallery-gtk.qdoc +++ /dev/null @@ -1,141 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-gtk.html - - \title GTK Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "gtk" style. - - Take a look at the \l{Qt Widget Gallery} to see how Qt - applications appear in other styles. - -\section2 Buttons - -\table 100% -\row -\o \image gtk-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image gtk-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image gtk-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image gtk-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image gtk-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image gtk-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image gtk-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image gtk-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image gtk-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image gtk-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image gtk-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image gtk-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image gtk-label.png - The QLabel widget provides a text or image display. -\o \image gtk-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image gtk-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image gtk-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image gtk-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image gtk-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image gtk-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image gtk-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image gtk-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image gtk-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image gtk-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image gtk-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image gtk-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image gtk-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image gtk-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-macintosh.qdoc b/doc/src/widgets-and-layouts/gallery-macintosh.qdoc deleted file mode 100644 index 58622151b7..0000000000 --- a/doc/src/widgets-and-layouts/gallery-macintosh.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-macintosh.html - - \title Macintosh Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "macintosh" style. - -\section2 Buttons - -\table 100% -\row -\o \image macintosh-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image macintosh-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image macintosh-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image macintosh-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image macintosh-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image macintosh-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image macintosh-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image macintosh-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image macintosh-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image macintosh-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image macintosh-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image macintosh-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image macintosh-label.png - The QLabel widget provides a text or image display. -\o \image macintosh-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image macintosh-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image macintosh-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image macintosh-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image macintosh-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image macintosh-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image macintosh-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image macintosh-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image macintosh-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image macintosh-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image macintosh-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image macintosh-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image macintosh-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image macintosh-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-motif.qdoc b/doc/src/widgets-and-layouts/gallery-motif.qdoc deleted file mode 100644 index 91485a088f..0000000000 --- a/doc/src/widgets-and-layouts/gallery-motif.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-motif.html - - \title Motif Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "motif" style. - -\section2 Buttons - -\table 100% -\row -\o \image motif-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image motif-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image motif-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image motif-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image motif-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image motif-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image motif-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image motif-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image motif-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image motif-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image motif-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image motif-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image motif-label.png - The QLabel widget provides a text or image display. -\o \image motif-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image motif-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image motif-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image motif-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image motif-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image motif-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image motif-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image motif-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image motif-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image motif-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image motif-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image motif-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image motif-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image motif-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-plastique.qdoc b/doc/src/widgets-and-layouts/gallery-plastique.qdoc deleted file mode 100644 index 473d7e8da5..0000000000 --- a/doc/src/widgets-and-layouts/gallery-plastique.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-plastique.html - - \title Plastique Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "plastique" style. - -\section2 Buttons - -\table 100% -\row -\o \image plastique-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image plastique-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image plastique-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image plastique-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image plastique-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image plastique-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image plastique-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image plastique-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image plastique-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image plastique-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image plastique-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image plastique-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image plastique-label.png - The QLabel widget provides a text or image display. -\o \image plastique-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image plastique-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image plastique-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image plastique-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image plastique-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image plastique-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image plastique-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image plastique-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image plastique-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image plastique-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image plastique-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image plastique-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image plastique-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image plastique-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-windows.qdoc b/doc/src/widgets-and-layouts/gallery-windows.qdoc deleted file mode 100644 index 1f600b9814..0000000000 --- a/doc/src/widgets-and-layouts/gallery-windows.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-windows.html - - \title Windows Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "windows" style. - -\section2 Buttons - -\table 100% -\row -\o \image windows-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image windows-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image windows-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image windows-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image windows-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image windows-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image windows-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image windows-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image windows-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image windows-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image windows-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image windows-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image windows-label.png - The QLabel widget provides a text or image display. -\o \image windows-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image windows-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image windows-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image windows-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image windows-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image windows-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image windows-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image windows-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image windows-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image windows-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image windows-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image windows-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image windows-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image windows-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-windowsvista.qdoc b/doc/src/widgets-and-layouts/gallery-windowsvista.qdoc deleted file mode 100644 index 534da3e2bd..0000000000 --- a/doc/src/widgets-and-layouts/gallery-windowsvista.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-windowsvista.html - - \title Windows Vista Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "windowsvista" style. - -\section2 Buttons - -\table 100% -\row -\o \image windowsvista-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image windowsvista-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image windowsvista-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image windowsvista-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image windowsvista-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image windowsvista-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image windowsvista-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image windowsvista-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image windowsvista-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image windowsvista-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image windowsvista-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image windowsvista-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image windowsvista-label.png - The QLabel widget provides a text or image display. -\o \image windowsvista-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image windowsvista-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image windowsvista-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image windowsvista-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image windowsvista-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image windowsvista-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image windowsvista-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image windowsvista-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image windowsvista-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image windowsvista-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image windowsvista-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image windowsvista-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image windowsvista-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image windowsvista-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery-windowsxp.qdoc b/doc/src/widgets-and-layouts/gallery-windowsxp.qdoc deleted file mode 100644 index 4d1c79cc9a..0000000000 --- a/doc/src/widgets-and-layouts/gallery-windowsxp.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page gallery-windowsxp.html - - \title Windows XP Style Widget Gallery - \ingroup gallery - - This page shows some of the widgets available in Qt - when configured to use the "windowsxp" style. - -\section2 Buttons - -\table 100% -\row -\o \image windowsxp-pushbutton.png - \caption The QPushButton widget provides a command button. -\o \image windowsxp-toolbutton.png - \caption The QToolButton class provides a quick-access button to commands - or options, usually used inside a QToolBar. -\endtable - -\table 100% -\row -\o \image windowsxp-checkbox.png - \caption The QCheckBox widget provides a checkbox with a text label. -\o \image windowsxp-radiobutton.png - \caption The QRadioButton widget provides a radio button with a text or pixmap label. -\endtable - -\section2 Containers - -\table 100% -\row -\o \image windowsxp-groupbox.png - The The QGroupBox widget provides a group box frame with a title. -\o \image windowsxp-tabwidget.png - The QTabWidget class provides a stack of tabbed widgets. -\o \image windowsxp-frame.png - The QFrame widget provides a simple decorated container for other widgets. -\o \image windowsxp-toolbox.png - The QToolBox class provides a column of tabbed widget items. -\endtable - -\section2 Item Views - -\table 100% -\row -\o \image windowsxp-listview.png - The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. -\o \image windowsxp-treeview.png - The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. -\o \image windowsxp-tableview.png - The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o -\o -\endtable - -\section2 Display Widgets - -\table 100% -\row -\o \image windowsxp-progressbar.png - The QProgressBar widget provides a horizontal progress bar. -\o \image windowsxp-label.png - The QLabel widget provides a text or image display. -\o \image windowsxp-lcdnumber.png - The QLCDNumber widget displays a number with LCD-like digits. -\endtable - -\section2 Input Widgets - -\table 100% -\row -\o \image windowsxp-lineedit.png - The QLineEdit widget is a one-line text editor. -\o \image windowsxp-dateedit.png - The QDateEdit class provides a widget for editing dates. -\o \image windowsxp-timeedit.png - The QTimeEdit class provides a widget for editing times. -\o \image windowsxp-datetimeedit.png - The QDateTimeEdit class provides a widget for editing dates and times. -\endtable - -\table 100% -\row -\o \image windowsxp-slider.png - The QSlider widget provides a vertical or horizontal slider. -\o \image windowsxp-combobox.png - The QComboBox widget is a combined button and pop-up list. -\o \image windowsxp-spinbox.png - The QSpinBox class provides a spin box widget. -\endtable - -\table 100% -\row -\o \image windowsxp-fontcombobox.png - The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. -\o \image windowsxp-doublespinbox.png - The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. -\o \image windowsxp-horizontalscrollbar.png - The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. -\endtable - -\table 100% -\row -\o \image windowsxp-dial.png - The QDial class provides a rounded range control (like a speedometer or potentiometer). -\o \image windowsxp-textedit.png - The QTextEdit class provides a widget that is used to edit and display both plain and rich text. -\o \image windowsxp-calendarwidget.png - The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. -\endtable -*/ diff --git a/doc/src/widgets-and-layouts/gallery.qdoc b/doc/src/widgets-and-layouts/gallery.qdoc deleted file mode 100644 index eb27ec97db..0000000000 --- a/doc/src/widgets-and-layouts/gallery.qdoc +++ /dev/null @@ -1,84 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group gallery - \title Qt Widget Gallery - \brief Qt widgets shown in different styles on various platforms. - - Qt's support for widget styles and themes enables your application to fit in - with the native desktop enviroment. Below, you can find links to the various - widget styles that are supplied with Qt 4. - - \table - \row - \o \image plastique-tabwidget.png Plastique Style Widget Gallery - \caption \l{Plastique Style Widget Gallery} - - The Plastique style is provided by QPlastiqueStyle. - \o \image windowsxp-tabwidget.png Windows XP Style Widget Gallery - \caption \l{Windows XP Style Widget Gallery} - - The Windows XP style is provided by QWindowsXPStyle. - \o \image windows-tabwidget.png Windows Style Widget Gallery - \caption \l{Windows Style Widget Gallery} - - The Windows style is provided by QWindowsStyle. - \endtable - - \table - \row - \o \image macintosh-tabwidget.png Macintosh Style Widget Gallery - \caption \l{Macintosh Style Widget Gallery} - - The Macintosh style is provided by QMacStyle. - \o \image cleanlooks-tabwidget.png Cleanlooks Style Widget Gallery - \caption \l{Cleanlooks Style Widget Gallery} - - The Cleanlooks style is provided by QCleanlooksStyle. - \o \image windowsvista-tabwidget.png Windows Vista Style Widget Gallery - \caption \l{Windows Vista Style Widget Gallery} - - The Windows Vista style is provided by QWindowsVistaStyle. - \endtable - - \table - \row - \o \image gtk-tabwidget.png GTK Style Widget Gallery - \caption \l{GTK Style Widget Gallery} - - The GTK style is provided by QGtkStyle. - \o \image motif-tabwidget.png Motif Style Widget Gallery - \caption \l{Motif Style Widget Gallery} - - The Motif style is provided by QMotifStyle. - \o \image cde-tabwidget.png CDE Style Widget Gallery - \caption \l{CDE Style Widget Gallery} - - The Common Desktop Environment style is provided by QCDEStyle. - \endtable -*/ diff --git a/doc/src/widgets-and-layouts/layout.qdoc b/doc/src/widgets-and-layouts/layout.qdoc deleted file mode 100644 index 3db58c21f9..0000000000 --- a/doc/src/widgets-and-layouts/layout.qdoc +++ /dev/null @@ -1,396 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group geomanagement - \title Layout Classes -*/ - -/*! - \page layout.html - \title Layout Management - \ingroup qt-basic-concepts - \ingroup qt-gui-concepts - \brief A tour of the standard layout managers and an introduction to custom - layouts. - - \previouspage Widgets and Layouts - \contentspage Widgets and Layouts - \nextpage {Styles and Style Aware Widgets}{Styles} - - \ingroup frameworks-technologies - - The Qt layout system provides a simple and powerful way of automatically - arranging child widgets within a widget to ensure that they make good use - of the available space. - - \tableofcontents - - \section1 Introduction - - Qt includes a set of layout management classes that are used to describe - how widgets are laid out in an application's user interface. These layouts - automatically position and resize widgets when the amount of space - available for them changes, ensuring that they are consistently arranged - and that the user interface as a whole remains usable. - - All QWidget subclasses can use layouts to manage their children. The - QWidget::setLayout() function applies a layout to a widget. When a layout - is set on a widget in this way, it takes charge of the following tasks: - - \list - \o Positioning of child widgets. - \o Sensible default sizes for windows. - \o Sensible minimum sizes for windows. - \o Resize handling. - \o Automatic updates when contents change: - \list - \o Font size, text or other contents of child widgets. - \o Hiding or showing a child widget. - \o Removal of child widgets. - \endlist - \endlist - - \section1 Qt's Layout Classes - - Qt's layout classes were designed for hand-written C++ code, allowing - measurements to be specified in pixels for simplicity, so they are easy to - understand and use. The code generated for forms created using \QD also - uses the layout classes. \QD is useful to use when experimenting with the - design of a form since it avoids the compile, link and run cycle usually - involved in user interface development. - - \annotatedlist geomanagement - - \section1 Horizontal, Vertical, Grid, and Form Layouts - - The easiest way to give your widgets a good layout is to use the built-in - layout managers: QHBoxLayout, QVBoxLayout, QGridLayout, and QFormLayout. - These classes inherit from QLayout, which in turn derives from QObject (not - QWidget). They take care of geometry management for a set of widgets. To - create more complex layouts, you can nest layout managers inside each other. - - \list - \o A QHBoxLayout lays out widgets in a horizontal row, from left to - right (or right to left for right-to-left languages). - \image qhboxlayout-with-5-children.png - - \o A QVBoxLayout lays out widgets in a vertical column, from top to - bottom. - \image qvboxlayout-with-5-children.png - - \o A QGridLayout lays out widgets in a two-dimensional grid. Widgets - can occupy multiple cells. - \image qgridlayout-with-5-children.png - - \o A QFormLayout lays out widgets in a 2-column descriptive label- - field style. - \image qformlayout-with-6-children.png - \endlist - - - \section2 Laying Out Widgets in Code - - The following code creates a QHBoxLayout that manages the geometry of five - \l{QPushButton}{QPushButtons}, as shown on the first screenshot above: - - \snippet doc/src/snippets/layouts/layouts.cpp 0 - \snippet doc/src/snippets/layouts/layouts.cpp 1 - \snippet doc/src/snippets/layouts/layouts.cpp 2 - \codeline - \snippet doc/src/snippets/layouts/layouts.cpp 3 - \snippet doc/src/snippets/layouts/layouts.cpp 4 - \snippet doc/src/snippets/layouts/layouts.cpp 5 - - The code for QVBoxLayout is identical, except the line where the layout is - created. The code for QGridLayout is a bit different, because we need to - specify the row and column position of the child widget: - - \snippet doc/src/snippets/layouts/layouts.cpp 12 - \snippet doc/src/snippets/layouts/layouts.cpp 13 - \snippet doc/src/snippets/layouts/layouts.cpp 14 - \codeline - \snippet doc/src/snippets/layouts/layouts.cpp 15 - \snippet doc/src/snippets/layouts/layouts.cpp 16 - \snippet doc/src/snippets/layouts/layouts.cpp 17 - - The third QPushButton spans 2 columns. This is possible by specifying 2 as - the fifth argument to QGridLayout::addWidget(). - - QFormLayout will add two widgets on a row, commonly a QLabel and a QLineEdit - to create forms. Adding a QLabel and a QLineEdit on the same row will set - the QLineEdit as the QLabel's buddy. The following code will use the - QFormLayout to place three \l{QPushButton}{QPushButtons} and a corresponding - QLineEdit on a row. - - \snippet doc/src/snippets/layouts/layouts.cpp 18 - \snippet doc/src/snippets/layouts/layouts.cpp 19 - \snippet doc/src/snippets/layouts/layouts.cpp 20 - \codeline - \snippet doc/src/snippets/layouts/layouts.cpp 21 - \snippet doc/src/snippets/layouts/layouts.cpp 22 - \snippet doc/src/snippets/layouts/layouts.cpp 23 - - - \section2 Tips for Using Layouts - - When you use a layout, you do not need to pass a parent when constructing - the child widgets. The layout will automatically reparent the widgets - (using QWidget::setParent()) so that they are children of the widget on - which the layout is installed. - - \note Widgets in a layout are children of the widget on which the layout - is installed, \e not of the layout itself. Widgets can only have other - widgets as parent, not layouts. - - You can nest layouts using \c addLayout() on a layout; the inner layout - then becomes a child of the layout it is inserted into. - - - \section1 Adding Widgets to a Layout - - When you add widgets to a layout, the layout process works as follows: - - \list 1 - \o All the widgets will initially be allocated an amount of space in - accordance with their QWidget::sizePolicy() and - QWidget::sizeHint(). - - \o If any of the widgets have stretch factors set, with a value - greater than zero, then they are allocated space in proportion to - their stretch factor (explained below). - - \o If any of the widgets have stretch factors set to zero they will - only get more space if no other widgets want the space. Of these, - space is allocated to widgets with an - \l{QSizePolicy::Expanding}{Expanding} size policy first. - - \o Any widgets that are allocated less space than their minimum size - (or minimum size hint if no minimum size is specified) are - allocated this minimum size they require. (Widgets don't have to - have a minimum size or minimum size hint in which case the strech - factor is their determining factor.) - - \o Any widgets that are allocated more space than their maximum size - are allocated the maximum size space they require. (Widgets do not - have to have a maximum size in which case the strech factor is - their determining factor.) - \endlist - - - \section2 Stretch Factors - \keyword stretch factor - - Widgets are normally created without any stretch factor set. When they are - laid out in a layout the widgets are given a share of space in accordance - with their QWidget::sizePolicy() or their minimum size hint whichever is - the greater. Stretch factors are used to change how much space widgets are - given in proportion to one another. - - If we have three widgets laid out using a QHBoxLayout with no stretch - factors set we will get a layout like this: - - \img layout1.png Three widgets in a row - - If we apply stretch factors to each widget, they will be laid out in - proportion (but never less than their minimum size hint), e.g. - - \img layout2.png Three widgets with different stretch factors in a row - - - \section1 Custom Widgets in Layouts - - When you make your own widget class, you should also communicate its layout - properties. If the widget has a one of Qt's layouts, this is already taken - care of. If the widget does not have any child widgets, or uses manual - layout, you can change the behavior of the widget using any or all of the - following mechanisms: - - \list - \o Reimplement QWidget::sizeHint() to return the preferred size of the - widget. - \o Reimplement QWidget::minimumSizeHint() to return the smallest size - the widget can have. - \o Call QWidget::setSizePolicy() to specify the space requirements of - the widget. - \endlist - - Call QWidget::updateGeometry() whenever the size hint, minimum size hint or - size policy changes. This will cause a layout recalculation. Multiple - consecutive calls to QWidget::updateGeometry() will only cause one layout - recalculation. - - If the preferred height of your widget depends on its actual width (e.g., - a label with automatic word-breaking), set the - \l{QSizePolicy::hasHeightForWidth()}{height-for-width} flag in the - widget's \l{QWidget::sizePolicy}{size policy} and reimplement - QWidget::heightForWidth(). - - Even if you implement QWidget::heightForWidth(), it is still a good idea to - provide a reasonable sizeHint(). - - For further guidance when implementing these functions, see the - \e{Qt Quarterly} article - \l{http://doc.qt.nokia.com/qq/qq04-height-for-width.html} - {Trading Height for Width}. - - - \section1 Layout Issues - - The use of rich text in a label widget can introduce some problems to the - layout of its parent widget. Problems occur due to the way rich text is - handled by Qt's layout managers when the label is word wrapped. - - In certain cases the parent layout is put into QLayout::FreeResize mode, - meaning that it will not adapt the layout of its contents to fit inside - small sized windows, or even prevent the user from making the window too - small to be usable. This can be overcome by subclassing the problematic - widgets, and implementing suitable \l{QWidget::}{sizeHint()} and - \l{QWidget::}{minimumSizeHint()} functions. - - In some cases, it is relevant when a layout is added to a widget. When - you set the widget of a QDockWidget or a QScrollArea (with - QDockWidget::setWidget() and QScrollArea::setWidget()), the layout must - already have been set on the widget. If not, the widget will not be - visible. - - - \section1 Manual Layout - - If you are making a one-of-a-kind special layout, you can also make a - custom widget as described above. Reimplement QWidget::resizeEvent() to - calculate the required distribution of sizes and call - \l{QWidget::}{setGeometry()} on each child. - - The widget will get an event of type QEvent::LayoutRequest when the - layout needs to be recalculated. Reimplement QWidget::event() to handle - QEvent::LayoutRequest events. - - - \section1 How to Write A Custom Layout Manager - - An alternative to manual layout is to write your own layout manager by - subclassing QLayout. The \l{layouts/borderlayout}{Border Layout} and - \l{layouts/flowlayout}{Flow Layout} examples show how to do this. - - Here we present an example in detail. The \c CardLayout class is inspired - by the Java layout manager of the same name. It lays out the items (widgets - or nested layouts) on top of each other, each item offset by - QLayout::spacing(). - - To write your own layout class, you must define the following: - \list - \o A data structure to store the items handled by the layout. Each - item is a \link QLayoutItem QLayoutItem\endlink. We will use a - QList in this example. - \o \l{QLayout::}{addItem()}, how to add items to the layout. - \o \l{QLayout::}{setGeometry()}, how to perform the layout. - \o \l{QLayout::}{sizeHint()}, the preferred size of the layout. - \o \l{QLayout::}{itemAt()}, how to iterate over the layout. - \o \l{QLayout::}{takeAt()}, how to remove items from the layout. - \endlist - - In most cases, you will also implement \l{QLayout::}{minimumSize()}. - - - \section2 The Header File (\c card.h) - - \snippet doc/src/snippets/code/doc_src_layout.cpp 0 - - - \section2 The Implementation File (\c card.cpp) - - \snippet doc/src/snippets/code/doc_src_layout.cpp 1 - - First we define \c{count()} to fetch the number of items in the list. - - \snippet doc/src/snippets/code/doc_src_layout.cpp 2 - - Then we define two functions that iterate over the layout: \c{itemAt()} - and \c{takeAt()}. These functions are used internally by the layout system - to handle deletion of widgets. They are also available for application - programmers. - - \c{itemAt()} returns the item at the given index. \c{takeAt()} removes the - item at the given index, and returns it. In this case we use the list index - as the layout index. In other cases where we have a more complex data - structure, we may have to spend more effort defining a linear order for the - items. - - \snippet doc/src/snippets/code/doc_src_layout.cpp 3 - - \c{addItem()} implements the default placement strategy for layout items. - This function must be implemented. It is used by QLayout::add(), by the - QLayout constructor that takes a layout as parent. If your layout has - advanced placement options that require parameters, you must provide extra - access functions such as the row and column spanning overloads of - QGridLayout::addItem(), QGridLayout::addWidget(), and - QGridLayout::addLayout(). - - \snippet doc/src/snippets/code/doc_src_layout.cpp 4 - - The layout takes over responsibility of the items added. Since QLayoutItem - does not inherit QObject, we must delete the items manually. In the - destructor, we remove each item from the list using \c{takeAt()}, and - then delete it. - - \snippet doc/src/snippets/code/doc_src_layout.cpp 5 - - The \c{setGeometry()} function actually performs the layout. The rectangle - supplied as an argument does not include \c{margin()}. If relevant, use - \c{spacing()} as the distance between items. - - \snippet doc/src/snippets/code/doc_src_layout.cpp 6 - - \c{sizeHint()} and \c{minimumSize()} are normally very similar in - implementation. The sizes returned by both functions should include - \c{spacing()}, but not \c{margin()}. - - \snippet doc/src/snippets/code/doc_src_layout.cpp 7 - - - \section2 Further Notes - - \list - \o This custom layout does not handle height for width. - \o We ignore QLayoutItem::isEmpty(); this means that the layout will - treat hidden widgets as visible. - \o For complex layouts, speed can be greatly increased by caching - calculated values. In that case, implement - QLayoutItem::invalidate() to mark the cached data is dirty. - \o Calling QLayoutItem::sizeHint(), etc. may be expensive. So, you - should store the value in a local variable if you need it again - later within in the same function. - \o You should not call QLayoutItem::setGeometry() twice on the same - item in the same function. This call can be very expensive if the - item has several child widgets, because the layout manager must do - a complete layout every time. Instead, calculate the geometry and - then set it. (This does not only apply to layouts, you should do - the same if you implement your own resizeEvent(), for example.) - \endlist -*/ - diff --git a/doc/src/widgets-and-layouts/styles.qdoc b/doc/src/widgets-and-layouts/styles.qdoc deleted file mode 100644 index 3b705de973..0000000000 --- a/doc/src/widgets-and-layouts/styles.qdoc +++ /dev/null @@ -1,2102 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group appearance - \title Widget Appearance and Style - \brief Classes used for customizing UI appearance and style. -*/ - -/*! - \page style-reference.html - \title Styles and Style Aware Widgets - \ingroup qt-gui-concepts - \brief Styles and the styling of widgets. - - Styles (classes that inherit QStyle) draw on behalf of widgets - and encapsulate the look and feel of a GUI. The QStyle class is - an abstract base class that encapsulates the look and feel of a - GUI. Qt's built-in widgets use it to perform nearly all of their - drawing, ensuring that they look exactly like the equivalent - native widgets. - - Several styles are built into Qt (e.g., windows style and motif style). - Other styles are only available on specific platforms (such as - the windows XP style). Custom styles are made available as plugins - or by creating an instance of the style class in an application and - setting it with QApplication::setStyle(). - - To implement a new style, you inherit one of Qt's existing styles - - the one most resembling the style you want to create - and - reimplement a few virtual functions. This process is somewhat - involved, and we therefore provide this overview. We give a - step-by-step walkthrough of how to style individual Qt widgets. - We will examine the QStyle virtual functions, member variables, - and enumerations. - - The part of this document that does not concern the styling of - individual widgets is meant to be read sequentially because later - sections tend to depend on earlier ones. The description of the - widgets can be used for reference while implementing a style. - However, you may need to consult the Qt source code in some cases. - The sequence in the styling process should become clear after - reading this document, which will aid you in locating relevant code. - - To develop style aware widgets (i.e., widgets that conform to - the style in which they are drawn), you need to draw them using the - current style. This document shows how widgets draw themselves - and which possibilities the style gives them. - - \section1 Classes for Widget Styling - - These classes are used to customize an application's appearance and - style. - - \annotatedlist appearance - - \section1 The QStyle implementation - - The API of QStyle contains functions that draw the widgets, static - helper functions to do common and difficult tasks (e.g., - calculating the position of slider handles) and functions to do - the various calculations necessary while drawing (e.g., for the - widgets to calculate their size hints). The style also help some - widgets with the layout of their contents. In addition, it creates - a QPalette that contains \l{QBrush}es to draw with. - - QStyle draws graphical elements; an element is a widget or a - widget part like a push button bevel, a window frame, or a scroll - bar. Most draw functions now take four arguments: - - \list - \o an enum value specifying which graphical element to draw - \o a QStyleOption specifying how and where to render that element - \o a QPainter that should be used to draw the element - \o a QWidget on which the drawing is performed (optional) - \endlist - - When a widget asks a style to draw an element, it provides the style - with a QStyleOption, which is a class that contains the information - necessary for drawing. Thanks to QStyleOption, it is possible to make - QStyle draw widgets without linking in any code for the widget. This - makes it possible to use \l{QStyle}'s draw functions on any paint - device, i.e., you can draw a combobox on any widget, not just on a - QComboBox. - - The widget is passed as the last argument in case the style needs - it to perform special effects (such as animated default buttons on - Mac OS X), but it isn't mandatory. - - We will in the course of this section look at the style elements, - the style options, and the functions of QStyle. Finally, we describe - how the palette is used. - - Items in item views is drawn by \l{Delegate Classes}{delegates} in - Qt. The item view headers are still drawn by the style. Qt's - default delegate, QStyledItemDelegate, draws its items partially - through the current style; it draws the check box indicators and - calculate bounding rectangles for the elements of which the item - consists. In this document, we only describe how to implement a - QStyle subclass. If you wish to add support for other datatypes - than those supported by the QStyledItemDelegate, you need to - implement a custom delegate. Note that delegates must be set - programmatically for each individual widget (i.e., default - delegates cannot be provided as plugins). - - \section2 The Style Elements - - A style element is a graphical part of a GUI. A widget consists - of a hierarchy (or tree) of style elements. For instance, when a - style receives a request to draw a push button (from QPushButton, - for example), it draws a label (text and icon), a button bevel, - and a focus frame. The button bevel, in turn, consists of a frame - around the bevel and two other elements, which we will look at - later. Below is a conceptual illustration of the push button - element tree. We will see the actual tree for QPushButton when we - go through the individual widgets. - - \image javastyle/conceptualpushbuttontree.png - - Widgets are not necessarily drawn by asking the style to draw - only one element. Widgets can make several calls to the style to - draw different elements. An example is QTabWidget, which draws its - tabs and frame individually. - - There are three element types: primitive elements, control - elements, and complex control elements. The elements are defined - by the \l{QStyle::}{ComplexControl}, \l{QStyle::}{ControlElement}, - and \l{QStyle::}{PrimitiveElement} enums. The values of - each element enum has a prefix to identify their type: \c{CC_} for - complex elements, \c{CE_} for control elements, and \c{PE_} for - primitive elements. We will in the following three sections see what - defines the different elements and see examples of widgets that use - them. - - The QStyle class description contains a list of these elements and - their roles in styling widgets. We will see how they are used when - we style individual widgets. - - \section3 Primitive Elements - - Primitive elements are GUI elements that are common and often used - by several widgets. Examples of these are frames, button bevels, - and arrows for spin boxes, scroll bars, and combo boxes. - Primitive elements cannot exist on their own: they are always part - of a larger construct. They take no part in the interaction with - the user, but are passive decorations in the GUI. - - \section3 Control Elements - - A control element performs an action or displays information - to the user. Examples of control elements are push buttons, check - boxes, and header sections in tables and tree views. Control - elements are not necessarily complete widgets such as push - buttons, but can also be widget parts such as tab bar tabs and - scroll bar sliders. They differ from primitive elements in that - they are not passive, but fill a function in the interaction with - the user. Controls that consist of several elements often use the - style to calculate the bounding rectangles of the elements. The - available sub elements are defined by the \l{QStyle::}{SubElement} - enum. This enum is only used for calculating bounding rectangles, - and sub elements are as such not graphical elements to be drawn - like primitive, control, and complex elements. - - \section3 Complex Control Elements - - Complex control elements contain sub controls. Complex controls - behave differently depending on where the user handles them with - the mouse and which keyboard keys are pressed. This is dependent - on which sub control (if any) that the mouse is over or received a - mouse press. Examples of complex controls are scroll bars and - combo boxes. With a scroll bar, you can use the mouse to move the - slider and press the line up and line down buttons. The available - sub controls are defined by the \l{QStyle}{SubControl} enum. - - In addition to drawing, the style needs to provide the widgets - with information on which sub control (if any) a mouse press was - made on. For instance, a QScrollBar needs to know if the user - pressed the slider, the slider groove, or one of the buttons. - - Note that sub controls are not the same as the control elements - described in the previous section. You cannot use the style to - draw a sub control; the style will only calculate the bounding - rectangle in which the sub control should be drawn. It is common, - though, that complex elements use control and primitive elements - to draw their sub controls, which is an approach that is - frequently used by the built-in styles in Qt and also the Java - style. For instance, the Java style uses PE_IndicatorCheckBox to - draw the check box in group boxes (which is a sub control of - CC_GroupBox). Some sub controls have an equivalent control element, - e.g., the scroll bar slider (SC_SCrollBarSlider and - CE_ScrollBarSlider). - - \section3 Other QStyle Tasks - - The style elements and widgets, as mentioned, use the style to - calculate bounding rectangles of sub elements and sub controls, - and pixel metrics, which is a style dependent size in screen - pixels, for measures when drawing. The available rectangles and - pixel metrics are represented by three enums in QStyle: - \l{QStyle::}{SubElement}, \l{QStyle::}{SubControl}, and - \l{QStyle::}{PixelMetric}. Values of the enums can easily by - identified as they start with SE_, SC_ and PM_. - - The style also contain a set of style hints, which is - represented as values in the \l{QStyle::}{StyleHint} enum. All - widgets do not have the same functionality and look in the - different styles. For instance, when the menu items in a menu do not - fit in a single column on the screen, some styles support - scrolling while others draw more than one column to fit all items. - - A style usually has a set of standard images (such as a warning, a - question, and an error image) for message boxes, file dialogs, - etc. QStyle provides the \l{QStyle::}{StandardPixmap} enum. Its - values represent the standard images. Qt's widgets use these, so - when you implement a custom style you should supply the images - used by the style that is being implemented. - - The style calculates the spacing between widgets in layouts. There - are two ways the style can handle these calculations. You can set - the PM_LayoutHorizontalSpacing and PM_LayoutVerticalSpacing, which - is the way the java style does it (through QCommonStyle). - Alternatively, you can implement QStyle::layoutSpacing() and - QStyle::layoutSpacingImplementation() if you need more control over - this part of the layout. In these functions you can calculate the - spacing based on control types (QSizePolicy::ControlType) for - different size policies (QSizePolicy::Policy) and also the style - option for the widget in question. - - \section2 Style Options - - The sub-classes of QStyleOption contain all information necessary - to style the individual elements. Style options are instantiated - - usually on the stack - and filled out by the caller of the QStyle - function. Depending on what is drawn the style will expect - different a different style option class. For example, the - QStyle::PE_FrameFocusRect element expects a QStyleOptionFocusRect - argument, and it's possible to create custom subclasses that a - custom style can use. The style options keep public variables - for performance reasons. - - The widgets can be in a number of different states, which are - defined by the \l{QStyle::}{State} enum. Some of the state flags have - different meanings depending on the widget, but others are common - for all widgets like State_Disabled. It is QStyleOption that sets - the common states with QStyleOption::initFrom(); the rest of the - states are set by the individual widgets. - - Most notably, the style options contain the palette and bounding - rectangles of the widgets to be drawn. Most widgets have - specialized style options. QPushButton and QCheckBox, for - instance, use QStyleOptionButton as style option, which contain - the text, icon, and the size of their icon. The exact contents of - all options are described when we go through individual widgets. - - When reimplementing QStyle functions that take a - QStyleOption parameter, you often need to cast the - QStyleOption to a subclass (e.g., QStyleOptionFocusRect). For - safety, you can use qstyleoption_cast() to ensure that the - pointer type is correct. If the object isn't of the right type, - qstyleoption_cast() returns 0. For example: - - \snippet doc/src/snippets/code/doc_src_qt4-styles.cpp 0 - - The following code snippet illustrates how to use QStyle to - draw the focus rectangle from a custom widget's paintEvent(): - - \snippet doc/src/snippets/code/doc_src_qt4-styles.cpp 1 - - The next example shows how to derive from an existing style to - customize the look of a graphical element: - - \snippet doc/src/snippets/customstyle/customstyle.h 0 - \codeline - \snippet doc/src/snippets/customstyle/customstyle.cpp 2 - \snippet doc/src/snippets/customstyle/customstyle.cpp 3 - \snippet doc/src/snippets/customstyle/customstyle.cpp 4 - - \section2 QStyle Functions - - The QStyle class defines three functions for drawing the primitive, - control, and complex elements: - \l{QStyle::}{drawPrimitive()}, - \l{QStyle::}{drawControl()}, and - \l{QStyle::}{drawComplexControl()}. The functions takes the - following parameters: - - \list - \o the enum value of the element to draw - \o a QStyleOption which contains the information needed to - draw the element. - \o a QPainter with which to draw the element. - \o a pointer to a QWidget, typically the widget - that the element is painted on. - \endlist - - Not all widgets send a pointer to themselves. If the style - option sent to the function does not contain the information you - need, you should check the widget implementation to see if it - sends a pointer to itself. - - The QStyle class also provides helper functions that are used - when drawing the elements. The \l{QStyle::}{drawItemText()} - function draws text within a specified rectangle and taking a - QPalette as a parameter. The \l{QStyle::}{drawItemPixmap()} - function helps to align a pixmap within a specified bounding - rectangle. - - Other QStyle functions do various calculations for the - functions that draw. The widgets also use these functions for - calculating size hints and also for bounding rectangle - calculations if they draw several style elements themselves. - As with the functions that draw elements the helper functions - typically takes the same arguments. - - \list - \o The \l{QStyle::}{subElementRect()} function takes a - \l{QStyle::}{SubElement} enum value, and calculates a bounding - rectangle for a sub element. The style uses this function to - know where to draw the different parts of an element. This is - mainly done for reuse. If you create a new style, you can use - the same location of sub elements as the super class. - - \o The \l{QStyle::}{subControlRect()} function is used to - calculate bounding rectangles for sub controls in complex - controls. When you implement a new style, you reimplement \c - subControlRect() and calculate the rectangles that are different - from the super class. - - \o The \l{QStyle::}{pixelMetric()} function returns a pixel - metric, which is a style dependent size given in screen - pixels. It takes a value of the \l{QStyle::}{PixelMetric} enum - and returns the correct measure. Note that pixel metrics do - not necessarily have to be static measures, but can be - calculated with, for example, the style option. - - \o The \l{QStyle::}{hitTestComplexControl()} function returns the - sub control that the mouse pointer is over in a complex control. - Usually, this is simply a matter of using - \l{QStyle::}{subControlRect()} to get the bounding rectangles of - the sub controls, and see which rectangle contains the position of - the cursor. - \endlist - - QStyle also have the functions \l{QStyle::}{polish()} and - \l{QStyle::}{unpolish()}. All widgets are sent to the \c polish() - function before being shown and to \c unpolish() when they - are hidden. You can use these functions to set attributes on the - widgets or do other work that is required by your style. For - instance, if you need to know when the mouse is hovering over the - widget, you need to set the \l{Qt::}{WA_Hover} widget attribute. - The State_MouseOver state flag will then be set in the widget's - style options. - - QStyle has a few static helper functions that do some common and - difficult tasks. They can calculate the position of a slider - handle from the value of the slider and transform rectangles - and draw text considering reverse layouts; see the QStyle - class documentation for more details. - - The usual approach when one reimplements QStyle virtual - functions is to do work on elements that are different from the - super class; for all other elements, you can simply use the super - class implementation. - - \section2 The Palette - - Each style provides a color - that is, QBrush - palette that - should be used for drawing the widgets. There is one set of colors - for the different widget states (QPalette::ColorGroup): active - (widgets in the window that has keyboard focus), inactive (widgets - used for other windows), and disabled (widgets that are set - disabled). The states can be found by querying the State_Active - and State_Enabled state flags. Each set contains color certain - roles given by the QPalette::ColorRole enum. The roles describe in - which situations the colors should be used (e.g., for painting - widget backgrounds, text, or buttons). - - How the color roles are used is up to the style. For instance, if - the style uses gradients, one can use a palette color and make it - darker or lighter with QColor::darker() and QColor::lighter() to - create the gradient. In general, if you need a brush that is not - provided by the palette, you should try to derive it from one. - - QPalette, which provides the palette, stores colors for - different widget states and color roles. The palette for a style - is returned by \l{QStyle::}{standardPalette()}. The standard - palette is not installed automatically when a new style is set - on the application (QApplication::setStyle()) or widget - (QWidget::setStyle()), so you must set the palette yourself - with (QApplication::setPalette()) or (QWidget::setPalette()). - - It is not recommended to hard code colors as applications and - individual widgets can set their own palette and also use the - styles palette for drawing. Note that none of Qt's widgets set - their own palette. The java style does hard code some colors, but - its author looks past this in silence. Of course, it is not - intended that the style should look good with any palette. - - \section2 Implementation Issues - - When you implement styles, there are several issues to - consider. We will give some hints and advice on implementation - here. - - When implementing styles, it is necessary to look through the - code of the widgets and code of the base class and its ancestors. - This is because the widgets use the style differently, because the - implementation in the different styles virtual functions can - affect the state of the drawing (e.g., by altering the QPainter - state without restoring it and drawing some elements without using - the appropriate pixel metrics and sub elements). - - It is recommended that the styles do not alter the proposed size - of widgets with the QStyle::sizeFromContents() function but let - the QCommonStyle implementation handle it. If changes need to be - made, you should try to keep them small; application development - may be difficult if the layout of widgets looks considerably - different in the various styles. - - We recommend using the QPainter directly for drawing, i.e., not - use pixmaps or images. This makes it easier for the style conform - to the palette (although you can set your own color table on a - QImage with \l{QImage::}{setColorTable()}). - - It is, naturally, possible to draw elements without using the - style to draw the sub elements as intended by Qt. This is - discouraged as custom widgets may depend on these sub elements to - be implemented correctly. The widget walkthrough shows how Qt - uses the sub elements. - - \section1 Java Style - - We have implemented a style that resembles the Java default look - and feel (previously known as Metal). We have done this as it is - relatively simple to implement and we wanted to build a style for - this overview document. To keep it simple and not to extensive, we - have simplified the style somewhat, but Qt is perfectly able to - make an exact copy of the style. However, there are no concrete - plans to implement the style as a part of Qt. - - In this section we will have a look at some implementation - issues. Finally, we will see a complete example on the styling of - a Java widget. We will continue to use the java style - throughout the document for examples and widget images. The - implementation itself is somewhat involved, and it is not - intended that you should read through it. - - \section2 Design and Implementation - - The first step in designing the style was to select the base - class. We chose to subclass QWindowsStyle. This class implements - most of the functionality we need other than performing the actual - drawing. Also, windows and java share layout of sub controls for - several of the complex controls (which reduces the amount of code - required considerably). - - The style is implemented in one class. We have done this - because we find it convenient to keep all code in one file. Also, - it is an advantage with regards to optimization as we instantiate - less objects. We also keep the number of functions at a minimum by - using switches to identify which element to draw in the functions. - This results in large functions, but since we divide the code for - each element in the switches, the code should still be easy to - read. - - \section2 Limitations and Differences from Java - - We have not fully implemented every element in the Java style. - This way, we have reduced the amount and complexity of the code. - In general, the style was intended as a practical example for - this style overview document, and not to be a part of Qt - itself. - - Not all widgets have every state implemented. This goes for - states that are common, e.g., State_Disabled. Each state is, - however, implemented for at least one widget. - - We have only implemented ticks below the slider. Flat push - buttons are also left out. We do not handle the case where the - title bars and dock window titles grows to small for their - contents, but simply draw sub controls over each other. - - We have not tried to emulate the Java fonts. Java and Qt use very - different font engines, so we don't consider it worth the effort - as we only use the style as an example for this overview. - - We have hardcoded the colors (we don't use the QPalette) for - the linear gradients, which are used, for example, for button - bevels, tool bars, and check boxes. This is because the Java - palette cannot produce these colors. Java does not change these - colors based on widget color group or role anyway (they are not - dependent on the palette), so it does not present a problem in any - case. - - It is Qt's widgets that are styled. Some widgets do not exist - at all in Java, e.g., QToolBox. Others contain elements that the - Java widgets don't. The tree widget is an example of the latter in - which Java's JTree does not have a header. - - The style does not handle reverse layouts. We assume that the - layout direction is left to right. QWindowsStyle handles reverse - widgets; if we implemented reverse layouts, widgets that we change - the position of sub elements, or handle text alignment in labels - our selves would need to be updated. - - \section2 Styling Java Check Boxes - - As an example, we will examine the styling of check boxes in the - java style. We describe the complete process and print all code in - both the java style and Qt classes involved. In the rest of this - document, we will not examine the source code of the individual - widgets. Hopefully, this will give you an idea on how to search - through the code if you need to check specific implementation - details; most widgets follow the same structure as the check - boxes. We have edited the QCommonStyle code somewhat to remove - code that is not directly relevant for check box styling. - - We start with a look at how QCheckBox builds it style option, - which is QStyleOptionButton for checkboxes: - - \snippet doc/src/snippets/code/doc_src_styles.cpp 0 - - First we let QStyleOption set up the option with the information - that is common for all widgets with \c initFrom(). We will look at - this shortly. - - The down boolean is true when the user press the box down; this is - true whether the box is checked or not of the checkbox. The - State_NoChange state is set when we have a tristate checkbox and - it is partially checked. It has State_On if the box is checked and - State_Off if it is unchecked. State_MouseOver is set if the mouse - hovers over the checkbox and the widget has attribute Qt::WA_Hover - set - you set this in QStyle::polish(). In addition, the style - option also contains the text, icon, and icon size of the button. - - \l{QStyleOption::}{initFrom()} sets up the style option with the - attributes that are common for all widgets. We print its - implementation here: - - \snippet doc/src/snippets/code/doc_src_styles.cpp 1 - - The State_Enabled is set when the widget is enabled. When the - widget has focus the State_HasFocus flag is set. Equally, the - State_Active flag is set when the widget is a child of the active - window. The State_MouseOver will only be set if the widget has - the WA_HoverEnabled windows flag set. Notice that keypad - navigation must be enabled in Qt for the State_HasEditFocus to - be included; it is not included by default. - - In addition to setting state flags the QStyleOption contains - other information about the widget: \c direction is the layout - direction of the layout, \c rect is the bounding rectangle of the - widget (the area in which to draw), \c palette is the QPalette - that should be used for drawing the widget, and \c fontMetrics is - the metrics of the font that is used by the widget. - - We give an image of a checkbox and the style option to match - it. - - \image javastyle/checkboxexample.png A java style checkbox - - The above checkbox will have the following state flags in its - style option: - - \table 90% - \header - \o State flag - \o Set - \row - \o State_Sunken - \o Yes - \row - \o State_NoChange - \o No - \row - \o State_On - \o Yes - \row - \o State_Off - \o No - \row - \o State_MouseOver - \o Yes - \row - \o State_Enabled - \o Yes - \row - \o State_HasFocus - \o Yes - \row - \o State_KeyboardFocusChange - \o No - \row - \o State_Active - \o Yes - \endtable - - The QCheckBox paints itself in QWidget::paintEvent() with - style option \c opt and QStylePainter \c p. The QStylePainter - class is a convenience class to draw style elements. Most - notably, it wraps the methods in QStyle used for painting. The - QCheckBox draws itself as follows: - - \snippet doc/src/snippets/code/doc_src_styles.cpp 2 - - QCommonStyle handles the CE_CheckBox element. The QCheckBox - has two sub elements: SE_CheckBoxIndicator (the checked indicator) - and SE_CheckBoxContents (the contents, which is used for the - checkbox label). QCommonStyle also implements these sub element - bounding rectangles. We have a look at the QCommonStyle code: - - \snippet doc/src/snippets/code/doc_src_styles.cpp 3 - - As can be seen from the code extract, the common style gets - the bounding rectangles of the two sub elements of - CE_CheckBox, and then draws them. If the checkbox has focus, - the focus frame is also drawn. - - The java style draws CE_CheckBoxIndicator, while QCommonStyle - handles CE_CheckboxLabel. We will examine each implementation and - start with CE_CheckBoxLabel: - - \snippet doc/src/snippets/code/doc_src_styles.cpp 4 - - \l{QStyle::}{visualAlignment()} adjusts the alignment of text - according to the layout direction. We then draw an icon if it - exists, and adjust the space left for the text. - \l{QStyle::}{drawItemText()} draws the text taking alignment, - layout direction, and the mnemonic into account. It also uses the - palette to draw the text in the right color. - - The drawing of labels often get somewhat involved. Luckily, it - can usually be handled by the base class. The java style - implements its own push button label since Java-contrary to - windows-center button contents also when the button has an icon. - You can examine that implementation if you need an example of - reimplementing label drawing. - - We take a look at the java implementation - of CE_CheckBoxIndicator in \c drawControl(): - - \snippet doc/src/snippets/javastyle.cpp 0 - - We first save the state of the painter. This is not always - necessary but in this case the QWindowsStyle needs the painter in - the same state as it was when PE_IndicatorCheckBox was called (We - could also set the state with function calls, of course). We then - use \c drawButtonBackground() to draw the background of the check - box indicator. This is a helper function that draws the background - and also the frame of push buttons and check boxes. We take a look - at that function below. We then check if the mouse is hovering - over the checkbox. If it is, we draw the frame java checkboxes - have when the box is not pressed down and the mouse is over it. - You may note that java does not handle tristate boxes, so we have - not implemented it. - - Here we use a png image for our indicator. We could also check - here if the widget is disabled. We would then have to use - another image with the indicator in the disabled color. - - \snippet doc/src/snippets/javastyle.cpp 1 - - We have seen how check boxes are styled in the java style from the - widget gets a paint request to the style is finished painting. To - learn in detail how each widget is painted, you need to go through - the code step-by-step as we have done here. However, it is - usually enough to know which style elements the widgets draw. The - widget builds a style option and calls on the style one or more - times to draw the style elements of which it consists. Usually, - it is also sufficient to know the states a widget can be in and the - other contents of the style option, i.e., what we list in the next - section. - - \section1 Widget Walkthrough - - In this section, we will examine how most of Qt's widgets are - styled. Hopefully, this will save you some time and effort while - developing your own styles and widgets. You will not find - information here that is not attainable elsewhere (i.e., by - examining the source code or the class descriptions for the style - related classes). - - We mostly use java style widgets as examples. The java style does not - draw every element in the element trees. This is because they are - not visible for that widget in the java style. We still make sure - that all elements are implemented in a way that conforms with the - java style as custom widgets might need them (this does not - exclude leaving implementations to QWindowsStyle though). - - The following is given for each widget: - - \list - \o A table with the members (variables, etc.) of its style option. - \o A table over the state flags (QStyle::StateFlag) that - can be set on the widget and when the states are set. - \o Its element tree (see section \l{The Style Elements}). - \o An image of the widget in which the elements are outlined. - \omit This is not written yet - probably never will be - either - \o List of style hints that should be checked for the - widget. - \o List of standard pixmaps that could be used by the - elements. - \endomit - \endlist - - The element tree contains the primitive, control, and complex - style elements. By doing a top-down traversal of the element tree, - you get the sequence in which the elements should be drawn. In the - nodes, we have written the sub element rectangles, sub control - elements, and pixel metrics that should be considered when drawing - the element of the node. - - Our approach on styling center on the drawing of the widgets. The - calculations of sub elements rectangles, sub controls, and pixel - metrics used \bold during drawing is only listed as contents in - the element trees. Note that there are rectangles and pixel - metrics that are only used by widgets. This leaves these - calculations untreated in the walkthrough. For instance, the - \l{QStyle::}{subControlRect()} and - \l{QStyle::}{sizeFromContents()} functions often call - \l{QStyle::}{subElementRect()} to calculate their bounding - rectangles. We could draw trees for this as well. However, how - these calculations are done is completely up to the individual - styles, and they do not have to follow a specific structure (Qt - does not impose a specific structure). You should still make sure - that you use the appropriate pixel metrics, though. To limit the - size of the document, we have therefore chosen not to include - trees or describe the calculations made by the Java (or any other) - style. - - You may be confused about how the different pixel metrics, sub - element rectangles, and sub control rectangles should be used when - examining the trees. If you are in doubt after reading the QStyle - enum descriptions, we suggest that you examine the QCommonStyle - and QWindowsStyle implementations. - - Some of the bounding rectangles that we outline in the widget - images are equal. Reasons for this are that some elements draw - backgrounds while others draw frames and labels. If in doubt, - check the description of each element in QStyle. Also, some - elements are there to layout, i.e., decide where to draw, other - elements. - - \section2 Common Widget Properties - - Some states and variables are common for all widgets. These are - set with QStyleOption::initFrom(). Not all elements use this function; - it is the widgets that create the style options, and for some - elements the information from \l{QStyleOption::}{initFrom()} is not - necessary. - - A table with the common states follows: - - \table 90% - \header - \o State - \o State Set When - \row - \o State_Enabled - \o Set if the widget is not disabled (see - QWidget::setEnabled()) - \row - \o State_Focus - \o Set if the widget has focus (see - QWidget::hasFocus()) - \row - \o State_KeyobordFocusChange - \o Set when the user changes focus with the keyboard - (see Qt::WA_KeyboardFocusChange) - \row - \o State_MouseOver - \o Set if the mouse cursor is over the widget - \row - \o State_Active - \o Set if the widget is a child of the active window. - \row - \o State_HasEditFocus - \o Set if the widget has the edit focus - \endtable - - The other common members for widgets are: - - \table 90% - \header - \o Member - \o Content - \row - \o rect - \o The bounding rectangle of the element to draw. This - is set to the widget bounding rectangle - (QWidget::rect()). - \row - \o direction - \o The layout direction; a value of the - Qt::LayoutDirection enum. - \row - \o palette - \o The QPalette to use when drawing the element. This - is set to the widgets palette (QWidget::palette()). - \row - \o fontMetrics - \o The QFontMetrics to use when drawing text on the - widget. - \endtable - - The complex style options (classes that inherit - QStyleOptionComplex) used for complex style elements share two - variables: \l{QStyleOptionComplex::}{subControls} and - \l{QStyleOptionComplex::}{activeSubControls}. Both variables are - an OR'ed combination of QStyle::SubControl enum values. They - indicate which sub controls the complex control consists of and - which of these controls are currently active. - - As mentioned, the style calculates the size of the widgets - contents, which the widgets calculate their size hints from. In - addition, complex controls also use the style to test which - sub-controls the mouse is over. - - \section2 Widget Reference - - Without further delay, we present the widget walkthrough; each - widget has its own sub-section. - - \section3 Push Buttons - - The style structure for push buttons is shown below. By doing a - top-down traversal of the tree, you get the sequence in which the - elements should be drawn. - - \image javastyle/pushbutton.png The style structure for push buttons - - The layout of the buttons, with regard element bounds, varies from - style to style. This makes it difficult to show conceptual images - of this. Also, elements may - even be intended to - have the same - bounds; the PE_PushButtonBevel, for instance, is used in - QCommonStyle to draw the elements that contains it: - PE_FrameDefaultButton, PE_FrameButtonBevel, and - PE_PanelButtonCommand, all of which have the same bounds in common - and windows style. PE_PushButtonBevel is also responsible for - drawing the menu indicator (QCommonStyle draws - PE_IndicatorArrowDown). - - An image of a push button in the java style that show the bounding - rectangles of the elements is given below. Colors are used to - separate the bounding rectangles in the image; they do not fill - any other purpose. This is also true for similar images for the - other widgets. - - \image javastyle/button.png - - The java style, as well as all other styles implemented in Qt, - does not use PE_FrameButtonBevel. It is usual that a button - with a PE_DefaultFrame adjusts the PE_PanelButtonCommand's - rectangle by PM_ButtonDefaultIndicator. The CE_PushButtonLabel - is found by adjusting the rect by PM_DefaultFrameWidth. - - We will now examine the style option for push - buttons - QStyleOptionButton. A table for the states that - QPushButton can set on the style option follows: - - \table 90% - \header - \o State - \o State Set When - \row - \o State_Sunken - \o Button is down or menu is pressed shown - \row - \o State_On - \o Button is checked - \row - \o State_Raised - \o Button is not flat and not pressed down - \endtable - - Other members of QStyleOptionButton is: - - \table 90% - \header - \o Member - \o Content - \row - \o features - \o Flags of the QStyleOptionButton::ButtonFeatures enum, - which describes various button properties (see enum) - \row - \o icon - \o The buttons QIcon (if any) - \row - \o iconSize - \o The QSize of the icon - \row - \o text - \o a QString with the buttons text - \endtable - - \section3 Check and Radio Buttons - - The structures for radio and check buttons are identical. - We show the structure using QCheckBox element and pixel - metric names: - - \image javastyle/checkbox.png - - QStyleOptionButton is used as the style option for both check - and radio buttons. We first give a table of the states that - can be set in the option: - - \table 90% - \header - \o State - \o State Set When - \row - \o State_sunken - \o The box is pressed down - \row - \o State_NoChange - \o The box is partially checked (for tristate - checkboxes.) - \row - \o State_On - \o The box is checked - \row - \o State_Off - \o The box is unchecked - \endtable - - See \l{Push Buttons} for a table over other members in the - QStyleOptionButtonClass. - - \section3 Tabs - - In Qt, QTabBar uses the style to draw its tabs. Tabs exist either - in a QTabWidget, which contains a QTabBar, or as a separate bar. - If the bar is not part of a tab widget, it draws its own base. - - QTabBar lays out the tabs, so the style does not have control over - tab placement. However, while laying out its tabs, the bar asks - the style for PM_TabBarTabHSpace and PM_TabBarTabVSpace, which is - extra width and height over the minimum size of the tab bar tab - label (icon and text). The style can also further influence the - tab size before it is laid out, as the tab bar asks for - CT_TabBarTab. The bounding rectangle of the bar is decided by the - tab widget when it is part of the widget (still considering - CT_TabBarTab). - - The tab bar is responsible for drawing the buttons that appear on - the tab bar when all tabs do not fit. Their placement is not - controlled by the style, but the buttons are \l{QToolButton}s - and are therefore drawn by the style. - - Here is the style structure for QTabWidget and QTabBar: - - \image javastyle/tab.png - - The dotted lines indicate that the QTabWidget contains a tab bar, - but does not draw it itself, that QTabBar only draws its base line - when not part of a tab widget, and that the tab bar keeps two tool - buttons that scroll the bar when all tabs do not fit; see \l{Tool - Buttons} for their element tree. Also note that since the buttons - are children of the tab bar, they are drawn after the bar. The - tabs bounding rectangles overlap the base by PM_TabBarBaseOverlap. - - Here is a tab widget in the java style: - - \image javastyle/tabwidget.png - - In the java style (and also windows), the tab bar shape and label - have the same bounding rectangle as CE_TabBarTab. Notice that the - tabs overlap with the tab widget frame. The base of the tab bar - (if drawn) is the area where the tabs and frame overlap. - - The style option for tabs (QStyleOptionTab) contains the necessary - information for drawing tabs. The option contains the position of - the tab in the tab bar, the position of the selected tab, the - shape of the tab, the text, and icon. After Qt 4.1 the option - should be cast to a QStyleOptionTabV2, which also contains the - icons size. - - As the java style tabs don't overlap, we also present an image of - a tab widget in the windows style. Note that if you want the tabs - to overlap horizontally, you do that when drawing the tabs in - CE_TabBarTabShape; the tabs bounding rectangles will not be - altered by the tab bar. The tabs are drawn from left to right in a - north tab bar shape, top to bottom in an east tab bar shape, etc. - The selected tab is drawn last, so that it is easy to draw it over - the other tabs (if it is to be bigger). - - \image javastyle/windowstabimage.png - - A table of the states a tab bar can set on its tabs follows: - - \table 90% - \header - \o State - \o State Set When - \row - \o State_Sunken - \o The tab is pressed on with the mouse. - \row - \o State_Selected - \o If it is the current tab. - \row - \o State_HasFocus - \o The tab bar has focus and the tab is selected - \endtable - - Note that individual tabs may be disabled even if the tab bar - is not. The tab will be active if the tab bar is active. - - Here follows a table of QStyleOptionTabV2's members: - - \table 90% - \header - \o Member - \o Content - \row - \o cornerWidgets - \o Is flags of the CornerWidget enum, which indicate - if and which corner widgets the tab bar has. - \row - \o icon - \o The QIcon of the tab - \row - \o iconSize - \o The QSize of the icon - \row - \o position - \o A TabPosition enum value that indicates the tabs - position on the bar relative to the other tabs. - \row - \o row - \o holds which row the tab is in - \row - \o selectedPosition - \o A value of the SelectedPosition enum that indicates - whether the selected tab is adjacent to or is the - tab. - \row - \o shape - \o A value of the QTabBar::Shape enum indication - whether the tab has rounded or triangular corners - and the orientation of the tab. - \row - \o text - \o The tab text - \endtable - - The frame for tab widgets use QStyleOptionTabWidgetFrame as - style option. We list its members here. It does not have - states set besides the common flags. - - \table 90% - \header - \o Member - \o content - \row - \o leftCornerWidgetSize - \o The QSize of the left corner widget (if any). - \row - \o rightCornerWidgetSize - \o The QSize of the right corner widget (if any). - \row - \o lineWidth - \o holds the line with for drawing the panel. - \row - \o midLineWith - \o this value is currently always 0. - \row - \o shape - \o The shape of the tabs on the tab bar. - \row - \o tabBarSize - \o The QSize of the tab bar. - \endtable - - \section3 Scroll Bars - - Here is the style structure for scrollBars: - - \image javastyle/scrollbar.png - - QScrollBar simply creates its style option and then draws - CC_ScrollBar. Some styles draw the background of add page and sub - page with PE_PanelButtonBevel and also use indicator arrows to - draw the arrows in the nest and previous line indicators; we have - not included these in the tree as their use is up to the - individual style. The style's PM_MaximumDragDistance is the - maximum distance in pixels the mouse can move from the bounds - of the scroll bar and still move the handle. - - Here is an image of a scrollbar in the java style: - - \image javastyle/scrollbarimage.png - - You may notice that the scrollbar is slightly different from - Java's as it has two line up indicators. We have done this to show - how that you can have two separate bounding rectangles for a - single sub control. The scroll bar is an example of a widget that - is entirely implemented by the java style - neither QWindowsStyle - nor QCommonStyle are involved in the drawing. - - We have a look at the different states a scroll bar can set on - the style option: - - \table 90% - \header - \o State - \o State Set When - \row - \o State_Horizontal - \o The scroll bar is horizontal - \endtable - - The style option of QScrollBar is QStyleOptionSlider. Its - members are listed in the following table. The option is used - by all \l{QAbstractSlider}s; we only describe the members - relevant for scroll bars here. - - \table 90% - \header - \o Member - \o Content - \row - \o maximum - \o the maximum value of the scroll bar - \row - \o minimum - \o the minimum value of the scroll bar - \row - \o notchTarget - \o the number of pixels between notches - \row - \o orientation - \o a value of the Qt::Orientation enum that specifies - whether the scroll bar is vertical or horizontal - \row - \o pageStep - \o the number to increase or decrease the sliders - value (relative to the size of the slider and its value - range) on page steps. - \row - \o singleStep - \o the number to increase or decrease the sliders - value on single (or line) steps - \row - \o sliderValue - \o The value of the slider - \row - \o sliderPosition - \o the position of the slider handle. This is the same - as \c sliderValue if the scroll bar is - QAbstractSlider::tracking. If not, the scroll - bar does not update its value before the mouse - releases the handle. - \row - \o upsideDown - \o holds the direction in which the scroll bar - increases its value. This is used instead of - QStyleOption::direction for all abstract sliders. - \endtable - - \section3 Sliders - - When calculating the sliders size hint, PM_SliderTickness and - PM_SliderLength is queried from the style. As with scroll bars, - the QSlider only lets the user move the handle if the mouse is - within PM_MaximumDragDistance from the slider bounds. When it - draws itself it creates the style option and calls \c - drawComplexControl() with CC_Slider: - - \image javastyle/slider.png - - We also show a picture of a slider in the java style. We show - the bounding rectangles of the sub elements as all drawing is done - in CC_Slider. - - \image javastyle/sliderimage.png - - QSlider uses QStyleOptionSlider as all \l{QAbstractSlider}s do. We - present a table with the members that affect QSlider: - - \table 90% - \header - \o Member - \o Content - \row - \o maximum - \o the maximum value of the slider - \row - \o minimum - \o the minimum value of the slider - \row - \o notchTarget - \o this is the number of pixels between each notch - \row - \o orientation - \o a Qt::Orientation enum value that gives whether the - slider is vertical or horizontal. - \row - \o pageStep - \o a number in slider value to increase or decrease - for page steps - \row - \o singleStep - \o the number to increase or decrease the sliders - value on single (or line) steps. - \row - \o sliderValue - \o the value of the slider. - \row - \o sliderPosition - \o the position of the slider given as a slider value. - This will be equal to the \c sliderValue if the - slider is \l{QAbstractSlider::}{tracking}; if - not, the sliders value will not change until the handle is - released with the mouse. - \row - \o upsideDown - \o this member is used instead of QStyleOption::direction - for all abstract sliders. - \endtable - - You should note that the slider does not use direction for - reverse layouts; it uses \c upsideDown. - - \section3 Spin Boxes - - When QSpinBox paints itself it creates a QStyleOptionSpinBox and - asks the style to draw CC_SpinBox. The edit field is a line - edit that is a child of the spin box. The dimensions of the - field is calculated by the style with SC_SpinBoxEditField. - - Here follows the style tree for spin boxes. It is not - required that a style uses the button panel primitive to paint - the indicator backgrounds. You can see an image below the tree - showing the sub elements in QSpinBox in the java style. - - \image javastyle/spinbox.png - - \image javastyle/spinboximage.png - - The QStyleOptionSpinBox, which is the style option for spin - boxes. It can set the following states on the spin box.: - - \table 90% - \header - \o State - \o State Set When - \row - \o State_Sunken - \o Is set if one of the sub controls CC_SpinUp or - CC_SpinDown is pressed on with the mouse. - \endtable - - The rest of the members in the spin boxes style options are: - - \table 90% - \header - \o Property - \o Function - \row - \o frame - \o boolean that is true if the spin box is to draw a - frame. - \row - \o buttonSymbols - \o Value of the ButtonSymbols enum that decides the - symbol on the up/down buttons. - \row - \o stepEnabled - \o A value of the StepEnabled indication which of the - spin box buttons are pressed down. - \endtable - - \section3 Title Bar - - The title bar complex control, CC_TitleBar, is used to draw - the title bars of internal windows in QMdiArea. It typically - consists of a window title and close, minimize, system menu, and - maximize buttons. Some styles also provide buttons for shading - the window, and a button for context sensitive help. - - The bar is drawn in CC_TitleBar without using any sub elements. - How the individual styles draw their buttons is individual, but - there are standard pixmaps for the buttons that the style should - provide. - - \image javastyle/titlebar.png - - In an image over a title bar in the java style, we show the - bounding rectangles of the sub elements supported by the java style - (all of which are drawn with standard pixmaps). It is usual to - draw the button backgrounds using PE_PanelButtonTool, but it's no - rule. - - \image javastyle/titlebarimage.png - - The style option for title bars is QStyleOptionTitleBar. It's - members are: - - \table 90% - \header - \o Member - \o Content - \row - \o icon - \o The title bars icon - \row - \o text - \o the text for the title bar's label - \row - \o windowFlags - \o flags of the Qt::WindowFlag enum. The window flags - used by QMdiArea for window management. - \row - \o titleBarState - \o this is the QWidget::windowState() of the window - that contains the title bar. - \endtable - - \section3 Combo Box - - A QComboBox uses the style to draw the button and label of - non-editable boxes with CC_ComboBox and CE_ComboBoxLabel. - - The list that pops up when the user clicks on the combo box is - drawn by a \l{Delegate Classes}{delegate}, which we do not cover - in this overview. You can, however, use the style to control the - list's size and position with the sub element - SC_ComboBoxListBoxPopup. The style also decides where the edit - field for editable boxes should be with SC_ComboBoxEditField; the - field itself is a QLineEdit that is a child of the combo box. - - \image javastyle/combobox.png - - We show an image over a java style combo box in which we have - outlined its sub elements and sub element rectangles: - - \image javastyle/comboboximage.png - - Java combo boxes do not use the focus rect; it changes its - background color when it has focus. The SC_ComboBoxEdit field is - used both by QComboBox to calculate the size of the edit field and - the style for calculating the size of the combo box label. - - The style option for combo boxes is QStyleOptionComboBox. It - can set the following states: - - \table 90% - \header - \o State - \o Set When - \row - \o State_Selected - \o The box is not editable and has focus - \row - \o State_Sunken - \o SC_ComboBoxArrow is active - \row - \o State_on - \o The container (list) of the box is visible - \endtable - - The style options other members are: - - \table - \header - \o Member - \o Content - \row - \o currentIcon - \o the icon of the current (selected) item of the - combo box. - \row - \o currentText - \o the text of the current item in the box. - \row - \o editable - \o holds whether the combo box is editable or not - \row - \o frame - \o holds whether the combo box has a frame or not - \row - \o iconSize - \o the size of the current items icon. - \row - \o popupRect - \o the bounding rectangle of the combo box's popup - list. - \endtable - - \section3 Group Boxes - - When calculating the size hint, QGroupBox fetches three pixel - metrics from the style: PM_IndicatorWidth, - PM_CheckBoxLabelSpacing, and PM_IndicatorHeight. QGroupBox has - the following style element tree: - - \image javastyle/groupbox.png - - Qt does not impose restrictions on how the check box is drawn; the - java style draws it with CE_IndicatorCheckBox. See \l{Check and - Radio Buttons} for the complete tree. - - We also give an image of the widget with the sub controls and - sub control rectangles drawn: - - \image javastyle/groupboximage.png - - The style option for group boxes are QStyleOptionGroupBox. The - following states can be set on it: - - \table 90% - \header - \o State - \o Set When - \row - \o State_On - \o The check box is checked - \row - \o State_Sunken - \o The checkbox is pressed down - \row - \o State_Off - \o The check box is unchecked (or there is no check box) - \endtable - - The remaining members of QStyleOptionGroupBox are: - - \table - \header - \o Member - \o Content - \row - \o features - \o flags of the QStyleOptionFrameV2::FrameFeatures - enum describing the frame of the group box. - \row - \o lineWidth - \o the line width with which to draw the panel. This - is always 1. - \row - \o text - \o the text of the group box. - \row - \o textAlignment - \o the alignment of the group box title - \row - \o textColor - \o the QColor of the text - \endtable - - \section3 Splitters - - As the structure of splitters are simple and do not contain any - sub elements, we do not include image of splitters. CE_Splitter - does not use any other elements or metrics. - - For its style option, Splitters uses the base class QStyleOption. - It can set the following state flags on it: - - \table 90% - \header - \o State - \o Set When - \row - \o State_Horizontal - \o Set if it is a horizontal splitter - \endtable - - QSplitter does not use \l{QStyleOption::}{initFrom()} to set up its - option; it sets the State_MouseOver and State_Disabled flags - itself. - - \section3 Progress Bar - - The CE_ProgressBar element is used by QProgressBar, and it is the - only element used by this widget. We start with looking at the - style structure: - - \image javastyle/progressbar.png - - Here is a progress bar in the windows style (the java style - bounding rectangles are equal): - - \image javastyle/progressbarimage.png - - The style option for QProgressBar is QStyleOptionProgressBarV2. - The bar does not set any state flags, but the other members of the - option are: - - \table 90% - \header - \o Member - \o Content - \row - \o minimum - \o The minimum value of the bar - \row - \o maximum - \o The maximum value of the bar - \row - \o progress - \o The current value of the bar - \row - \o textAlignment - \o How the text is aligned in the label - \row - \o textVisible - \o Whether the label is drawn - \row - \o text - \o The label text - \row - \o orientation - \o Progress bars can be vertical or horizontal - \row - \o invertedAppearance - \o The progress is inverted (i.e., right to left in a - horizontal bar) - \row - \o bottomToTop - \o Boolean that if true, turns the label of vertical - progress bars 90 degrees. - \endtable - - \section3 Tool Buttons - - Tool buttons exist either independently or as part of tool bars. - They are drawn equally either way. The QToolButton draws only one - style element: CC_ToolButton. - - As you must be used to by now (at least if you have read this - document sequentially), we have a tree of the widget's style - structure: - - \image javastyle/toolbutton.png - - Note that PE_FrameButtonTool and PE_IndicatorArrowDown are - included in the tree as the java style draws them, but they can - safely be omitted if you prefer it. The structure may also be - different. QWindowsStyle, for instance, draws both - PE_IndicatorButtonDropDown and PE_IndicatorArrowDown in - CE_ToolButton. - - We also have an image of a tool button where we have outlined - the sub element bounding rectangles and sub controls. - - \image javastyle/toolbuttonimage.png - - Here is the states table for tool buttons: - - \table 90% - \header - \o State - \o Set When - \row - \o State_AutoRise - \o the tool button has the autoRise property set - \row - \o State_raised - \o the button is not sunken (i.e., by being checked or - pressed on with the mouse). - \row - \o State_Sunken - \o the button is down - \row - \o State_On - \o the button is checkable and checked. - \endtable - - QStyleOptionToolButton also contains the following members: - - \table - \header - \o Member - \o Content - \row - \o arrowType - \o a Qt::ArrowType enum value, which contains the - direction of the buttons arrow (if an arrow is to - be used in place of an icon) - \row - \o features - \o flags of the QStyleOptionToolButton::ButtonFeature - enum describing if the button has an arrow, a menu, - and/or has a popup-delay. - \row - \o font - \o the QFont of the buttons label - \row - \o icon - \o the QIcon of the tool button - \row - \o iconSize - \o the icon size of the button's icon - \row - \o pos - \o the position of the button, as given by - QWidget::pos() - \row - \o text - \o the text of the button - \row - \o toolButtonStyle - \o a Qt::ToolButtonStyle enum value which decides - whether the button shows the icon, the text, or both. - \endtable - - \section3 Toolbars - - Toolbars are part of the \l{QMainWindow}{main window framework} - and cooperates with the QMainWindow to which it belongs while it - builds its style option. A main window has 4 areas that toolbars - can be placed in. They are positioned next to the four sides of - the window (i.e., north, south, west, and east). Within each area - there can be more than one line of toolbars; a line consists of - toolbars with equal orientation (vertical or horizontal) placed - next to each other. - - \l{QToolbar}{QToolbar}s in Qt consists of three elements - CE_ToolBar, PE_IndicatorToolBarHandle, and - PE_IndicatorToolBarSeparator. It is QMainWindowLayout that - calculates the bounding rectangles (i.e., position and size of the - toolbars and their contents. The main window also uses the \c - sizeHint() of the items in the toolbars when calculating the size - of the bars. - - Here is the element tree for QToolBar: - - \image javastyle/toolbar.png - - The dotted lines indicate that the QToolBar keeps an instance of - QToolBarLayout and that QToolBarSeparators are kept by - QToolBarLayout. When the toolbar is floating (i.e., has its own - window) the PE_FrameMenu element is drawn, else QToolbar draws - CE_ToolBar. - - Here is an image of a toolbar in the java style: - - \image javastyle/toolbarimage.png - - QToolBarSaparator uses QStyleOption for their style option. It - sets the State_horizontal flag if the toolbar they live in is - horizontal. Other than that, they use \l{QStyleOption::}{initFrom()}. - - The style option for QToolBar is QStyleOptionToolBar. The only - state flag set (besides the common flags) is State_Horizontal - if the bar is horizontal (i.e., in the north or south toolbar area). - The member variables of the style option are: - - \table 90% - \header - \o Member - \o Content - \row - \o features - \o Holds whether the bar is movable in a value of the - ToolBarFeature, which is either Movable or None. - \row - \o lineWidth - \o The width of the tool bar frame. - \row - \o midLineWidth - \o This variable is currently not used and is always - 0. - \row - \o positionOfLine - \o The position of the toolbar line within the toolbar - area to which it belongs. - \row - \o positionWithinLine - \o The position of the toolbar within the toolbar line. - \row - \o toolBarArea - \o The toolbar area in which the toolbar lives. - \endtable - - \section3 Menus - - Menus in Qt are implemented in QMenu. The QMenu keeps a list of - action, which it draws as menu items. When QMenu receives paint - events ,it calculates the size of each menu item and draws them - individually with CE_MenuItem. (Menu items do not have a separate - element for their label (contents), so all drawing is done in - CE_MenuItem. The menu also draws the frame of the menu with - PE_FrameMenu. It also draws CE_MenuScroller if the style supports - scrolling. CE_MenuTearOff is drawn if the menu is to large for its - bounding rectangle. - - In the style structure tree, we also include QMenu as it also does - styling related work. The bounding rectangles of menu items are - calculated for the menus size hint and when the menu is displayed - or resized. - - \image javastyle/menu.png - - The CE_MenuScroller and CE_MenuTearOff elements are handled by - QCommonStyle and are not shown unless the menu is to large to fit - on the screen. PE_FrameMenu is only drawn for pop-up menus. - - QMenu calculates rectangles based on its actions and calls - CE_MenuItem and CE_MenuScroller if the style supports that. - - It is also usual to use PE_IndicatorCheckBox (instead of using - PE_IndicatorMenuCheckMark) and PE_IndicatorRadioButton for drawing - checkable menu items; we have not included them in the style tree - as this is optional and varies from style to style. - - \image javastyle/menuimage.png - - The style option for menu items is QStyleOptionMenuItem. The - following tables describe its state flags and other members. - - \table 90% - \header - \o State - \o Set When - \row - \o State_Selected - \o The mouse is over the action and the action is not - a separator. - \row - \o State_Sunken - \o The mouse is pressed down on the menu item. - \row - \o State_DownArrow - \o Set if the menu item is a menu scroller and it scrolls - the menu downwards. - \endtable - - \table 90% - \header - \o Member - \o Content - \row - \o checkType - \o A value of the \l{QStyleOptionMenuItem::}{CheckType} enum, - which is either NotCheckable, Exclusive, or - NonExclusive. - \row - \o checked - \o Boolean that is true if the menu item is checked. - \row - \o font - \o The QFont to use for the menu item's text. - \row - \o icon - \o the QIcon of the menu item. - \row - \o maxIconWidth - \o The maximum width allowed for the icon - \row - \o menuHasChecableItem - \o Boolean which is true if at least one item in the - menu is checkable. - \row - \o menuItemType - \o The type of the menu item. This a value of the - \l{QStyleOptionMenuItem::}{MenuItemType}. - \row - \o menuRect - \o The bounding rectangle for the QMenu that the menu - item lives in. - \row - \o tabWidth - \o This is the distance between the text of the menu - item and the shortcut. - \row - \o text - \o The text of the menu item. - \endtable - - The setup of the style option for CE_MenuTearOff and - CE_MenuScroller also uses QStyleOptionMenuItem; they only set the - \c menuRect variable in addition to the common settings with - QStyleOption's \l{QStyleOption::}{initFrom()}. - - \section3 Menu Bar - - QMenuBar uses the style to draw each menu bar item and the empty - area of the menu bar. The pull-down menus themselves are - \l{QMenu}s (see \l{Menus}). The style element tree for the menu - bar follows: - - \image javastyle/menubar.png - - The panel and empty area is drawn after the menu items. The - QPainter that the QMenuBar sends to the style has the bounding - rectangles of the items clipped out (i.e., clip region), so you - don't need to worry about drawing over the items. The pixel - metrics in QMenuBar is used when the bounding rectangles of the - menu bar items are calculated. - - \image javastyle/menubarimage.png - - QStyleOptionMenuItem is used for menu bar items. The members that - are used by QMenuBar is described in the following table: - - \table - \header - \o Member - \o Content - \row - \o menuRect - \o the bounding rectangle of the entire menu bar to - which the item belongs. - \row - \o text - \o the text of the item - \row - \o icon - \o the icon of the menu item (it is not common that - styles draw this icon) - \endtable - - QStyleOptionMenuItem is also used for drawing CE_EmptyMenuBarArea. - - QStyleOptionFrame is used for drawing the panel frame The - \l{QStyleOptionFrame::}{lineWidth} is set to PM_MenuBarPanelWidth. - The \l{QStyleOptionFrame::}{midLineWidth} is currently always set - to 0. - - \section3 Item View Headers - - It is the style that draws the headers of Qt's item views. The - item views keeps the dimensions on individual sections. Also - note that the delegates may use the style to paint decorations - and frames around items. QItemDelegate, for instance, draws - PE_FrameFocusRect and PE_IndicatorViewItemCheck. - - \image javastyle/header.png - - Here is a QTableWidget showing the bounding rects of a Java - header: - - \image javastyle/headerimage.png - - The QHeaderView uses CT_HeaderSection, PM_HeaderMargin and - PM_HeaderGripMargin for size and hit test calculations. The - PM_HeaderMarkSize is currently not used by Qt. QTableView draws - the button in the top-left corner (i.e., the area where the - vertical and horizontal headers intersect) as a CE_Header. - - The style option for header views is QStyleOptionHeader. The view - paints one header section at a time, so the data is for the - section being drawn. Its contents are: - - \table 90% - \header - \o Member - \o Content - \row - \o icon - \o the icon of the header (for section that is being - drawn). - \row - \o iconAlignment - \o the alignment (Qt::Alignment) of the icon in the header. - \row - \o orientation - \o a Qt::Orientation value deciding whether the header - is the horizontal header above the view or the - vertical header on the left. - \row - \o position - \o a QStyleOptionHeader::SectionPosition value - giving the header section's position relative to - the other sections. - \row - \o section - \o holds the section that is being drawn. - \row - \o selectedPosition - \o a QStyleOptionHeader::SelectedPosition value giving - the selected section's position relative to the - section that is being painted. - \row - \o sortIndicator - \o a QStyleOptionHeader::SortIndicator value that - describes the direction in which the section's sort - indicator should be drawn. - \row - \o text - \o the text of the currently drawn section. - \row - \o textAlignment - \o the Qt::Alignment of the text within the - headersection. - \endtable - - \section3 Tree Branch Indicators - - The branch indicators in a tree view is drawn by the style with - PE_IndicatorBranch. We think of indicators here as the indicators - that describe the relationship of the nodes in the tree. The - generic QStyleOption is sent to the style for drawing this - elements. The various branch types are described by states. Since - there are no specific style option, we simply present the states - table: - - \table 90% - \header - \o State - \o Set When - \row - \o State_Sibling - \o the node in the tree has a sibling (i.e., there is - another node in the same column). - \row - \o State_Item - \o this branch indicator has an item. - \row - \o State_Children - \o the branch has children (i.e., a new sub-tree can - be opened at the branch). - \row - \o State_Open - \o the branch indicator has an opened sub-tree. - \endtable - - The tree view (and tree widget) use the style to draw the branches - (or nodes if you will) of the tree. - - QStyleOption is used as the style for PE_IndicatorBranch has state - flags set depending on what type of branch it is. - - Since there is no tree structure for branch indicators, we only - present an image of a tree in the java style. Each state is marked - in the image with a rectangle in a specific color (i.e., these - rectangles are not bounding rectangles). All combinations of - states you must be aware of are represented in the image. - - \image javastyle/branchindicatorimage.png - - \section3 Tool Boxes - - PM_SmallIconSize for sizeHints. - - QToolBox is a container that keeps a collection of widgets. It has - one tab for each widget and display one of them at a time. The - tool box lays the components it displays (the tool box buttons - and selected widget) in a QVBoxLayout. The style tree for tool - boxes looks like this: - - \image javastyle/toolbox.png - - We show an image of a tool box in the Plastique style: - - \image javastyle/toolboximage.png - - All elements have the same bounding rectangles in the - Plastique as well as the other Qt built-in styles. - - The style option for tool boxes is QStyleOptionToolBox. It - contains the text and icon of the tool box contents. The only - state set by QToolBox is State_Sunken, which is set when the user - presses a tab down with the mouse. The rest of the - QStyleOptionToolBox members are: - - \table 90% - \header - \o Member - \o Content - \row - \o icon - \o the icon on the toolbox tab - \row - \o text - \o the text on the toolbox tab - \endtable - - \section3 Size Grip - - The size grip calculates its size hint with CT_SizeGrip. The pixel - metric PM_SizeGripSize is currently unused by Qt. The element tree - for and an image in the Plastique style of QSizeGrip follows: - - \image javastyle/sizegrip.png - - \image javastyle/sizegripimage.png - - We show the size grip in a \l{QMainWindow}'s bottom right - corner. - - The size grip style option, QStyleOptionSizeGrip, have one - member except the common members from QStyleOption: - - \table 90% - \header - \o Member - \o Content - \row - \o corner - \o a Qt::Corner value that describe which corner in a - window (or equivalent) the grip is located. - \endtable - - \section3 Rubber Band - - The \l{QRubberBand}'s style tree consists of two nodes. - - \image javastyle/rubberband.png - - We present an image of a Java style window being moved in a - QMdiArea with a rubber band: - - \image javastyle/rubberbandimage.png - - The style option for rubber bands is QStyleOptionRubberBand. - Its members are: - - \table - \header - \o Member - \o Content - \row - \o opaque - \o boolean that is true if the rubber band must be - drawn in an opaque style (i.e., color) - \row - \o shape - \o a QRubberBand::Shape enum value that holds the - shape of the band (which is either a rectangle or a - line) - \endtable - - \section3 Dock Widgets - - When the dock widget lays out its contents it asks the style for - these pixel metrics: PM_DockWidgetSeparatorExtent, - PM_DockWidgetTitleBarButtonMargin, PM_DockWidgetFrameWidth, and - PM_DockWidgetTitleMargin. It also calculates the bounding - rectangles of the float and close buttons with - SE_DockWidgetCloseButton and SE_DockWidgetFloatButton. - - \image javastyle/dockwidget.png - - The dotted lines indicate that the sender keeps instances of the - recipient of the arrow (i.e., it is not a style element to draw). - The dock widget only draws PE_frameDockWidget when it is detached - from its main window (i.e., it is a top level window). If it is - docked it draws the indicator dock widget resize handle. We show a - dock widget in both docked and floating state in the plastique - style: - - \image javastyle/dockwidgetimage.png - - The style option is QStyleOptionDockWidget: - - \table 90% - \header - \o Member - \o Content - \row - \o closeable - \o boolean that holds whether the dock window can be - closed - \row - \o floatable - \o boolean that holds whether the dock window can - float (i.e., detach from the main window in which - it lives) - \row - \o movable - \o boolean that holds whether the window is movable - (i.e., can move to other dock widget areas) - \row - \o title - \o the title text of the dock window - \endtable - - For the buttons, QStyleOptionButton is used (see \l{Tool Buttons} - for content description). The dock widget resize handle has a - plain QStyleOption. -*/ diff --git a/doc/src/widgets-and-layouts/stylesheet.qdoc b/doc/src/widgets-and-layouts/stylesheet.qdoc deleted file mode 100644 index 80376b40a1..0000000000 --- a/doc/src/widgets-and-layouts/stylesheet.qdoc +++ /dev/null @@ -1,3963 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page stylesheet.html - \title Qt Style Sheets - \brief How to use style sheets to customize the appearance of widgets. - - \ingroup frameworks-technologies - \ingroup qt-basic-concepts - \ingroup qt-gui-concepts - - \previouspage {Styles and Style Aware Widgets}{Styles} - \contentspage Widgets and Layouts - \nextpage The Style Sheet Syntax - - \keyword style sheet - \keyword stylesheet - - Qt Style Sheets are a powerful mechanism that allows you to - customize the appearance of widgets, in addition to what is - already possible by subclassing QStyle. The concepts, - terminology, and syntax of Qt Style Sheets are heavily inspired - by HTML \l{http://www.w3.org/Style/CSS/}{Cascading Style Sheets - (CSS)} but adapted to the world of widgets. - - Topics: - - \list - \i \l{Overview} - \i \l{The Style Sheet Syntax} - \i \l{Qt Designer Integration} - \i \l{Customizing Qt Widgets Using Style Sheets} - \i \l{Qt Style Sheets Reference} - \i \l{Qt Style Sheets Examples} - \endlist - - \target overview - \section1 Overview - - Styles sheets are textual specifications that can be set on the - whole application using QApplication::setStyleSheet() or on a - specific widget (and its children) using - QWidget::setStyleSheet(). If several style sheets are set at - different levels, Qt derives the effective style sheet from all - of those that are set. This is called cascading. - - For example, the following style sheet specifies that all - \l{QLineEdit}s should use yellow as their background color, and - all \l{QCheckBox}es should use red as the text color: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 0 - - For this kind of customization, style sheets are much more - powerful than QPalette. For example, it might be tempting to set - the QPalette::Button role to red for a QPushButton to obtain a - red push button. However, this wasn't guaranteed to work for all - styles, because style authors are restricted by the different - platforms' guidelines and (on Windows XP and Mac OS X) by the - native theme engine. - - Style sheets let you perform all kinds of customizations that are - difficult or impossible to perform using QPalette alone. If you - want yellow backgrounds for mandatory fields, red text for - potentially destructive push buttons, or fancy check boxes, style - sheets are the answer. - - Style sheets are applied on top of the current \l{QStyle}{widget - style}, meaning that your applications will look as native as - possible, but any style sheet constraints will be taken into - consideration. Unlike palette fiddling, style sheets offer - guarantees: If you set the background color of a QPushButton to be - red, you can be assured that the button will have a red background - in all styles, on all platforms. In addition, \l{Qt Designer} - provides style sheet integration, making it easy to view the effects - of a style sheet in different \l{QStyle}{widget styles}. - - In addition, style sheets can be used to provide a distinctive - look and feel for your application, without having to subclass - QStyle. For example, you can specify arbitrary images for radio - buttons and check boxes to make them stand out. Using this - technique, you can also achieve minor customizations that would - normally require subclassing several style classes, such as - specifying a \l{QStyle::styleHint()}{style hint}. The - \l{widgets/stylesheet}{Style Sheet} example depicted below defines - two distinctive style sheets that you can try out and modify at - will. - - \table - \row \o \inlineimage stylesheet-coffee-xp.png - \o \inlineimage stylesheet-pagefold.png - \row \o Coffee theme running on Windows XP - \o Pagefold theme running on Windows XP - \endtable - - \table - \row \o \inlineimage stylesheet-coffee-cleanlooks.png - \o \inlineimage stylesheet-pagefold-mac.png - \row \o Coffee theme running on Ubuntu Linux - \o Pagefold theme running on Mac OS X - \endtable - - When a style sheet is active, the QStyle returned by QWidget::style() - is a wrapper "style sheet" style, \e not the platform-specific style. The - wrapper style ensures that any active style sheet is respected and - otherwise forwards the drawing operations to the underlying, - platform-specific style (e.g., QWindowsXPStyle on Windows XP). - - Since Qt 4.5, Qt style sheets fully supports Mac OS X. - - \warning Qt style sheets are currently not supported for custom QStyle - subclasses. We plan to address this in some future release. -*/ - -/*! - \page stylesheet-syntax.html - \contentspage {Qt Style Sheet}{Contents} - \previouspage Qt Style Sheet - \nextpage Qt Designer Integration - \title The Style Sheet Syntax - - Qt Style Sheet terminology and syntactic rules are almost - identical to those of HTML CSS. If you already know CSS, you can - probably skim quickly through this section. - - \tableofcontents - - \section1 Style Rules - - Style sheets consist of a sequence of style rules. A \e{style - rule} is made up of a selector and a declaration. The - \e{selector} specifies which widgets are affected by the rule; - the \e{declaration} specifies which properties should be set on - the widget. For example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 1 - - In the above style rule, \c QPushButton is the selector and \c{{ - color: red }} is the declaration. The rule specifies that - QPushButton and its subclasses (e.g., \c MyPushButton) should use - red as their foreground color. - - Qt Style Sheet is generally case insensitive (i.e., \c color, - \c Color, \c COLOR, and \c cOloR refer to the same property). - The only exceptions are class names, - \l{QObject::setObjectName()}{object names}, and Qt property - names, which are case sensitive. - - Several selectors can be specified for the same declaration, - using commas (\c{,}) to separate the selectors. For example, - the rule - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 2 - - is equivalent to this sequence of three rules: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 3 - - The declaration part of a style rule is a list of - \tt{\e{property}: \e{value}} pairs, enclosed in braces (\c{{}}) - and separated with semicolons. For example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 4 - - See the \l{List of Properties} section below for the list of - properties provided by Qt widgets. - - \section1 Selector Types - - All the examples so far used the simplest type of selector, the - Type Selector. Qt Style Sheets support all the - \l{http://www.w3.org/TR/REC-CSS2/selector.html#q1}{selectors - defined in CSS2}. The table below summarizes the most useful - types of selectors. - - \table 100% - \header - \o Selector - \o Example - \o Explanation - - \row - \o Universal Selector - \o \c * - \o Matches all widgets. - - \row - \o Type Selector - \o \c QPushButton - \o Matches instances of QPushButton and of its subclasses. - - \row - \o Property Selector - \o \c{QPushButton[flat="false"]} - \o Matches instances of QPushButton that are not - \l{QPushButton::}{flat}. You may use this selector to test - for any Qt \l{Qt's Property System}{property} that supports - QVariant::toString() (see the \l{QVariant::}{toString()} - function documentation for details). In addition, the - special \c class property is supported, for the name of the - class. - - This selector may also be used to test dynamic properties. - For more information on customization using dynamic properties, - refer to \l{Customizing Using Dynamic Properties}. - - Instead of \c =, you can also use \c ~= to test whether a - Qt property of type QStringList contains a given QString. - - \warning If the value of the Qt property changes after the - style sheet has been set, it might be necessary to force a - style sheet recomputation. One way to achieve this is to - unset the style sheet and set it again. - - \row - \o Class Selector - \o \c .QPushButton - \o Matches instances of QPushButton, but not of its subclasses. - - This is equivalent to \c{*[class~="QPushButton"]}. - - \row - \o ID \target ID Selector - Selector - \o \c{QPushButton#okButton} - \o Matches all QPushButton instances whose - \l{QObject::objectName}{object name} is \c okButton. - - \row - \o Descendant Selector - \o \c{QDialog QPushButton} - \o Matches all instances of QPushButton that are descendants - (children, grandchildren, etc.) of a QDialog. - - \row - \o Child Selector - \o \c{QDialog > QPushButton} - \o Matches all instances of QPushButton that are direct - children of a QDialog. - \endtable - - \section1 Sub-Controls - - For styling complex widgets, it is necessary to access subcontrols of the - widget, such as the drop-down button of a QComboBox or the up and down - arrows of a QSpinBox. Selectors may contain \e{subcontrols} that make it - possible to restrict the application of a rule to specific widget - subcontrols. For example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 5 - - The above rule styles the drop-down button of all \l{QComboBox}es. - Although the double-colon (\c{::}) syntax is reminiscent of CSS3 - Pseudo-Elements, Qt Sub-Controls differ conceptually from these and have - different cascading semantics. - - Sub-controls are always positioned with respect to another element - a - reference element. This reference element could be the widget or another - Sub-control. For example, the \l{Qt Style Sheets Reference#drop-down-sub} - {::drop-down} of a QComboBox is placed, by default, in the top right corner - of the Padding rectangle of the QComboBox. The - \l{Qt Style Sheets Reference#drop-down-sub}{::drop-down} is placed, - by default, in the Center of the Contents rectangle of the - \l{Qt Style Sheets Reference#drop-down-sub}{::drop-down} Sub-control. See - the \l{List of Stylable Widgets} below for the Sub-controls to use to - style a widget and their default positions. - - The origin rectangle to be used can be changed using the - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} - property. For example, if we want to place the drop-down in the margin - rectangle of the QComboBox instead of the default Padding rectangle, we - can specify: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 6 - - The alignment of the drop-down within the Margin rectangle is changed - using \l{Qt Style Sheets Reference#subcontrol-position-prop} - {subcontrol-position} property. - - The \l{Qt Style Sheets Reference#width-prop}{width} and - \l{Qt Style Sheets Reference#height-prop}{height} properties can be used - to control the size of the Sub-control. Note that setting a - \l{Qt Style Sheets Reference#image-prop}{image} implicitly sets the size - of a Sub-control. - - The relative positioning scheme - (\l{Qt Style Sheets Reference#position-prop}{position} : relative), - allows the position of the Sub-Control to be offset from its initial - position. For example, when the QComboBox's drop-down button is - pressed, we might like the arrow inside to be offset to give a - "pressed" effect. To achieve this, we can specify: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 7 - - The absolute positioning scheme - (\l{Qt Style Sheets Reference#position-prop}{position} : absolute), - allows the position and size of the Sub-control to be changed with - respect to the reference element. - - Once positioned, they are treated the same as widgets and can be styled - using the \l{box model}. - - See the \l{List of Sub-Controls} below for a list of supported - sub-controls, and \l{Customizing the QPushButton's Menu Indicator - Sub-Control} for a realistic example. - - \note With complex widgets such as QComboBox and QScrollBar, if one - property or sub-control is customized, \bold{all} the other properties or - sub-controls must be customized as well. - - \section1 Pseudo-States - - Selectors may contain \e{pseudo-states} that denote that restrict - the application of the rule based on the widget's state. - Pseudo-states appear at the end of the selector, with a colon - (\c{:}) in between. For example, the following rule applies when - the mouse hovers over a QPushButton: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 8 - - Pseudo-states can be negated using the exclamation operator. For - example, the following rule applies when the mouse does not hover - over a QRadioButton: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 9 - - Pseudo-states can be chained, in which case a logical AND is - implied. For example, the following rule applies to when the - mouse hovers over a checked QCheckBox: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 10 - - Negated Pseudo-states may appear in Pseudo-state chains. For example, - the following rule applies when the mouse hovers over a QPushButton - that is not pressed: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 11 - - If needed, logical OR can be expressed using the comma operator: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 12 - - Pseudo-states can appear in combination with subcontrols. For - example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 13 - - See the \l{List of Pseudo-States} section below for the list of - pseudo-states provided by Qt widgets. - - \section1 Conflict Resolution - - Conflicts arise when several style rules specify the same - properties with different values. Consider the following style - sheet: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 14 - - Both rules match QPushButton instances called \c okButton and - there is a conflict for the \c color property. To resolve this - conflict, we must take into account the \e specificity of the - selectors. In the above example, \c{QPushButton#okButton} is - considered more specific than \c QPushButton, because it - (usually) refers to a single object, not to all instances of a - class. - - Similarly, selectors with pseudo-states are more specific than - ones that do not specify pseudo-states. Thus, the following style - sheet specifies that a \l{QPushButton} should have white text - when the mouse is hovering over it, otherwise red text: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 15 - - Here's a tricky one: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 16 - - Here, both selectors have the same specificity, so if the mouse - hovers over the button while it is enabled, the second rule takes - precedence. If we want the text to be white in that case, we can - reorder the rules like this: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 17 - - Alternatively, we can make the first rule more specific: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 18 - - A similar issue arises in conjunction with Type Selectors. - Consider the following example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 19 - - Both rules apply to QPushButton instances (since QPushButton - inherits QAbstractButton) and there is a conflict for the - \l{Qt Style Sheets Reference#color-prop}{color} property. Because QPushButton - inherits QAbstractButton, it might be tempting to assume that - \c QPushButton is more specific than \c QAbstractButton. However, - for style sheet computations, all Type Selectors have the same - specificity, and the rule that appears last takes precedence. In - other words, \l{Qt Style Sheets Reference#color-prop}{color} is set to \c gray - for all \l{QAbstractButton}s, including \l{QPushButton}s. If we really - want \l{QPushButton}s to have red text, we can always reorder the - rules. - - For determining the specificity of a rule, Qt Style Sheets follow - the - \l{http://www.w3.org/TR/REC-CSS2/cascade.html#specificity}{CSS2 - Specification}: - - \quotation - \e{A selector's specificity is calculated as follows:} - - \list - \o \e{count the number of ID attributes in the selector (= a)} - \o \e{count the number of other attributes and pseudo-classes in the selector (= b)} - \o \e{count the number of element names in the selector (= c)} - \o \e{ignore pseudo-elements [i.e., \l{subcontrols}].} - \endlist - - \e{Concatenating the three numbers a-b-c (in a number system with a - large base) gives the specificity.} - - \e{Some examples:} - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 20 - \endquotation - - \section1 Cascading - - Style sheets can be set on the QApplication, on parent widgets, - and on child widgets. An arbitrary widget's effective style sheet - is obtained by merging the style sheets set on the widget's - ancestors (parent, grandparent, etc.), as well as any style sheet - set on the QApplication. - - When conflicts arise, the widget's own style sheet is always - preferred to any inherited style sheet, irrespective of the - specificity of the conflicting rules. Likewise, the parent - widget's style sheet is preferred to the grandparent's, etc. - - One consequence of this is that setting a style rule on a widget - automatically gives it precedence over other rules specified in - the ancestor widgets' style sheets or the QApplication style - sheet. Consider the following example. First, we set a style - sheet on the QApplication: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 21 - - Then we set a style sheet on a QPushButton object: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 22 - - The style sheet on the QPushButton forces the QPushButton (and - any child widget) to have blue text, in spite of the more - specific rule set provided by the application-wide style sheet. - - The result would have been the same if we had written - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 23 - - except that if the QPushButton had children (which is unlikely), - the style sheet would have no impact on them. - - Style sheet cascading is a complex topic. Refer to the - \l{http://www.w3.org/TR/CSS2/cascade.html#cascade}{CSS2 - Specification} for the gory details. Be aware that Qt currently - doesn't implement \c{!important}. - - \section1 Inheritance - - In classic CSS, when font and color of an item is not explicitly set, - it gets automatically inherited from the parent. When using Qt Style Sheets, - a widget does \bold{not} automatically inherit its font and color setting - from its parent widget. - - For example, consider a QPushButton inside a QGroupBox: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 24 - - The QPushButton does not have an explicit color set. Hence, instead - of inheriting color of its parent QGroupBox, it has the system color. - If we want to set the color on a QGroupBox and its children, - we can write: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 25 - - In contrast, setting a font and propagate using QWidget::setFont() and - QWidget::setPalette() propagates to child widgets. - - \section1 Widgets inside C++ namespaces - - The Type Selector can be used to style widgets of a particular type. For - example, - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 26 - - Qt Style Sheet uses QObject::className() of the widget to determine - when to apply the Type Selector. When custom widgets are inside namespaces, - the QObject::className() returns ::. This conflicts - with the syntax for \l{Sub-Controls}. To overcome this problem, - when using the Type Selector for widgets inside namespaces, we must - replace the "::" with "--". For example, - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 27 - - \section1 Setting QObject properties - - From 4.3 and above, any designable Q_PROPERTY - can be set using the qproperty- syntax. - - For example, - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 28 - - If the property references an enum declared with Q_ENUMS, you should - reference its constants by name, i.e., not their numeric value. - -*/ - -/*! - \page stylesheet-designer.html - \contentspage {Qt Style Sheet}{Contents} - \previouspage The Style Sheet Syntax - \nextpage Customizing Qt Widgets Using Style Sheets - \title Qt Designer Integration - - \l{Qt Designer}{Qt Designer} is an excellent tool - to preview style sheets. You can right-click on any widget in Designer - and select \gui{Change styleSheet...} to set the style sheet. - - \image designer-stylesheet-options.png - - In Qt 4.2 and later, \l{Qt Designer}{Qt Designer} also includes a - style sheet syntax highlighter and validator. The validator indicates - if the syntax is valid or invalid, at the bottom left of the \gui{Edit - Style Sheet} dialog. - - \image designer-validator-highlighter.png - - When you click \gui{OK} or \gui{Apply}, \QD will automatically display - the widget with its new stylesheet. - - \image designer-stylesheet-usage.png - */ - -/*! - \page stylesheet-customizing.html - \contentspage {Qt Style Sheet}{Contents} - \previouspage Qt Designer Integration - \nextpage Qt Style Sheets Reference - \title Customizing Qt Widgets Using Style Sheets - - When using style sheets, every widget is treated as a box with four - concentric rectangles: the margin rectangle, the border rectangle, the - padding rectangle, and the content rectangle. The box model describes - this in further detail. - - \tableofcontents - - \target box model - \section1 The Box Model - - The four concentric rectangles appear conceptually as below: - - \image stylesheet-boxmodel.png - - \list - \o The margin falls outside the border. - \o The border is drawn between the margin and the padding. - \o The padding falls inside the border, between the border and - the actual contents. - \o The content is what is left from the original widget or - subcontrol once we have removed the margin, the border, and - the padding. - \endlist - - The \l{Qt Style Sheets Reference#margin-prop}{margin}, - \l{Qt Style Sheets Reference#border-width-prop} - {border-width}, and - \l{Qt Style Sheets Reference#padding-prop}{padding} - properties all default to zero. In that case, all four rectangles - (\c margin, \c border, \c padding, and \c content) coincide exactly. - - You can specify a background for the widget using the - \l{Qt Style Sheets Reference#background-image-prop}{background-image} - property. By default, the background-image is drawn only for the area - inside the border. This can be changed using the - \l{Qt Style Sheets Reference#background-clip-prop}{background-clip} - property. You can use - \l{Qt Style Sheets Reference#background-repeat-prop}{background-repeat} - and - \l{Qt Style Sheets Reference#background-origin-prop}{background-origin} - to control the repetition and origin of the background image. - - A background-image does not scale with the size of the widget. To provide - a "skin" or background that scales along with the widget size, one must - use - \l{Qt Style Sheets Reference#border-image-prop}{border-image}. Since the - border-image property provides an alternate background, it is not required - to specify a background-image when border-image is specified. In the case, - when both of them are specified, the border-image draws over the - background-image. - - In addition, the \l{Qt Style Sheets Reference#image-prop}{image} property - may be used to draw an image over the border-image. The image specified does - not tile or stretch and when its size does not match the size of the widget, - its alignment is specified using the - \l{Qt Style Sheets Reference#image-position-prop}{image-position} - property. Unlike background-image and border-image, one may specify a - SVG in the image property, in which case the image is scaled automatically - according to the widget size. - - The steps to render a rule are as follows: - \list - \o Set clip for entire rendering operation (border-radius) - \o Draw the background (background-image) - \o Draw the border (border-image, border) - \o Draw overlay image (image) - \endlist - - \target sub controls - \section1 Sub-controls - - A widget is considered as a hierarchy (tree) of subcontrols drawn on top - of each other. For example, the QComboBox draws the drop-down sub-control - followed by the down-arrow sub-control. A QComboBox is thus rendered as - follows: - \list - \o Render the QComboBox { } rule - \o Render the QComboBox::drop-down { } rule - \o Render the QComboBox::down-arrow { } rule - \endlist - - Sub-controls share a parent-child relationship. In the case of QComboBox, - the parent of down-arrow is the drop-down and the parent of drop-down is - the widget itself. Sub-controls are positioned within their parent using - the \l{Qt Style Sheets Reference#subcontrol-position-prop} - {subcontrol-position} and - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} - properties. - - Once positioned, sub-controls can be styled using the \l{box model}. - - \note With complex widgets such as QComboBox and QScrollBar, if one - property or sub-control is customized, \bold{all} the other properties or - sub-controls must be customized as well. - -*/ - -/*! - \page stylesheet-reference.html - \contentspage {Qt Style Sheet}{Contents} - \previouspage Customizing Qt Widgets Using Style Sheets - \nextpage Qt Style Sheets Examples - \title Qt Style Sheets Reference - - Qt Style Sheets support various properties, pseudo-states, and - subcontrols that make it possible to customize the look of - widgets. - - \tableofcontents - - \section1 List of Stylable Widgets - - The following table lists the Qt widgets that can be customized - using style sheets: - - \table 100% - \header - \o Widget - \o How to Style - - \row - \o QAbstractScrollArea \target qabstractscrollarea-widget - \o Supports the \l{box model}. - - All derivatives of QAbstractScrollArea, including QTextEdit, - and QAbstractItemView (all item view classes), support - scrollable backgrounds using - \l{Qt Style Sheets Reference#background-attachment-prop} - {background-attachment}. Setting the background-attachment to - \c{fixed} provides a background-image that does not scroll with the - viewport. Setting the background-attachment to \c{scroll}, scrolls - the background-image when the scroll bars move. - - See \l{Qt Style Sheets Examples#Customizing QAbstractScrollArea} - {Customizing QAbstractScrollArea} for an example. - - \row - \o QCheckBox \target qcheckbox-widget - \o Supports the \l{box model}. The check indicator can be - styled using the \l{#indicator-sub}{::indicator} - subcontrol. By default, the indicator is placed in the Top - Left corner of the Contents rectangle of the widget. - - The \l{#spacing-prop}{spacing} property - specifies the spacing between the check indicator and - the text. - - See \l{Qt Style Sheets Examples#Customizing QCheckBox} - {Customizing QCheckBox} for an example. - - \row - \o QColumnView \target qcolumnview-widget - \o The grip can be styled be using the \l{image-prop}{image} property. - The arrow indicators can by styled using the - \l{left-arrow-sub}{::left-arrow} subcontrol and the - \l{right-arrow-sub}{::right-arrow} subcontrol. - - \row - \o QComboBox \target qcombobox-widget - \o The frame around the combobox can be styled using the - \l{box model}. The drop-down button can be styled using - the \l{#drop-down-sub}{::drop-down} subcontrol. By default, the - drop-down button is placed in the top right corner of the padding - rectangle of the widget. The arrow mark inside the drop-down button - can be styled using the \l{#down-arrow-sub}{::down-arrow} - subcontrol. By default, the arrow is placed in the center of the - contents rectangle of the drop-down subcontrol. - - See \l{Qt Style Sheets Examples#Customizing QComboBox}{Customizing QComboBox} - for an example. - - \row - \o QDateEdit \target qdateedit-widget - \o See \l{#qspinbox-widget}{QSpinBox}. - - \row - \o QDateTimeEdit \target qdatetimeedit-widget - \o See \l{#qspinbox-widget}{QSpinBox}. - - \row - \o QDialog \target qdialog-widget - \o Supports only the \l{Qt Style Sheets Reference#background-prop}{background}, - \l{#background-clip-prop}{background-clip} and - \l{#background-origin-prop}{background-origin} properties. - - \warning Make sure you define the Q_OBJECT macro for your custom - widget. - - \row - \o QDialogButtonBox \target qdialogbuttonbox-widget - \o The layout of buttons can be altered using the - \l{#button-layout-prop}{button-layout} property. - - \row - \o QDockWidget \target qdockwidget-widget - \o Supports styling of the title bar and the title bar buttons when docked. - - The dock widget border can be styled using the \l{#border-prop}{border} - property. The \l{#title-sub}{::title} subcontrol can be used to customize - the title bar. The close and float buttons are positioned with respect - to the \l{title-sub}{::title} subcontrol using the - \l{#close-button-sub}{::close-button} and - \l{#float-button-sub}{::float-button} respectively. - - When the title bar is vertical, the \l{#vertical-ps}{:vertical} pseudo - class is set. In addition, depending on QDockWidget::DockWidgetFeature, - the \l{#closable-ps}{:closable}, \l{#floatable-ps}{:floatable} and - \l{#movable-ps}{:movable} pseudo states are set. - - \note Use QMainWindow::separator to style the resize handle. - - \warning The style sheet has no effect when the QDockWidget is undocked - as Qt uses native top level windows when undocked. - - See \l{Qt Style Sheets Examples#Customizing QDockWidget} - {Customizing QDockWidget} for an example. - - \row - \o QDoubleSpinBox \target qdoublespinbox-widget - \o See \l{#qspinbox-widget}{QSpinBox}. - - \row - \o QFrame \target qframe-widget - \o Supports the \l{box model}. - - Since 4.3, setting a stylesheet on a QLabel automatically - sets the QFrame::frameStyle property to QFrame::StyledPanel. - - See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} - for an example. - - \row - \o QGroupBox \target qgroupbox-widget - \o Supports the \l{box model}. The title can be styled using the - \l{#title-sub}{::title} subcontrol. By default, the title is placed - depending on QGroupBox::textAlignment. - - In the case of a checkable QGroupBox, the title includes the - check indicator. The indicator is styled using the - the \l{#indicator-sub}{::indicator} subcontrol. The - \l{#spacing-prop}{spacing} property can be used to control - the spacing between the text and indicator. - - See \l{Qt Style Sheets Examples#Customizing QGroupBox}{Customizing QGroupBox} - for an example. - - \row - \o QHeaderView \target qheaderview-widget - \o Supports the \l{box model}. The sections of the header view are - styled using the \l{#section-sub}{::section} sub control. The - \c{section} Sub-control supports the \l{#middle-ps}{:middle}, - \l{#first-ps}{:first}, \l{#last-ps}{:last}, - \l{#only-one-ps}{:only-one}, \l{#next-selected-ps}{:next-selected}, - \l{#previous-selected-ps}{:previous-selected}, - \l{#selected-ps}{:selected}, - and \l{#checked-ps}{:checked} pseudo states. - - Sort indicator in can be styled using the - \l{#up-arrow-sub}{::up-arrow} and the - \l{#down-arrow-sub}{::down-arrow} Sub-control. - - See \l{Qt Style Sheets Examples#Customizing QHeaderView}{Customizing QHeaderView} - for an example. - - \row - \o QLabel \target qlabel-widget - \o Supports the \l{box model}. Does not support the - \l{#hover-ps}{:hover} pseudo-state. - - Since 4.3, setting a stylesheet on a QLabel automatically - sets the QFrame::frameStyle property to QFrame::StyledPanel. - - See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} for an - example (a QLabel derives from QFrame). - - \row - \o QLineEdit \target qlineedit-widget - \o Support the \l{box model}. - - The color and background of the selected item is styled using - \l{#selection-color-prop}{selection-color} and - \l{#selection-background-color-prop}{selection-background-color} - respectively. - - The password character can be styled using the - \l{#lineedit-password-character-prop}{lineedit-password-character} - property. - - See \l{Qt Style Sheets Examples#Customizing QLineEdit}{Customizing QLineEdit} - for an example. - - \row - \o QListView \target qlistview-widget - \o Supports the \l{box model}. When - \l{QAbstractItemView::alternatingRowColors}{alternating row colors} - is enabled, the alternating colors can be styled using the - \l{#alternate-background-color-prop}{alternate-background-color} - property. - - The color and background of the selected item is styled using - \l{#selection-color-prop}{selection-color} and - \l{#selection-background-color-prop}{selection-background-color} - respectively. - - The selection behavior is controlled by the - \l{#show-decoration-selected-prop}{show-decoration-selected} property. - - Use the \l{#item-sub}{::item} subcontrol for more fine grained - control over the items in the QListView. - - See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to - style scrollable backgrounds. - - See \l{Qt Style Sheets Examples#Customizing QListView} - {Customzing QListView} for an example. - - \row - \o QListWidget \target qlistwidget-widget - \o See \l{#qlistview-widget}{QListView}. - - \row - \o QMainWindow \target qmainwindow-widget - \o Supports styling of the separator - - The separator in a QMainWindow when using QDockWidget is styled - using the \l{#separator-sub}{::separator} subcontrol. - - See \l{Qt Style Sheets Examples#Customizing QMainWindow}{Customizing QMainWindow} - for an example. - - \row - \o QMenu \target qmenu-widget - \o Supports the \l{box model}. - - Individual items are styled using the \l{#item-sub}{::item} - subcontrol. In addition to the usually supported pseudo states, - \c{item} subcontrol supports the - \l{#selected-ps}{:selected}, \l{#default-ps}{:default}, - \l{#exclusive-ps}{:exclusive} and the - \l{#non-exclusive-ps}{non-exclusive} pseudo states. - - The indicator of checkable menu items is styled using the - \l{#indicator-sub}{::indicator} subcontrol. - - The separator is styled using the \l{#separator-sub}{::separator} - subcontrol. - - For items with a sub menu, the arrow marks are styled using the - \l{right-arrow-sub}{right-arrow} and - \l{left-arrow-sub}{left-arrow}. - - The scroller is styled using the \l{#scroller-sub}{::scroller}. - - The tear-off is styled using the \l{#tearoff-sub}{::tearoff}. - - See \l{Qt Style Sheets Examples#Customizing QMenu}{Customizing QMenu} - for an example. - - \row - \o QMenuBar \target qmenubar-widget - \o Supports the \l{box model}. The \l{#spacing-prop}{spacing} - property specifies the spacing between menu items. - Individual items are styled using the \l{#item-sub}{::item} - subcontrol. - - \warning When running on Qt/Mac, the menu bar is usually embedded into the - system-wide menu bar. In this case, the style sheet will have no effect. - - See \l{Qt Style Sheets Examples#Customizing QMenuBar}{Customizing QMenuBar} - for an example. - - \row - \o QMessageBox \target qmessagebox-widget - \o The \l{#messagebox-text-interaction-flags-prop} - {messagebox-text-interaction-flags} property can be used to alter - the interaction with text in the message box. - - \row - \o QProgressBar \target qprogressbar-widget - \o Supports the \l{box model}. The chunks of the progress bar - can be styled using the \l{#chunk-sub}{::chunk} subcontrol. - The chunk is displayed on the Contents rectangle of the widget. - - If the progress bar displays text, use the \l{text-align-prop}{text-align} - property to position the text. - - Indeterminate progress bars have the - \l{#indeterminate-ps}{:indeterminate} pseudo state set. - - See \l{Qt Style Sheets Examples#Customizing QProgressBar}{Customizing QProgressBar} - for an example. - - \row - \o QPushButton \target qpushbutton-widget - \o Supports the \l{box model}. Supports the \l{#default-ps}{:default}, - \l{#flat-ps}{:flat}, \l{#checked-ps}{:checked} pseudo states. - - For QPushButton with a menu, the menu indicator is styled - using the \l{#menu-indicator-sub}{::menu-indicator} - subcontrol. Appearance of checkable push buttons can be - customized using the \l{#open-ps}{:open} and - \l{#closed-ps}{:closed} pseudo-states. - - \warning If you only set a background-color on a QPushButton, the background - may not appear unless you set the border property to some value. This is - because, by default, the QPushButton draws a native border which completely - overlaps the background-color. For example, - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 30 - - See \l{Qt Style Sheets Examples#Customizing QPushButton}{Customizing QPushButton} - for an example. - - \row - \o QRadioButton \target qradiobutton-widget - \o Supports the \l{box model}. The check indicator can be - styled using the \l{#indicator-sub}{::indicator} - subcontrol. By default, the indicator is placed in the Top - Left corner of the Contents rectangle of the widget. - - The \l{#spacing-prop}{spacing} property - specifies the spacing between the check indicator and - the text. - - See \l{Qt Style Sheets Examples#Customizing QRadioButton} - {Customizing QRadioButton} for an example. - - \row - \o QScrollBar \target qscrollbar-widget - \o Supports the \l{box model}. The Contents rectangle of the widget - is considered to be the groove over which the slider moves. The extent - of the QScrollBar (i.e the width or the height depending on the orientation) - is set using the \l{#width-prop}{width} or \l{#height-prop}{height} property - respectively. To determine the orientation, use the - \l{#horizontal-ps}{:horizontal} and the \l{vertical-ps}{:vertical} - pseudo states. - - The slider can be styled using the \l{#handle-sub}{::handle} subcontrol. - Setting the \l{#min-width-prop}{min-width} or \l{#min-height-prop}{min-height} - provides size contraints for the slider depending on the orientation. - - The \l{add-line-sub}{::add-line} subcontrol can be used to style the - button to add a line. By default, the add-line subcontrol is placed in - top right corner of the Border rectangle of the widget. Depending on the - orientation the \l{#right-arrow-sub}{::right-arrow} or - \l{#down-arrow-sub}{::down-arrow}. By default, the arrows are placed in - the center of the Contents rectangle of the add-line subcontrol. - - The \l{sub-line-sub}{::sub-line} subcontrol can be used to style the - button to subtract a line. By default, the sub-line subcontrol is placed in - bottom right corner of the Border rectangle of the widget. Depending on the - orientation the \l{#left-arrow-sub}{::left-arrow} or - \l{#up-arrow-sub}{::up-arrow}. By default, the arrows are placed in - the center of the Contents rectangle of the sub-line subcontrol. - - The \l{sub-page-sub}{::sub-page} subcontrol can be used to style the - region of the slider that subtracts a page. The \l{add-page-sub}{::add-page} - subcontrol can be used to style the region of the slider that adds a page. - - See \l{Qt Style Sheets Examples#Customizing QScrollBar}{Customizing QScrollBar} - for an example. - - \row - \o QSizeGrip \target qsizegrip-widget - \o Supports the \l{#width-prop}{width}, - \l{#height-prop}{height}, and \l{#image-prop}{image} - properties. - - See \l{Qt Style Sheets Examples#Customizing QSizeGrip}{Customizing QSizeGrip} - for an example. - - \row - \o QSlider \target qslider-widget - \o Supports the \l{box model}. For horizontal slides, the - \l{min-width-prop}{min-width} and \l{height-prop}{height} - properties must be provided. For vertical sliders, the - \l{min-height-prop}{min-height} and \l{width-prop}{width} - properties must be provided. - - The groove of the slider is styled - using the \l{#groove-sub}{::groove}. The groove is - positioned by default in the Contents rectangle of the widget. - The thumb of the slider is styled using \l{#handle-sub}{::handle} - subcontrol. The subcontrol moves in the Contents rectangle of - the groove subcontrol. - - See \l{Qt Style Sheets Examples#Customizing QSlider}{Customizing QSlider} - for an example. - - \row - \o QSpinBox \target qspinbox-widget - \o The frame of the spin box can be styled using the \l{box - model}. - - The up button and arrow can be styled using the - \l{#up-button-sub}{::up-button} and - \l{#up-arrow-sub}{::up-arrow} subcontrols. By default, - the up-button is placed in the top right corner in the - Padding rectangle of the widget. Without an explicit size, - it occupies half the height of its reference rectangle. - The up-arrow is placed in the center of the Contents - rectangle of the up-button. - - The down button and arrow can be styled using the - \l{#down-button-sub}{::down-button} and - \l{#down-arrow-sub}{::down-arrow} subcontrols. By default, - the down-button is placed in the bottom right corner in the - Padding rectangle of the widget. Without an explicit size, - it occupies half the height of its reference rectangle. - The bottom-arrow is placed in the center of the Contents - rectangle of the bottom-button. - - See \l{Qt Style Sheets Examples#Customizing QSpinBox}{Customizing QSpinBox} - for an example. - - \row - \o QSplitter \target qsplitter-widget - \o Supports the \l{box model}. The handle of the splitter - is styled using the \l{#handle-sub}{::handle} subcontrol. - - See \l{Qt Style Sheets Examples#Customizing QSplitter}{Customizing QSplitter} - for an example. - - \row - \o QStatusBar \target qstatusbar-widget - \o Supports only the \l{Qt Style Sheets Reference#background-prop} - {background} property. - The frame for individual items can be style using the - \l{#item-sub}{::item} subcontrol. - - See \l{Qt Style Sheets Examples#Customizing QStatusBar}{Customizing QStatusBar} - for an example. - - \row - \o QTabBar \target qtabbar-widget - \o Individual tabs may be styled using the \l{#tab-sub}{::tab} subcontrol. - Close buttons using the \l{#close-button-sub}{::close-button} - The tabs support the - \l{#only-one-ps}{:only-one}, \l{#first-ps}{:first}, - \l{#last-ps}{:last}, \l{#middle-ps}{:middle}, - \l{#previous-selected-ps}{:previous--selected}, - \l{#next-selected-ps}{:next-selected}, - \l{#selected-ps}{:selected} pseudo states. - - The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right}, - \l{#bottom-ps}{:bottom} pseudo states depending on the orientation - of the tabs. - - Overlapping tabs for the selected state are created by using - negative margins or using the \c{absolute} position scheme. - - The tear indicator of the QTabBar is styled using the - \l{#tear-sub}{::tear} subcontrol. - - QTabBar used two QToolButtons for its scrollers that can be styled - using the \c{QTabBar QToolButton} selector. To specify the width - of the scroll button use the \l{#scroller-sub}{::scroller} - subcontrol. - - The alignment of the tabs within the QTabBar is styled - using the \l{#Alignment}{alignment} property. \warning - - To change the position of the QTabBar within a QTabWidget, use the - \l{#tab-bar-sub}{tab-bar} subcontrol (and set subcontrol-position). - - See \l{Qt Style Sheets Examples#Customizing QTabWidget and QTabBar}{Customizing QTabBar} - for an example. - - \row - \o QTabWidget \target qtabwidget-widget - \o The frame of the tab widget is styled using the - \l{#pane-sub}{::pane} subcontrol. The left and right - corners are styled using the \l{#left-corner-sub}{::left-corner} - and \l{#right-corner-sub}{::right-corner} respectively. - The position of the tab bar is controlled using the - \l{#tab-bar-sub}{::tab-bar} subcontrol. - - By default, the subcontrols have positions of a QTabWidget in - the QWindowsStyle. To place the QTabBar in the center, set the - subcontrol-position of the tab-bar subcontrol. - - The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right}, - \l{#bottom-ps}{:bottom} pseudo states depending on the orientation - of the tabs. - - See \l{Qt Style Sheets Examples#Customizing QTabWidget and QTabBar} - {Customizing QTabWidget} for an example. - - \row - \o QTableView \target qtableview-widget - \o Supports the \l{box model}. When - \l{QAbstractItemView::alternatingRowColors}{alternating row colors} - is enabled, the alternating colors can be styled using the - \l{#alternate-background-color-prop}{alternate-background-color} - property. - - The color and background of the selected item is styled using - \l{#selection-color-prop}{selection-color} and - \l{#selection-background-color-prop}{selection-background-color} - respectively. - - The corner widget in a QTableView is implemented as a QAbstractButton - and can be styled using the "QTableView QTableCornerButton::section" - selector. - - \warning If you only set a background-color on a QTableCornerButton, - the background may not appear unless you set the border property to - some value. This is because, by default, the QTableCornerButton draws a - native border which completely overlaps the background-color. - - The color of the grid can be specified using the - \l{#gridline-color-prop}{gridline-color} property. - - See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to - style scrollable backgrounds. - - See \l{Qt Style Sheets Examples#Customizing QTableView} - {Customzing QTableView} for an example. - - \row - \o QTableWidget \target qtablewidget-widget - \o See \l{#qtableview-widget}{QTableView}. - - \row - \o QTextEdit \target qtextedit-widget - \o Supports the \l{box model}. - - The color and background of selected text is styled using - \l{#selection-color-prop}{selection-color} and - \l{#selection-background-color-prop}{selection-background-color} - respectively. - - See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to - style scrollable backgrounds. - - \row - \o QTimeEdit \target qtimeedit-widget - \o See \l{#qspinbox-widget}{QSpinBox}. - - \row - \o QToolBar \target qtoolbar-widget - \o Supports the \l{box model}. - - The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right}, - \l{#bottom-ps}{:bottom} pseudo states depending on the area in - which the tool bar is grouped. - - The \l{#first-ps}{:first}, \l{#last-ps}{:last}, \l{#middle-ps}{:middle}, - \l{#only-one-ps}{:only-one} pseudo states indicator the position - of the tool bar within a line group (See - QStyleOptionToolBar::positionWithinLine). - - The separator of a QToolBar is styled using the - \l{#separator-sub}{::separator} subcontrol. - - The handle (to move the toolbar) is styled using the - \l{#handle-sub}{::handle} subcontrol. - - See \l{Qt Style Sheets Examples#Customizing QToolBar}{Customizing QToolBar} - for an example. - - \row - \o QToolButton \target qtoolbutton-widget - \o Supports the \l{box model}. - - If the QToolButton has a menu, is - \l{#menu-indicator-sub}{::menu-indicator} subcontrol can be used to - style the indicator. By default, the menu-indicator is positioned - at the bottom right of the Padding rectangle of the widget. - - If the QToolButton is in QToolButton::MenuButtonPopup mode, - the \l{#menu-button-sub}{::menu-button} subcontrol is used to draw the - menu button. \l{#menu-arrow-sub}{::menu-arrow} subcontrol is used to - draw the menu arrow inside the menu-button. By default, it is - positioned in the center of the Contents rectangle of the - menu-button subcontrol. - - When the QToolButton displays arrows, the \l{#up-arrow-sub}{::up-arrow}, - \l{#down-arrow-sub}{::down-arrow}, \l{#left-arrow-sub}{::left-arrow} - and \l{#right-arrow-sub}{::right-arrow} subcontrols are used. - - \warning If you only set a background-color on a QToolButton, the background - will not appear unless you set the border property to some value. This is - because, by default, the QToolButton draws a native border which completely - overlaps the background-color. For example, - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 31 - - See \l{Qt Style Sheets Examples#Customizing QToolButton}{Customizing QToolButton} - for an example. - - \row - \o QToolBox \target qtoolbox-widget - \o Supports the \l{box model}. - - The individual tabs can by styled using the - \l{#tab-sub}{::tab} subcontrol. The tabs support the - \l{#only-one-ps}{:only-one}, \l{#first-ps}{:first}, - \l{#last-ps}{:last}, \l{#middle-ps}{:middle}, - \l{#previous-selected-ps}{:previous-selected}, - \l{#next-selected-ps}{:next-selected}, - \l{#selected-ps}{:selected} pseudo states. - - \row - \o QToolTip \target qtooltip-widget - \o Supports the \l{box model}. The \l{#opacity-prop}{opacity} - property controls the opacity of the tooltip. - - See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} - for an example (a QToolTip is a QFrame). - - \row - \o QTreeView \target qtreeview-widget - \o Supports the \l{box model}. When - \l{QAbstractItemView::alternatingRowColors}{alternating row colors} - is enabled, the alternating colors can be styled using the - \l{#alternate-background-color-prop}{alternate-background-color} - property. - - The color and background of the selected item is styled using - \l{#selection-color-prop}{selection-color} and - \l{#selection-background-color-prop}{selection-background-color} - respectively. - - The selection behavior is controlled by the - \l{#show-decoration-selected-prop}{show-decoration-selected} property. - - The branches of the tree view can be styled using the - \l{#branch-sub}{::branch} subcontrol. The - ::branch Sub-control supports the \l{open-ps}{:open}, - \l{closed-ps}{:closed}, \l{has-siblings-ps}{:has-sibling} and - \l{has-children-ps}{:has-children} pseudo states. - - Use the \l{#item-sub}{::item} subcontrol for more fine grained - control over the items in the QTreeView. - - See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to - style scrollable backgrounds. - - See \l{Qt Style Sheets Examples#Customizing QTreeView}{Customizing QTreeView} - for an example to style the branches. - - \row - \o QTreeWidget \target qtreewidget-widget - \o See \l{#qtreeview-widget}{QTreeView}. - - \row - \o QWidget \target qwidget-widget - \o Supports only the \l{Qt Style Sheets Reference#background-prop}{background}, - \l{#background-clip-prop}{background-clip} and - \l{#background-origin-prop}{background-origin} properties. - - If you subclass from QWidget, you need to provide a paintEvent for your - custom QWidget as below: - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 32 - - The above code is a no-operation if there is no stylesheet set. - - \warning Make sure you define the Q_OBJECT macro for your custom - widget. - - \endtable - - \section1 List of Properties - - The table below lists all the properties supported by Qt Style - Sheets. Which values can be given to an property depend on the - \l{List of Property Types}{property's type}. Unless otherwise - specified, properties below apply to all widgets. Properties - marked with an asterisk * are specific to Qt and have no equivalent - in CSS2 or CSS3. - - \table 100% - \header - \o Property - \o Type - \o Description - - \row - \o \bold{\c alternate-background-color} \target alternate-background-color-prop - \o \l{#Brush}{Brush} \BR - \o The \l{QAbstractItemView::alternatingRowColors} - {alternate background color} used in QAbstractItemView subclasses. - - If this property is not set, the default value is - whatever is set for the palette's - \l{QPalette::}{AlternateBase} role. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 33 - - See also \l{Qt Style Sheets Reference#background-prop}{background} and - \l{#selection-background-color-prop}{selection-background-color}. - - \row - \o \bold{\c background} \target background-prop - \o \l{#Background}{Background} - \o Shorthand notation for setting the background. Equivalent - to specifying \c background-color, \c background-image, \c - background-repeat, and/or \c background-position. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QDialog, QFrame, QGroupBox, QLabel, QLineEdit, - QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, - QTextEdit, QToolTip, and plain \l{QWidget}s. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 34 - - - Often, it is required to set a fill pattern similar to the styles - in Qt::BrushStyle. You can use the background-color property for - Qt::SolidPattern, Qt::RadialGradientPattern, Qt::LinearGradientPattern - and Qt::ConicalGradientPattern. The other patterns are easily achieved - by creating a background image that contains the pattern. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 35 - - See also \l{#background-origin-prop}{background-origin}, - \l{#selection-background-color-prop}{selection-background-color}, - \l{#background-clip-prop}{background-clip}, - \l{#background-attachment-prop}{background-attachment} - and \l{#alternate-background-color-prop}{alternate-background-color}. - - \row - \o \c background-color \target background-color-prop - \o \l{#Brush}{Brush} \BR - \o The background color used for the widget. - - Examples: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 36 - - \row - \o \c background-image \target background-image-prop - \o \l{#Url}{Url} - \o The background image used for the widget. Semi-transparent - parts of the image let the \c background-color shine - through. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 37 - - \row - \o \c background-repeat \target background-repeat-prop - \o \l{#Repeat}{Repeat} - \o Whether and how the background image is repeated to fill - the \c background-origin rectangle. - - If this property is not specified, the background image - is repeated in both directions (\c repeat). - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 38 - - \row - \o \c background-position - \o \l{#Alignment}{Alignment} - \o The alignment of the background image within the \c - background-origin rectangle. - - If this property is not specified, the alignment is \c - top \c left. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 39 - - \row - \o \bold{\c background-attachment} \target background-attachment-prop - \o \l{#Attachment}{Attachment} - \o Determines whether the background-image in a QAbstractScrollArea - is scrolled or fixed with respect to the viewport. - By default, the background-image scrolls with the viewport. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 40 - - See also \l{Qt Style Sheets Reference#background-prop}{background} - - \row - \o \bold{\c background-clip} \target background-clip-prop - \o \l{#Origin}{Origin} - \o The widget's rectangle, in which the \c background is drawn. - - This property specifies the rectangle to which the \c background-color - and \c background-image are clipped. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QDialog, QFrame, QGroupBox, QLabel, - QPushButton, QRadioButton, QSplitter, QTextEdit, QToolTip, - and plain \l{QWidget}s. - - If this property is not specified, the default is \c - border. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 41 - - See also \l{Qt Style Sheets Reference#background-prop}{background}, - \l{#background-origin-prop}{background-origin} and \l{The Box Model}. - - \row - \o \bold{\c background-origin} \target background-origin-prop - \o \l{#Origin}{Origin} - \o The widget's background rectangle, to use in conjunction - with \c background-position and \c background-image. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QDialog, QFrame, QGroupBox, QLabel, - QPushButton, QRadioButton, QSplitter, QTextEdit, QToolTip, - and plain \l{QWidget}s. - - If this property is not specified, the default is \c - padding. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 42 - - See also \l{Qt Style Sheets Reference#background-prop}{background} and - \l{The Box Model}. - - \row - \o \bold{\c border} \target border-prop - \o \l{#Border}{Border} - \o Shorthand notation for setting the widget's border. Equivalent - to specifying \c border-color, \c border-style, and/or - \c border-width. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, - QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, - QTextEdit, QToolTip, and plain \l{QWidget}s. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 43 - - \row - \o \c border-top - \o \l{#Border}{Border} - \o Shorthand notation for setting the widget's top border. - Equivalent to specifying \c border-top-color, \c - border-top-style, and/or \c border-top-width. - - \row - \o \c border-right - \o \l{#Border}{Border} - \o Shorthand notation for setting the widget's right border. - Equivalent to specifying \c border-right-color, \c - border-right-style, and/or \c border-right-width. - - \row - \o \c border-bottom - \o \l{#Border}{Border} - \o Shorthand notation for setting the widget's bottom border. - Equivalent to specifying \c border-bottom-color, \c - border-bottom-style, and/or \c border-bottom-width. - - \row - \o \c border-left - \o \l{#Border}{Border} - \o Shorthand notation for setting the widget's left border. - Equivalent to specifying \c border-left-color, \c - border-left-style, and/or \c border-left-width. - - \row - \o \bold{\c border-color} \target border-attrs - \target border-color-prop - \o \l{#Box Colors}{Box Colors} - \o The color of all the border's edges. Equivalent to - specifying \c border-top-color, \c border-right-color, \c - border-bottom-color, and \c border-left-color. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, - QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, - QTextEdit, QToolTip, and plain \l{QWidget}s. - - If this property is not specified, it defaults to - \l{#color-prop}{color} (i.e., the widget's foreground - color). - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 44 - - See also \l{Qt Style Sheets Reference#border-style-prop}{border-style}, - \l{Qt Style Sheets Reference#border-width-prop}{border-width}, - \l{#border-image-prop}{border-image}, and \l{The Box Model}. - - \row - \o \c border-top-color - \o \l{#Brush}{Brush} \BR - \o The color of the border's top edge. - - \row - \o \c border-right-color - \o \l{#Brush}{Brush} \BR - \o The color of the border's right edge. - - \row - \o \c border-bottom-color - \o \l{#Brush}{Brush} \BR - \o The color of the border's bottom edge. - - \row - \o \c border-left-color - \o \l{#Brush}{Brush} \BR - \o The color of the border's left edge. - - \row - \o \bold{\c border-image} \target border-image-prop - \o \l{#Border Image}{Border Image} - \o The image used to fill the border. The image is cut into - nine parts and stretched appropriately if necessary. See - \l{#Border Image}{Border Image} for details. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, - QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, - QTextEdit and QToolTip. - - See also \l{#border-color-prop}{border-color}, - \l{Qt Style Sheets Reference#border-style-prop}{border-style}, - \l{Qt Style Sheets Reference#border-width-prop}{border-width}, and - \l{The Box Model}. - - \row - \o \bold{\c border-radius} \target border-radius-prop - \o \l{#Radius}{Radius} - \o The radius of the border's corners. Equivalent to - specifying \c border-top-left-radius, \c - border-top-right-radius, \c border-bottom-right-radius, - and \c border-bottom-left-radius. - - The border-radius clips the element's - \l{Qt Style Sheets Reference#background-prop}{background}. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, - and QToolTip. - - If this property is not specified, it defaults to 0. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 45 - - See also \l{Qt Style Sheets Reference#border-width-prop}{border-width} and - \l{The Box Model}. - - \row - \o \c border-top-left-radius - \o \l{#Radius}{Radius} - \o The radius of the border's top-left corner. - - \row - \o \c border-top-right-radius - \o \l{#Radius}{Radius} - \o The radius of the border's top-right corner. - - \row - \o \c border-bottom-right-radius - \o \l{#Radius}{Radius} - \o The radius of the border's bottom-right corner. Setting - this property to a positive value results in a rounded - corner. - - \row - \o \c border-bottom-left-radius - \o \l{#Radius}{Radius} - \o The radius of the border's bottom-left corner. Setting this - property to a positive value results in a rounded corner. - - \row - \o \bold{\c border-style} \target border-style-prop - \o \l {Border Style} - \o The style of all the border's edges. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, - and QToolTip. - - If this property is not specified, it defaults to \c none. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 46 - - See also \l{#border-color-prop}{border-color}, - \l{Qt Style Sheets Reference#border-style-prop}{border-style}, - \l{#border-image-prop}{border-image}, and \l{The Box Model}. - - \row - \o \c border-top-style - \o \l{#Border Style}{Border Style} - \o The style of the border's top edge. - - \row - \o \c border-right-style - \o \l{#Border Style}{Border Style} - \o The style of the border's right edge/ - - \row - \o \c border-bottom-style - \o \l{#Border Style}{Border Style} - \o The style of the border's bottom edge. - - \row - \o \c border-left-style - \o \l{#Border Style}{Border Style} - \o The style of the border's left edge. - - \row - \o \bold{\c border-width} \target border-width-prop - \o \l{#Box Lengths}{Box Lengths} - \o The width of the border. Equivalent to setting \c - border-top-width, \c border-right-width, \c - border-bottom-width, and \c border-left-width. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, - and QToolTip. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 47 - - See also \l{#border-color-prop}{border-color}, - \l{#border-radius-prop}{border-radius}, - \l{Qt Style Sheets Reference#border-style-prop}{border-style}, - \l{#border-image-prop}{border-image}, and - \l{The Box Model}. - - \row - \o \c border-top-width - \o \l{#Length}{Length} - \o The width of the border's top edge. - - \row - \o \c border-right-width - \o \l{#Length}{Length} - \o The width of the border's right edge. - - \row - \o \c border-bottom-width - \o \l{#Length}{Length} - \o The width of the border's bottom edge. - - \row - \o \c border-left-width - \o \l{#Length}{Length} - \o The width of the border's left edge. - - \row - \o \bold{\c bottom} \target bottom-prop - \o \l{#Length}{Length} - \o If \l{#position-prop}{position} is \c relative (the - default), moves a \l{subcontrol} by a certain offset up; - specifying \tt{bottom: \e{y}} is then equivalent to - specifying \tt{\l{Qt Style Sheets Reference#top-prop}{top}: -\e{y}}. - - If \l{#position-prop}{position} is \c absolute, the \c - bottom property specifies the subcontrol's bottom edge - in relation to the parent's bottom edge (see also - \l{Qt Style Sheets Reference#subcontrol-origin-prop} - {subcontrol-origin}). - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 48 - - See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{#right-prop}{right}, and - \l{Qt Style Sheets Reference#top-prop}{top}. - - \row - \o \bold{\c button-layout} \target button-layout-prop - \o \l{#Number}{Number} - \o The layout of buttons in a QDialogButtonBox or - a QMessageBox. The possible values are 0 - (\l{QDialogButtonBox::}{WinLayout}), 1 - (\l{QDialogButtonBox::}{MacLayout}), 2 - (\l{QDialogButtonBox::}{KdeLayout}), and 3 - (\l{QDialogButtonBox::}{GnomeLayout}). - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_DialogButtonLayout} style hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 49 - - \row - \o \bold{\c color} \target color-prop - \o \l{#Brush}{Brush} \BR - \o The color used to render text. - - This property is supported by all widgets that respect - the \l QWidget::palette. - - If this property is not set, the default is whatever is - set for in the widget's palette for the - QWidget::foregroundRole (typically black). - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 50 - - See also \l{Qt Style Sheets Reference#background-prop}{background} and - \l{#selection-color-prop}{selection-color}. - - \row - \o \bold{\c dialogbuttonbox-buttons-have-icons} - \o \l{#Boolean}{Boolean} - \o Whether the buttons in a QDialogButtonBox show icons - - If this property is set to 1, the buttons of a QDialogButtonBox - show icons; if it is set to 0, the icons are not shown. - - See the \l{Qt Style Sheets Reference#list of icons}{List of Icons} - section for information on how to set icons. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 51 - - \note Styles defining this property must be applied before the - QDialogButtonBox is created; this means that you must apply the - style to the parent widget or to the application itself. - - \omit - \row - \o \bold{\c etch-disabled-text}* - \o \l{#Boolean}{Boolean} - \o Whether disabled text is drawn etched. - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_EtchDisabledText} style hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 52 - \endomit - - \row - \o \bold{\c font} \target font-prop - \o \l{#Font}{Font} - \o Shorthand notation for setting the text's font. Equivalent - to specifying \c font-family, \c font-size, \c font-style, - and/or \c font-weight. - - This property is supported by all widgets that respect - the \l QWidget::font. - - If this property is not set, the default is the - QWidget::font. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 53 - - \row - \o \c font-family - \o String - \o The font family. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 54 - - \row - \o \c font-size - \o \l{#Font Size}{Font Size} - \o The font size. In this version of Qt, only pt and px metrics are - supported. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 55 - - \row - \o \c font-style - \o \l {Font Style} - \o The font style. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 56 - - \row - \o \c font-weight - \o \l{#Font Weight}{Font Weight} - \o The weight of the font. - - \row - \o \bold{\c gridline-color}* \target gridline-color-prop - \o \l{#Color}{Color} \BR - \o The color of the grid line in a QTableView. - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_Table_GridLineColor} style hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 57 - - \row - \o \bold{\c height} \target height-prop - \o \l{#Length}{Length} - \o The height of a \l{subcontrol} (or in some case, a widget). - - If this property is not specified, it defaults to a value - that depends on the subcontrol/widget and on the current style. - - \warning Unless otherwise specified, this property has no effect - when set on widgets. If you want a widget with a fixed height, set - the \l{#min-width-prop}{min-height} and - \l{#max-width-prop}{max-height} to the same value. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 58 - - See also \l{#width-prop}{width}. - - \row - \o \bold{\c icon-size} \target icon-size-prop - \o \l{#Length}{Length} - \o The width and height of the icon in a widget. - - The icon size of the following widgets can be set using this - property. - \list - \i QCheckBox - \i QListView - \i QPushButton - \i QRadioButton - \i QTabBar - \i QToolBar - \i QToolBox - \i QTreeView - \endlist - - \row - \o \bold{\c image}* \target image-prop - \o \l{#Url}{Url}+ - \o The image that is drawn in the contents rectangle of a - \l{subcontrol}. - - The image property accepts a list of \l{#Url}{Url}s or - an \c{svg}. The actual image that is drawn is determined - using the same algorithm as QIcon (i.e) the image is never scaled - up but always scaled down if necessary. If a \c{svg} is specified, - the image is scaled to the size of the contents rectangle. - - Setting the image property on sub controls implicitly sets the - width and height of the sub-control (unless the image in a SVG). - - In Qt 4.3 and later, the alignment of the - image within the rectangle can be specified using - \l{image-position-prop}{image-position}. - - This property is for \l{subcontrol}s only--we don't support it for - other elements. - - \warning The QIcon SVG plugin is needed to render SVG images. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 59 - - \row - \o \bold{\c image-position} \target image-position-prop - \o \l{#Alignment}{alignment} - \o In Qt 4.3 and later, the alignment of the image image's position can be specified - using relative or absolute position. - - \row - \o \bold{\c left} \target left-prop - \o \l{#Length}{Length} - \o If \l{#position-prop}{position} is \c relative (the - default), moves a \l{subcontrol} by a certain offset to - the right. - - If \l{#position-prop}{position} is \c absolute, the \c - left property specifies the subcontrol's left edge in - relation to the parent's left edge (see also - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}). - - If this property is not specified, it defaults to \c 0. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 60 - - See also \l{#right-prop}{right}, \l{Qt Style Sheets Reference#top-prop}{top}, and - \l{#bottom-prop}{bottom}. - - \row - \o \bold{\c lineedit-password-character*} \target lineedit-password-character-prop - \o \l{#Number}{Number} - \o The QLineEdit password character as a Unicode number. - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_LineEdit_PasswordCharacter} style hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 61 - - \row - \o \bold{\c margin} \target margin-prop - \o \l {Box Lengths} - \o The widget's margins. Equivalent to specifying \c - margin-top, \c margin-right, \c margin-bottom, and \c - margin-left. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, - and QToolTip. - - If this property is not specified, it defaults to \c 0. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 62 - - See also \l{Qt Style Sheets Reference#padding-prop}{padding}, - \l{#spacing-prop}{spacing}, and \l{The Box Model}. - - \row - \o \c margin-top - \o \l{#Length}{Length} - \o The widget's top margin. - - \row - \o \c margin-right - \o \l{#Length}{Length} - \o The widget's right margin. - - \row - \o \c margin-bottom - \o \l{#Length}{Length} - \o The widget's bottom margin. - - \row - \o \c margin-left - \o \l{#Length}{Length} - \o The widget's left margin. - - \row - \o \bold{\c max-height} \target max-height-prop - \o \l{#Length}{Length} - \o The widget's or a subcontrol's maximum height. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, - QSplitter, QStatusBar, QTextEdit, and QToolTip. - - The value is relative to the contents rect in the \l{The - Box Model}{box model}. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 63 - - See also \l{#max-width-prop}{max-width}. - - \row - \o \bold{\c max-width} \target max-width-prop - \o \l{#Length}{Length} - \o The widget's or a subcontrol's maximum width. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, - QSplitter, QStatusBar, QTextEdit, and QToolTip. - - The value is relative to the contents rect in the \l{The - Box Model}{box model}. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 64 - - See also \l{#max-height-prop}{max-height}. - - - \row - \o \bold{\c messagebox-text-interaction-flags*} \target messagebox-text-interaction-flags-prop - \o \l{#Number}{Number} - \o The interaction behavior for text in a message box. - Possible values are based on Qt::TextInteractionFlags. - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_MessageBox_TextInteractionFlags} style - hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 65 - - \row - \o \bold{\c min-height} \target min-height-prop - \o \l{#Length}{Length} - \o The widget's or a subcontrol's minimum height. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, - QSplitter, QStatusBar, QTextEdit, and QToolTip. - - If this property is not specified, the minimum height is - derived based on the widget's contents and the style. - - The value is relative to the contents rect in the \l{The - Box Model}{box model}. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 66 - - See also \l{#min-width-prop}{min-width}. - - \row - \o \bold{\c min-width} \target min-width-prop - \o \l{#Length}{Length} - \o The widget's or a subcontrol's minimum width. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, - QSplitter, QStatusBar, QTextEdit, and QToolTip. - - If this property is not specified, the minimum width is - derived based on the widget's contents and the style. - - The value is relative to the contents rect in the \l{The - Box Model}{box model}. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 67 - - See also \l{#min-height-prop}{min-height}. - - \row - \o \bold{\c opacity*} \target opacity-prop - \o \l{#Number}{Number} - \o The opacity for a widget. Possible values are from 0 - (transparent) to 255 (opaque). For the moment, this is - only supported for \l{QToolTip}{tooltips}. - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_ToolTipLabel_Opacity} style hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 68 - - \row - \o \bold{\c padding} \target padding-prop - \o \l{#Box Lengths}{Box Lengths} - \o The widget's padding. Equivalent to specifying \c - padding-top, \c padding-right, \c padding-bottom, and \c - padding-left. - - This property is supported by QAbstractItemView - subclasses, QAbstractSpinBox subclasses, QCheckBox, - QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, - QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, - and QToolTip. - - If this property is not specified, it defaults to \c 0. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 69 - - See also \l{#margin-prop}{margin}, - \l{#spacing-prop}{spacing}, and \l{The Box Model}. - - \row - \o \c padding-top - \o \l{#Length}{Length} - \o The widget's top padding. - - \row - \o \c padding-right - \o \l{#Length}{Length} - \o The widget's right padding. - - \row - \o \c padding-bottom - \o \l{#Length}{Length} - \o The widget's bottom padding. - - \row - \o \c padding-left - \o \l{#Length}{Length} - \o The widget's left padding. - - \row - \o \bold{\c paint-alternating-row-colors-for-empty-area} - \target paint-alternating-row-colors-for-empty-area-prop - \o \c bool - \o Whether the QTreeView paints alternating row colors for the empty - area (i.e the area where there are no items) - - \row - \o \bold{\c position} \target position-prop - \o \c relative \BR - | \c absolute - \o Whether offsets specified using \l{Qt Style Sheets Reference#left-prop}{left}, - \l{#right-prop}{right}, \l{Qt Style Sheets Reference#top-prop}{top}, and - \l{#bottom-prop}{bottom} are relative or absolute - coordinates. - - If this property is not specified, it defaults to \c - relative. - - \row - \o \bold{\c right} \target right-prop - \o \l{#Length}{Length} - \o If \l{#position-prop}{position} is \c relative (the - default), moves a \l{subcontrol} by a certain offset to - the left; specifying \tt{right: \e{x}} is then equivalent - to specifying \tt{\l{Qt Style Sheets Reference#left-prop}{left}: -\e{x}}. - - If \l{#position-prop}{position} is \c absolute, the \c - right property specifies the subcontrol's right edge in - relation to the parent's right edge (see also - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}). - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 70 - - See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{Qt Style Sheets Reference#top-prop}{top}, and - \l{#bottom-prop}{bottom}. - - \row - \o \bold{\c selection-background-color*} \target selection-background-color-prop - \o \l{#Brush}{Brush} \BR - \o The background of selected text or items. - - This property is supported by all widgets that respect - the \l QWidget::palette and that show selection text. - - If this property is not set, the default value is - whatever is set for the palette's - \l{QPalette::}{Highlight} role. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 71 - - See also \l{#selection-color-prop}{selection-color} and - \l{Qt Style Sheets Reference#background-prop}{background}. - - \row - \o \bold{\c selection-color*} \target selection-color-prop - \o \l{#Brush}{Brush} \BR - \o The foreground of selected text or items. - - This property is supported by all widgets that respect - the \l QWidget::palette and that show selection text. - - If this property is not set, the default value is - whatever is set for the palette's - \l{QPalette::}{HighlightedText} role. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 72 - - See also - \l{#selection-background-color-prop}{selection-background-color} - and \l{#color-prop}{color}. - - \row - \o \bold{\c show-decoration-selected*} \target show-decoration-selected-prop - \o \l{#Boolean}{Boolean} - \o Controls whether selections in a QListView cover the - entire row or just the extent of the text. - - If this property is not specified, it defaults to the - value specified by the current style for the - \l{QStyle::}{SH_ItemView_ShowDecorationSelected} style - hint. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 73 - - \row - \o \bold{\c spacing*} \target spacing-prop - \o \l{#Length}{Length} - \o Internal spacing in the widget. - - This property is supported by QCheckBox, checkable - \l{QGroupBox}es, QMenuBar, and QRadioButton. - - If this property is not specified, the default value - depends on the widget and on the current style. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 74 - - See also \l{Qt Style Sheets Reference#padding-prop}{padding} and - \l{#margin-prop}{margin}. - - \row - \o \bold{\c subcontrol-origin*} \target subcontrol-origin-prop - \o \l{#Origin}{Origin} - \o The origin rectangle of the \l subcontrol within the - parent element. - - If this property is not specified, the default is \c - padding. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 75 - - See also - \l{Qt Style Sheets Reference#subcontrol-position-prop}{subcontrol-position}. - - \row - \o \bold{\c subcontrol-position*} \target subcontrol-position-prop - \o \l{#Alignment}{Alignment} - \o The alignment of the \l subcontrol within the origin - rectangle specified by \l{Qt Style Sheets Reference#subcontrol-origin-prop} - {subcontrol-origin}. - - If this property is not specified, it defaults to a value - that depends on the subcontrol. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 76 - - See also - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}. - - \row - \o \bold{\c text-align} \target text-align-prop - \o \l{#Alignment}{Alignment} - \o The alignment of text and icon within the contents of the widget. - - If this value is not specified, it defaults to the value - that depends on the native style. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 77 - - This property is currently supported only by QPushButton - and QProgressBar. - - \row - \o \bold{\c text-decoration} - \o \c none \BR - \c underline \BR - \c overline \BR - \c line-through - \o Additional text effects - - \row - \o \bold{\c top} \target top-prop - \o \l{#Length}{Length} - \o If \l{#position-prop}{position} is \c relative (the - default), moves a \l{subcontrol} by a certain offset - down. - - If \l{#position-prop}{position} is \c absolute, the \c top - property specifies the subcontrol's top edge in relation - to the parent's top edge (see also - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}). - - If this property is not specified, it defaults to \c 0. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 78 - - See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{#right-prop}{right}, and - \l{#bottom-prop}{bottom}. - - \row - \o \bold{\c width} \target width-prop - \o \l{#Length}{Length} - \o The width of a \l{subcontrol} (or a widget in some cases). - - If this property is not specified, it defaults to a value - that depends on the subcontrol/widget and on the current style. - - \warning Unless otherwise specified, this property has no effect - when set on widgets. If you want a widget with a fixed width, set - the \l{#min-width-prop}{min-width} and - \l{#max-width-prop}{max-width} to the same value. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 79 - - See also \l{#height-prop}{height}. - - \endtable - - \target list of icons - \section1 List of Icons - - Icons used in Qt can be customized using the following properties. Each of - the properties listed in this section have the type \l{#Icon}{Icon}. - - Note that for icons to appear in buttons in a QDialogButtonBox, you need to - set the dialogbuttonbox-buttons-have-icons property to true. Also, to - customize the size of the icons, use the icon-size property. - - \table 100% - \header - \o Name - \o QStyle::StandardPixmap - - \row - \o backward-icon - \o QStyle::SP_ArrowBack - - \row - \o cd-icon - \o QStyle::SP_DriveCDIcon - - \row - \o computer-icon - \o QStyle::SP_ComputerIcon - - \row - \o desktop-icon - \o QStyle::SP_DesktopIcon - - \row - \o dialog-apply-icon - \o QStyle::SP_DialogApplyButton - - \row - \o dialog-cancel-icon - \o QStyle::SP_DialogCancelButton - - \row - \o dialog-close-icon - \o QStyle::SP_DialogCloseButton - - \row - \o dialog-discard-icon - \o QStyle::SP_DialogDiscardButton - - \row - \o dialog-help-icon - \o QStyle::SP_DialogHelpButton - - \row - \o dialog-no-icon - \o QStyle::SP_DialogNoButton - - \row - \o dialog-ok-icon - \o QStyle::SP_DialogOkButton - - \row - \o dialog-open-icon - \o QStyle::SP_DialogOpenButton - - \row - \o dialog-reset-icon - \o QStyle::SP_DialogResetButton - - \row - \o dialog-save-icon - \o QStyle::SP_DialogSaveButton - - \row - \o dialog-yes-icon - \o QStyle::SP_DialogYesButton - - \row - \o directory-closed-icon - \o QStyle::SP_DirClosedIcon - - \row - \o directory-icon - \o QStyle::SP_DirIcon - - \row - \o directory-link-icon - \o QStyle::SP_DirLinkIcon - - \row - \o directory-open-icon - \o QStyle::SP_DirOpenIcon - - \row - \o dockwidget-close-icon - \o QStyle::SP_DockWidgetCloseButton - - \row - \o downarrow-icon - \o QStyle::SP_ArrowDown - - \row - \o dvd-icon - \o QStyle::SP_DriveDVDIcon - - \row - \o file-icon - \o QStyle::SP_FileIcon - - \row - \o file-link-icon - \o QStyle::SP_FileLinkIcon - - \omit - \row - \o filedialog-backward-icon - \o QStyle::SP_FileDialogBack - \endomit - - \row - \o filedialog-contentsview-icon - \o QStyle::SP_FileDialogContentsView - - \row - \o filedialog-detailedview-icon - \o QStyle::SP_FileDialogDetailedView - - \row - \o filedialog-end-icon - \o QStyle::SP_FileDialogEnd - - \row - \o filedialog-infoview-icon - \o QStyle::SP_FileDialogInfoView - - \row - \o filedialog-listview-icon - \o QStyle::SP_FileDialogListView - - \row - \o filedialog-new-directory-icon - \o QStyle::SP_FileDialogNewFolder - - \row - \o filedialog-parent-directory-icon - \o QStyle::SP_FileDialogToParent - - \row - \o filedialog-start-icon - \o QStyle::SP_FileDialogStart - - \row - \o floppy-icon - \o QStyle::SP_DriveFDIcon - - \row - \o forward-icon - \o QStyle::SP_ArrowForward - - \row - \o harddisk-icon - \o QStyle::SP_DriveHDIcon - - \row - \o home-icon - \o QStyle::SP_DirHomeIcon - - \row - \o leftarrow-icon - \o QStyle::SP_ArrowLeft - - \row - \o messagebox-critical-icon - \o QStyle::SP_MessageBoxCritical - - \row - \o messagebox-information-icon - \o QStyle::SP_MessageBoxInformation - - \row - \o messagebox-question-icon - \o QStyle::SP_MessageBoxQuestion - - \row - \o messagebox-warning-icon - \o QStyle::SP_MessageBoxWarning - - \row - \o network-icon - \o QStyle::SP_DriveNetIcon - - \row - \o rightarrow-icon - \o QStyle::SP_ArrowRight - - \row - \o titlebar-contexthelp-icon - \o QStyle::SP_TitleBarContextHelpButton - - \row - \o titlebar-maximize-icon - \o QStyle::SP_TitleBarMaxButton - - \row - \o titlebar-menu-icon - \o QStyle::SP_TitleBarMenuButton - - \row - \o titlebar-minimize-icon - \o QStyle::SP_TitleBarMinButton - - \row - \o titlebar-normal-icon - \o QStyle::SP_TitleBarNormalButton - - \row - \o titlebar-shade-icon - \o QStyle::SP_TitleBarShadeButton - - \row - \o titlebar-unshade-icon - \o QStyle::SP_TitleBarUnshadeButton - - \row - \o trash-icon - \o QStyle::SP_TrashIcon - - \row - \o uparrow-icon - \o QStyle::SP_ArrowUp - - \endtable - - \section1 List of Property Types - - The following table summarizes the syntax and meaning of the - different property types. - - \table 100% - \header - \o Type - \o Syntax - \o Description - - \row - \o \bold Alignment \target Alignment - \o \{ \c top \BR - | \c bottom \BR - | \c left \BR - | \c right \BR - | \c center \}* - \o Horizontal and/or vertical alignment. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 80 - - \row - \o \bold Attachment \target Attachment - \o \{ \c scroll \BR - | \c fixed \}* - \o Scroll or fixed attachment. - - \row - \o \bold Background \target Background - \o \{ \l{#Brush}{Brush} \BR - | \l{#Url}{Url} \BR - | \l{#Repeat}{Repeat} \BR - | \l{#Alignment}{Alignment} \}* - \o A sequence of \l{#Brush}{Brush}, \l{#Url}{Url}, - \l{#Repeat}{Repeat}, and \l{#Alignment}{Alignment}. - - \row - \o \bold Boolean \target Boolean - \o 0 | 1 - \o True (\c 1) or false (\c 0). - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 81 - - \row - \o \bold Border \target Border - \o \{ \l{#Border Style}{Border Style} \BR - | \l{#Length}{Length} \BR - | \l{#Brush}{Brush} \}* - \o Shorthand border property. - - \row - \o \bold{Border Image} \target Border Image - \o \c none \BR - | \l{Url} \l{Number}\{4\} \BR (\c stretch | \c repeat){0,2} - \o A border image is an image that is composed of nine parts - (top left, top center, top right, center left, center, - center right, bottom left, bottom center, and bottom - right). When a border of a certain size is required, the - corner parts are used as is, and the top, right, bottom, - and left parts are stretched or repeated to produce a - border with the desired size. - - See the - \l{http://www.w3.org/TR/css3-background/#the-border-image} - {CSS3 Draft Specification} for details. - - \row - \o \bold{Border Style} \target Border Style - \o \c dashed \BR - | \c dot-dash \BR - | \c dot-dot-dash \BR - | \c dotted \BR - | \c double \BR - | \c groove \BR - | \c inset \BR - | \c outset \BR - | \c ridge \BR - | \c solid \BR - | \c none - \o Specifies the pattern used to draw a border. - See the \l{http://www.w3.org/TR/css3-background/#border-style} - {CSS3 Draft Specification} for details. - - \row - \o \bold{Box Colors} \target Box Colors - \o \l{#Brush}{Brush}\{1,4\} - \o One to four occurrences of \l{#Brush}{Brush}, specifying the top, - right, bottom, and left edges of a box, respectively. If - the left color is not specified, it is taken to be the - same as the right color. If the bottom color is not - specified, it is taken to be the same as the top color. If - the right color is not specified, it is taken to be the - same as the top color. - - Example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 82 - - \row - \o \bold{Box Lengths} \target Box Lengths - \o \l{#Length}{Length}\{1,4\} - \o One to four occurrences of \l{#Length}{Length}, specifying the - top, right, bottom, and left edges of a box, - respectively. If the left length is not specified, it is - taken to be the same as the right length. If the bottom - length is not specified, is it taken to be the same as the - top length. If the right length is not specified, it is - taken to be the same as the top length. - - Examples: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 83 - - \row - \o \bold{Brush} \target Brush - \o \l{#Color}{Color} \BR - | \l{Gradient} \BR - | \l{PaletteRole} - \o Specifies a Color or a Gradient or an entry in the Palette. - - \row - \o \bold{Color} \target Color - \o \tt{rgb(\e{r}, \e{g}, \e{b})} \BR - | \tt{rgba(\e{r}, \e{g}, \e{b}, \e{a})} \BR - | \tt{hsv(\e{h}, \e{s}, \e{v})} \BR - | \tt{hsva(\e{h}, \e{s}, \e{v}, \e{a})} \BR - | \tt{#\e{rrggbb}} \BR - | \l{QColor::setNamedColor()}{Color Name} \BR - \o Specifies a color as RGB (red, green, blue) or RGBA - (red, green, blue, alpha) or HSV (hue, saturation, value) or HSVA - (hue, saturation, value, alpha) or a named color. The \c rgb() or \c rgba() - syntax can be used with integer values between 0 and 255, or with - percentages. The value of s, v, and a in \c hsv() or \c hsva() must all - be in the range 0-255; the value of h must be in the range 0-359. - - Examples: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 84 - - \note The RGB colors allowed are the same as those allowed with - CSS 2.1, as listed - \l{http://www.w3.org/TR/CSS21/syndata.html#color-units}{here}. - - \row - \o \bold{Font} \target Font - \o (\l{#Font Style}{Font Style} | \l{#Font Weight}{Font Weight}){0,2} \l{#Font Size}{Font Size} String - \o Shorthand font property. - - \row - \o \bold{Font Size} \target Font Size - \o \l{Length} - \o The size of a font. - - \row - \o \bold{Font Style} \target Font Style - \o \c normal \BR - | \c italic \BR - | \c oblique - \o The style of a font. - - \row - \o \bold{Font Weight} \target Font Weight - \o \c normal \BR - | \c bold \BR - | \c 100 \BR - | \c 200 \BR - ... \BR - | \c 900 - \o The weight of a font. - - \row - \o \bold{Gradient} \target Gradient - \o \c qlineargradient \BR - | \c qradialgradient \BR - | \c qconicalgradient - \o Specifies gradient fills. There are three types of gradient fills: - - \list - \o \e{Linear} gradients interpolate colors between start and - end points. - \o \e{Radial} gradients interpolate colors between a focal - point and end points on a circle surrounding it. - \o \e{Conical} gradients interpolate colors around a center - point. - \endlist - - Gradients are specified in Object Bounding Mode. Imagine the box - in which the gradient is rendered, to have its top left corner at (0, 0) - and its bottom right corner at (1, 1). Gradient parameters are - then specified as percentages from 0 to 1. These values are - extrapolated to actual box coordinates at runtime. It is possible - specify values that lie outside the bounding box (-0.6 or 1.8, for - instance). - - \warning The stops have to appear sorted in ascending order. - - Examples: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 85 - - \row - \o \bold{Icon} \target Icon - \o (\l{#Url}{Url} (\c disabled | \c active | \c normal | \c selected)? - (\c on | \c off)? )* - \o A list of url, QIcon::Mode and QIcon::State. - - Example: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 86 - - \row - \o \bold{Length} \target Length - \o \l{#Number}{Number} (\c px | \c pt | \c em | \c ex)? - \o A number followed by a measurement unit. The CSS standard recommends - that user agents must - \l{http://www.w3.org/TR/CSS21/syndata.html#illegalvalues}{ignore} - a declaration with an illegal value. In Qt, it is mandatory to - specify measurement units. For compatibility with earlier versions - of Qt, numbers without measurement units are treated as pixels - in most contexts. The supported units are: - - \list - \o \c px: pixels - \o \c pt: the size of one point (i.e., 1/72 of an inch) - \o \c em: the em width of the font (i.e., the width of 'M') - \o \c ex: the ex width of the font (i.e., the height of 'x') - \endlist - - \row - \o \bold{Number} \target Number - \o A decimal integer or a real number - \o Examples: \c 0, \c 18, \c +127, \c -255, \c 12.34, \c -.5, - \c 0009. - - \row - \o \bold{Origin} \target Origin - \o \c margin \BR - | \c border \BR - | \c padding \BR - | \c content - \o Indicates which of four rectangles to use. - - \list - \o \c margin: The margin rectangle. The margin falls outside the border. - \o \c border: The border rectangle. This is where any border is drawn. - \o \c padding: The padding rectangle. Unlike the margins, - padding is located inside the border. - \o \c content: The content rectangle. This specifies where - the actual contents go, excluding any - padding, border, or margin. - \endlist - - See also \l{The Box Model}. - - \row - \o \bold{PaletteRole} \target PaletteRole - \o \c alternate-base \BR - | \c base \BR - | \c bright-text \BR - | \c button \BR - | \c button-text \BR - | \c dark \BR - | \c highlight \BR - | \c highlighted-text \BR - | \c light \BR - | \c link \BR - | \c link-visited \BR - | \c mid \BR - | \c midlight \BR - | \c shadow \BR - | \c text \BR - | \c window \BR - | \c window-text \BR - \o These values correspond the \l{QPalette::ColorRole}{Color roles} - in the widget's QPalette. - - For example, - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 87 - - \row - \o \bold{Radius} \target Radius - \o \l{#Length}{Length}\{1, 2\} - \o One or two occurrences of \l{#Length}{Length}. If only one length is - specified, it is used as the radius of the quarter circle - defining the corner. If two lengths are specified, the - first length is the horizontal radius of a quarter - ellipse, whereas the second length is the vertical radius. - - \row - \o \bold{Repeat} \target Repeat - \o \c repeat-x \BR - | \c repeat-y \BR - | \c repeat \BR - | \c no-repeat - \o A value indicating the nature of repetition. - - \list - \o \c repeat-x: Repeat horizontally. - \o \c repeat-y: Repeat vertically. - \o \c repeat: Repeat horizontally and vertically. - \o \c no-repeat: Don't repeat. - \endlist - - \row - \o \bold{Url} \target Url - \o \tt{url(\e{filename})} - \o \tt{\e{filename}} is the name of a file on the local disk - or stored using \l{the Qt Resource System}. Setting an - image implicitly sets the width and height of the element. - - \endtable - - \section1 List of Pseudo-States - - The following pseudo-states are supported: - - \table 100% - \header - \o Pseudo-State - \o Description - - \row \o \c :active \target active - \o This state is set when the widget resides in an active window. - - \row - \o \c :adjoins-item \target adjoins-item-ps - \o This state is set when the \l{#branch-sub}{::branch} of a QTreeView - is adjacent to an item. - - \row - \o \c :alternate \target alternate-ps - \o This state is set for every alternate row whe painting the row of - a QAbstractItemView when QAbstractItemView::alternatingRowColors() - is set to true. - - \row - \o \c :bottom \target bottom-ps - \o The item is positioned at the bottom. For example, a QTabBar - that has its tabs positioned at the bottom. - - \row - \o \c :checked \target checked-ps - \o The item is checked. For example, the - \l{QAbstractButton::checked}{checked} state of QAbstractButton. - - \row - \o \c :closable \target closable-ps - \o The items can be closed. For example, the QDockWidget has the - QDockWidget::DockWidgetClosable feature turned on. - - \row - \o \c :closed \target closed-ps - \o The item is in the closed state. For example, an non-expanded - item in a QTreeView - - \row - \o \c :default \target default-ps - \o The item is the default. For example, a - \l{QPushButton::default}{default} QPushButton or a default action - in a QMenu. - - \row - \o \c :disabled \target disabled-ps - \o The item is \l{QWidget::enabled}{disabled}. - - \row - \o \c :editable \target editable-ps - \o The QComboBox is editable. - - \row - \o \c :edit-focus \target edit-focus-ps - \o The item has edit focus (See QStyle::State_HasEditFocus). This state - is available only for Qt Extended applications. - - \row - \o \c :enabled \target enabled-ps - \o The item is \l{QWidget::enabled}{enabled}. - - \row - \o \c :exclusive \target exclusive-ps - \o The item is part of an exclusive item group. For example, a menu - item in a exclusive QActionGroup. - - \row - \o \c :first \target first-ps - \o The item is the first (in a list). For example, the first - tab in a QTabBar. - - \row - \o \c :flat \target flat-ps - \o The item is flat. For example, a - \l{QPushButton::flat}{flat} QPushButton. - - \row - \o \c :floatable \target floatable-ps - \o The items can be floated. For example, the QDockWidget has the - QDockWidget::DockWidgetFloatable feature turned on. - - \row - \o \c :focus \target focus-ps - \o The item has \l{QWidget::hasFocus()}{input focus}. - - \row - \o \c :has-children \target has-children-ps - \o The item has children. For example, an item in a - QTreeView that has child items. - - \row - \o \c :has-siblings \target has-siblings-ps - \o The item has siblings. For example, an item in a - QTreeView that siblings. - - \row - \o \c :horizontal \target horizontal-ps - \o The item has horizontal orientation - - \row - \o \c :hover \target hover-ps - \o The mouse is hovering over the item. - - \row - \o \c :indeterminate \target indeterminate-ps - \o The item has indeterminate state. For example, a QCheckBox - or QRadioButton is \l{Qt::PartiallyChecked}{partially checked}. - - \row - \o \c :last \target last-ps - \o The item is the last (in a list). For example, the last - tab in a QTabBar. - - \row - \o \c :left \target left-ps - \o The item is positioned at the left. For example, a QTabBar - that has its tabs positioned at the left. - - \row - \o \c :maximized \target maximized-ps - \o The item is maximized. For example, a maximized QMdiSubWindow. - - \row - \o \c :middle \target middle-ps - \o The item is in the middle (in a list). For example, a tab - that is not in the beginning or the end in a QTabBar. - - \row - \o \c :minimized \target minimized-ps - \o The item is minimized. For example, a minimized QMdiSubWindow. - - \row - \o \c :movable \target movable-ps - \o The item can be moved around. For example, the QDockWidget has the - QDockWidget::DockWidgetMovable feature turned on. - - \row - \o \c :no-frame \target no-frame-ps - \o The item has no frame. For example, a frameless QSpinBox - or QLineEdit. - - \row - \o \c :non-exclusive \target non-exclusive-ps - \o The item is part of a non-exclusive item group. For example, a menu - item in a non-exclusive QActionGroup. - - \row - \o \c :off \target off-ps - \o For items that can be toggled, this applies to items - in the "off" state. - - \row - \o \c :on \target on-ps - \o For items that can be toggled, this applies to widgets - in the "on" state. - - \row - \o \c :only-one \target only-one-ps - \o The item is the only one (in a list). For example, a lone tab - in a QTabBar. - - \row - \o \c :open \target open-ps - \o The item is in the open state. For example, an expanded - item in a QTreeView, or a QComboBox or QPushButton with - an open menu. - - \row - \o \c :next-selected \target next-selected-ps - \o The next item (in a list) is selected. For example, the - selected tab of a QTabBar is next to this item. - - \row - \o \c :pressed \target pressed-ps - \o The item is being pressed using the mouse. - - \row - \o \c :previous-selected \target previous-selected-ps - \o The previous item (in a list) is selected. For example, a - tab in a QTabBar that is next to the selected tab. - - \row - \o \c :read-only \target read-only-ps - \o The item is marked read only or non-editable. For example, - a read only QLineEdit or a non-editable QComboBox. - - \row - \o \c :right \target right-ps - \o The item is positioned at the right. For example, a QTabBar - that has its tabs positioned at the right. - - \row - \o \c :selected \target selected-ps - \o The item is selected. For example, the selected tab in - a QTabBar or the selected item in a QMenu. - - \row - \o \c :top \target top-ps - \o The item is positioned at the top. For example, a QTabBar - that has its tabs positioned at the top. - - \row - \o \c :unchecked \target unchecked-ps - \o The item is - \l{QAbstractButton::checked}{unchecked}. - - \row - \o \c :vertical \target vertical-ps - \o The item has vertical orientation. - - \row - \o \c :window \target window-ps - \o The widget is a window (i.e top level widget) - - \endtable - - \target subcontrols - \section1 List of Sub-Controls - - The following subcontrols are available: - - \table 100% - \header - \o Sub-Control - \o Description - - \row - \o \c ::add-line \target add-line-sub - \o The button to add a line of a QScrollBar. - - \row - \o \c ::add-page \target add-page-sub - \o The region between the handle (slider) and the \l{#add-line-sub}{add-line} - of a QScrollBar. - - \row - \o \c ::branch \target branch-sub - \o The branch indicator of a QTreeView. - - \row - \o \c ::chunk \target chunk-sub - \o The progress chunk of a QProgressBar. - - \row - \o \c ::close-button \target close-button-sub - \o The close button of a QDockWidget or tabs of QTabBar - - \row - \o \c ::corner \target corner-sub - \o The corner between two scrollbars in a QAbstractScrollArea - - \row - \o \c ::down-arrow \target down-arrow-sub - \o The down arrow of a QComboBox, QHeaderView (sort indicator), - QScrollBar or QSpinBox. - - \row - \o \c ::down-button \target down-button-sub - \o The down button of a QScrollBar or a QSpinBox. - - \row - \o \c ::drop-down \target drop-down-sub - \o The drop-down button of a QComboBox. - - \row - \o \c ::float-button \target float-button-sub - \o The float button of a QDockWidget - - \row - \o \c ::groove \target groove-sub - \o The groove of a QSlider. - - \row - \o \c ::indicator \target indicator-sub - \o The indicator of a QAbstractItemView, a QCheckBox, a QRadioButton, - a checkable QMenu item or a checkable QGroupBox. - - \row - \o \c ::handle \target handle-sub - \o The handle (slider) of a QScrollBar, a QSplitter, or a QSlider. - - \row - \o \c ::icon \target icon-sub - \o The icon of a QAbstractItemView or a QMenu. - - \row - \o \c ::item \target item-sub - \o An item of a QAbstractItemView, a QMenuBar, a QMenu, or - a QStatusBar. - - \row - \o \c ::left-arrow \target left-arrow-sub - \o The left arrow of a QScrollBar. - - \row - \o \c ::left-corner \target left-corner-sub - \o The left corner of a QTabWidget. For example, this control can be - used to control position the left corner widget in a QTabWidget. - - \row - \o \c ::menu-arrow \target menu-arrow-sub - \o The arrow of a QToolButton with a menu. - - \row - \o \c ::menu-button \target menu-button-sub - \o The menu button of a QToolButton. - - \row - \o \c ::menu-indicator \target menu-indicator-sub - \o The menu indicator of a QPushButton. - - \row - \o \c ::right-arrow \target right-arrow-sub - \o The right arrow of a QMenu or a QScrollBar. - - \row - \o \c ::pane \target pane-sub - \o The pane (frame) of a QTabWidget. - - \row - \o \c ::right-corner \target right-corner-sub - \o The right corner of a QTabWidget. For example, this control can be - used to control the position the right corner widget in a QTabWidget. - - \row - \o \c ::scroller \target scroller-sub - \o The scroller of a QMenu or QTabBar. - - \row - \o \c ::section \target section-sub - \o The section of a QHeaderView. - - \row - \o \c ::separator \target separator-sub - \o The separator of a QMenu or in a QMainWindow. - - \row - \o \c ::sub-line \target sub-line-sub - \o The button to subtract a line of a QScrollBar. - - \row - \o \c ::sub-page \target sub-page-sub - \o The region between the handle (slider) and the \l{#sub-line-sub}{sub-line} - of a QScrollBar. - - \row - \o \c ::tab \target tab-sub - \o The tab of a QTabBar or QToolBox. - - \row - \o \c ::tab-bar \target tab-bar-sub - \o The tab bar of a QTabWidget. This subcontrol exists only to - control the position of the QTabBar inside the QTabWidget. To - style the tabs using the \l{#tab-sub}{::tab} subcontrol. - - \row - \o \c ::tear \target tear-sub - \o The tear indicator of a QTabBar. - - \row - \o \c ::tearoff \target tearoff-sub - \o The tear-off indicator of a QMenu. - - \row - \o \c ::text \target text-ps - \o The text of a QAbstractItemView. - - \row - \o \c ::title \target title-sub - \o The title of a QGroupBox or a QDockWidget. - - \row - \o \c ::up-arrow \target up-arrow-sub - \o The up arrow of a QHeaderView (sort indicator), QScrollBar - or a QSpinBox. - - \row - \o \c ::up-button \target up-button-sub - \o The up button of a QSpinBox. - - \endtable - - See \l{Customizing the QPushButton's Menu Indicator Sub-Control} - for an example of how to customize a subcontrol. - */ - -/*! - \page stylesheet-examples.html - \contentspage {Qt Style Sheet}{Contents} - \previouspage Qt Style Sheets Reference - \title Qt Style Sheets Examples - - We will now see a few examples to get started with using Qt Style Sheets. - - \tableofcontents - \section1 Style Sheet Usage - - \section2 Customizing the Foreground and Background Colors - - Let's start by setting yellow as the background color of all - \l{QLineEdit}s in an application. This could be achieved like - this: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 88 - - If we want the property to apply only to the \l{QLineEdit}s that are - children (or grandchildren or grand-grandchildren) of a specific dialog, - we would rather do this: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 89 - - If we want the property to apply only to one specific QLineEdit, - we can give it a name using QObject::setObjectName() and use an - ID Selector to refer to it: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 90 - - Alternatively, we can set the - \l{Qt Style Sheets Reference#background-prop}{background-color} property directly on the - QLineEdit, omitting the selector: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 91 - - To ensure a good contrast, we should also specify a suitable - color for the text: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 92 - - It might be a good idea to change the colors used for selected - text as well: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 93 - - - \section2 Customizing Using Dynamic Properties - - There are many situations where we need to present a form that - has mandatory fields. To indicate to the user that the field is - mandatory, one effective (albeit esthetically dubious) solution - is to use yellow as the background color for those fields. It - turns out this is very easy to implement using Qt Style Sheets. - First, we would use the following application-wide style sheet: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 94 - - This means that every widget whose \c mandatoryField Qt property - is set to true would have a yellow background. - - Then, for each mandatory field widget, we would simply create a - \c mandatoryField property on the fly and set it to true. For - example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 95 - - \section2 Customizing a QPushButton Using the Box Model - - This time, we will show how to create a red QPushButton. This - QPushButton would presumably be connected to a very destructive - piece of code. - - First, we are tempted to use this style sheet: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 96 - - However, the result is a boring, flat button with no borders: - - \image stylesheet-redbutton1.png A flat red button - - What happened is this: - - \list - \o We have made a request that cannot be satisfied using the - native styles alone (e.g., the Windows XP theme engine doesn't - let us specify the background color of a button). - \o Therefore, the button is rendered using style sheets. - \o We haven't specified any values for - \l{Qt Style Sheets Reference#border-width-prop}{border-width} and - \l{Qt Style Sheets Reference#border-style-prop}{border-style}, so by default we obtain - a 0-pixel wide border of style \c none. - \endlist - - Let's improve the situation by specifying a border: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 97 - - \image stylesheet-redbutton2.png A red button with a beige border - - Things look already a lot better. But the button looks a bit - cramped. Let's specify some spacing between the border and the - text using the \l{Qt Style Sheets Reference#padding-prop}{padding}. Additionally, we will - enforce a minimum width, round the corners, and specify a larger - font to make the button look nicer: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 98 - - \image stylesheet-redbutton3.png A red button with a round beige border and big, bold text - - The only issue remaining is that the button doesn't react when we - press it. We can fix this by specifying a slightly different - background color and use a different border style. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 99 - - \section2 Customizing the QPushButton's Menu Indicator Sub-Control - - Subcontrols give access to the sub-elements of a widget. For - example, a QPushButton associated with a menu (using - QPushButton::setMenu()) has a menu indicator. Let's customize - the menu indicator for the red push button: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 100 - - By default, the menu indicator is located at the bottom-right - corner of the padding rectangle. We can change this by specifying - \l{Qt Style Sheets Reference#subcontrol-position-prop}{subcontrol-position} and - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} to anchor the - indicator differently. We can also use \l{Qt Style Sheets Reference#top-prop}{top} and - \l{Qt Style Sheets Reference#left-prop}{left} to move the indicator by a few pixels. For - example: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 101 - - This positions the \c myindicator.png to the center right of the - QPushButton's \l{Qt Style Sheets Reference#padding-prop}{padding} rectangle (see - \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} for more - information). - - \section2 Complex Selector Example - - Since red seems to be our favorite color, let's make the text in - QLineEdit red by setting the following application-wide - stylesheet: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 102 - - However, we would like to give a visual indication that a - QLineEdit is read-only by making it appear gray: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 103 - - At some point, our design team comes with the requirement that - all \l{QLineEdit}s in the registration form (with the - \l{QObject::objectName}{object name} \c registrationDialog) to be - brown: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 104 - - A few UI design meetings later, we decide that all our - \l{QDialog}s should have brown colored \l{QLineEdit}s: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 105 - - Quiz: What happens if we have a read-only QLineEdit in a QDialog? - [Hint: The \l{The Style Sheet Syntax#Conflict Resolution}{Conflict Resolution} section above explains - what happens in cases like this.] - - \section1 Customizing specific widgets - - This section provides examples to customize specific widgets using Style Sheets. - - \section2 Customizing QAbstractScrollArea - - The background of any QAbstractScrollArea (Item views, QTextEdit - and QTextBrowser) can be set using the background properties. For example, - to set a background-image that scrolls with the scroll bar: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 106 - - If the background-image is to be fixed with the viewport: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 107 - - \section2 Customizing QCheckBox - - Styling of a QCheckBox is almost indentical to styling a QRadioButton. The - main difference is that a tristate QCheckBox has an indeterminate state. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 108 - - \section2 Customizing QComboBox - - We will look at an example where the drop down button of a QComboBox - appears "merged" with the combo box frame. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 109 - - The pop-up of the QComboBox is a QAbstractItemView and is styled using - the descendant selector: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 110 - - \section2 Customizing QDockWidget - - The title bar and the buttons of a QDockWidget can be customized as - follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 111 - - If one desires to move the dock widget buttons to the left, the following - style sheet can be used: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 112 - - \note To customize the separator (resize handle) of a QDockWidget, - use QMainWindow::separator. - - \section2 Customizing QFrame - - A QFrame is styled using the \l{The Box Model}. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 113 - - \section2 Customizing QGroupBox - - Let us look at an example that moves the QGroupBox's title to - the center. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 114 - - For a checkable QGroupBox, use the \{#indicator-sub}{::indicator} subcontrol - and style it exactly like a QCheckBox (i.e) - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 115 - - \section2 Customizing QHeaderView - - QHeaderView is customized as follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 116 - - \section2 Customizing QLineEdit - - The frame of a QLineEdit is styled using the \l{The Box Model}. To - create a line edit with rounded corners, we can set: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 117 - - The password character of line edits that have QLineEdit::Password - echo mode can be set using: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 118 - - The background of a read only QLineEdit can be modified as below: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 119 - - \section2 Customizing QListView - - The background color of alternating rows can be customized using the following - style sheet: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 120 - - To provide a special background when you hover over items, we can use the - \l{item-sub}{::item} subcontrol. For example, - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 121 - - \section2 Customizing QMainWindow - - The separator of a QMainWindow can be styled as follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 122 - - \section2 Customizing QMenu - - Individual items of a QMenu are styled using the 'item' subcontrol as - follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 123 - - For a more advanced customization, use a style sheet as follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 124 - - \section2 Customizing QMenuBar - - QMenuBar is styled as follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 125 - - \section2 Customizing QProgressBar - - The QProgressBar's \l{stylesheet-reference.html#border-prop}{border}, - \l{stylesheet-reference.html#chunk-sub}{chunk}, and - \l{stylesheet-reference.html#text-align-prop}{text-align} can be customized using - style sheets. However, if one property or sub-control is customized, - all the other properties or sub-controls must be customized as well. - - \image progressBar-stylesheet.png - - For example, we change the \l{stylesheet-reference.html#border-prop} - {border} to grey and the \l{stylesheet-reference.html#chunk-sub}{chunk} - to cerulean. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 126 - - This leaves the \l{stylesheet-reference.html#text-align-prop} - {text-align}, which we customize by positioning the text in the center of - the progress bar. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 127 - - A \l{stylesheet-reference.html#margin-prop}{margin} can be included to - obtain more visible chunks. - - \image progressBar2-stylesheet.png - - In the screenshot above, we use a - \l{stylesheet-reference.html#margin-prop}{margin} of 0.5 pixels. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 128 - - \section2 Customizing QPushButton - - A QPushButton is styled as follows: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 129 - - For a QPushButton with a menu, use the - \l{Qt Style Sheets Reference#menu-indicator-sub}{::menu-indicator} - subcontrol. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 130 - - Checkable QPushButton have the \l{Qt Style Sheets Reference#checked-ps} - {:checked} pseudo state set. - - \section2 Customizing QRadioButton - - The indicator of a QRadioButton can be changed using: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 131 - - \section2 Customizing QScrollBar - - The QScrollBar can be styled using its subcontrols like - \l{stylesheet-reference.html#handle-sub}{handle}, - \l{stylesheet-reference.html#add-line-sub}{add-line}, - \l{stylesheet-reference.html#sub-line-sub}{sub-line}, and so on. Note that - if one property or sub-control is customized, all the other properties or - sub-controls must be customized as well. - - \image stylesheet-scrollbar1.png - - The scroll bar above has been styled in aquamarine with a solid grey - border. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 132 - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 133 - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 134 - - The \l{stylesheet-reference.html#left-arrow-sub}{left-arrow} and - \l{stylesheet-reference.html#right-arrow-sub}{right-arrow} have a solid grey - border with a white background. As an alternative, you could also embed the - image of an arrow. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 135 - - If you want the scroll buttons of the scroll bar to be placed together - (instead of the edges) like on Mac OS X, you can use the following - stylesheet: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 136 - - The scroll bar using the above stylesheet looks like this: - \image stylesheet-scrollbar2.png - - - To customize a vertical scroll bar use a style sheet similar to the following: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 137 - - \section2 Customizing QSizeGrip - - QSizeGrip is usually styled by just setting an image. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 138 - - \section2 Customizing QSlider - - You can style horizontal slider as below: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 139 - - If you want to change the color of the slider parts before and after the handle, you can use the add-page - and sub-page subcontrols. For example, for a vertical slider: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 140 - - \section2 Customizing QSpinBox - - QSpinBox can be completely customized as below (the style sheet has commentary inline): - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 141 - - - \section2 Customizing QSplitter - - A QSplitter derives from a QFrame and hence can be styled like a QFrame. - The grip or the handle is customized using the - \l{Qt Style Sheets Reference#handle-sub}{::handle} subcontrol. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 142 - - \section2 Customizing QStatusBar - - We can provide a background for the status bar and a border for items - inside the status bar as follows: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 143 - - Note that widgets that have been added to the QStatusBar can be styled - using the descendant declaration (i.e) - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 144 - - \section2 Customizing QTabWidget and QTabBar - - \image tabWidget-stylesheet1.png - - For the screenshot above, we need a stylesheet as follows: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 145 - - Often we require the tabs to overlap to look like below: - \image tabWidget-stylesheet2.png - - For a tab widget that looks like above, we make use of - \l{http://www.communitymx.com/content/article.cfm?cid=B0029} - {negative margins}. The resulting stylesheet looks like this: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 146 - - To move the tab bar to the center (as below), we require the following stylesheet: - \image tabWidget-stylesheet3.png - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 147 - - The tear indicator and the scroll buttons can be further customized as follows: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 148 - - Since Qt 4.6 the close button can be customized as follow: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 159 - - \section2 Customizing QTableView - - Suppose we'd like our selected item in QTableView to have bubblegum pink - fade to white as its background. - - \image tableWidget-stylesheet.png - - This is possible with the - \l{stylesheet-reference.html#selection-background-color-prop} - {selection-background-color} property and the syntax required is: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 149 - - The corner widget can be customized using the following style sheet - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 150 - - \section2 Customizing QToolBar - - The background and the handle of a QToolBar is customized as below: - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 151 - - \section2 Customizing QToolBox - - The tabs of the QToolBox are customized using the 'tab' subcontrol. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 152 - - \section2 Customizing QToolButton - - There are three types of QToolButtons. - \list - \i The QToolButton has no menu. In this case, the QToolButton is styled - exactly like QPushButton. See - \l{#Customizing QPushButton}{Customizing QPushButton} for an - example. - - \i The QToolButton has a menu and has the QToolButton::popupMode set to - QToolButton::DelayedPopup or QToolButton::InstantPopup. In this case, - the QToolButton is styled exactly like a QPushButton with a menu. - See \l{#Customizing QPushButton}{Customizing QPushButton} for an - example of the usage of the menu-indicator pseudo state. - - \i The QToolButton has its QToolButton::popupMode set to - QToolButton::MenuButtonPopup. In this case, we style it as follows: - \endlist - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 153 - - - \section2 Customizing QToolTip - - QToolTip is customized exactly like a QLabel. In addition, for platforms - that support it, the opacity property may be set to adjust the opacity. - - For example, - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 154 - - \section2 Customizing QTreeView - - The background color of alternating rows can be customized using the following - style sheet: - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 155 - - To provide a special background when you hover over items, we can use the - \l{item-sub}{::item} subcontrol. For example, - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 156 - - The branches of a QTreeView are styled using the - \l{Qt Style Sheets Reference#branch-sub}{::branch} subcontrol. The - following stylesheet color codes the various states when drawing - a branch. - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 157 - - Colorful, though it is, a more useful example can be made using the - following images: - - \table - \row - \o \inlineimage stylesheet-vline.png - \o \inlineimage stylesheet-branch-more.png - \o \inlineimage stylesheet-branch-end.png - \o \inlineimage stylesheet-branch-closed.png - \o \inlineimage stylesheet-branch-open.png - \row - \o vline.png - \o branch-more.png - \o branch-end.png - \o branch-closed.png - \o branch-open.png - \endtable - - \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 158 - - The resulting tree view looks like this: - - \image stylesheet-treeview.png - - \sa {Style Sheet Example}, {Supported HTML Subset}, QStyle - - - \section1 Common mistakes - - This section lists some common mistakes when using stylesheets. - - \section2 QPushButton and images - - When styling a QPushButton, it is often desirable to use an image as the - button graphic. It is common to try the - \l{Qt Style Sheets Reference#background-image-prop}{background-image} - property, - but this has a number of drawbacks: For instance, the background will - often appear hidden behind the button decoration, because it is not - considered a background. In addition, if the button is resized, the - entire background will be stretched or tiled, which does not - always look good. - - It is better to use the - \l{Qt Style Sheets Reference#border-image-prop}{border-image} - property, as it will always display the image, - regardless of the background (you can combine it with a background if it - has alpha values in it), and it has special settings to deal with button - resizing. - - Consider the following snippet: - - \snippet doc/src/snippets/stylesheet/common-mistakes.cpp 1 - - This will produce a button looking like this: - - \image stylesheet-border-image-normal.png - - The numbers after the url gives the top, right, bottom and left number of - pixels, respectively. These numbers correspond to the border and should not - stretch when the size changes. - Whenever you resize the button, the middle part of the image will stretch - in both directions, while the pixels specified in the stylesheet - will not. This makes the borders of the button look more natural, like - this: - - \table - \row - \o \inlineimage stylesheet-border-image-stretched.png - \row - \o With borders - \endtable - - \table - \row - \o \inlineimage stylesheet-border-image-wrong.png - \row - \o Without borders - \endtable - - */ diff --git a/doc/src/widgets-and-layouts/widgets.qdoc b/doc/src/widgets-and-layouts/widgets.qdoc deleted file mode 100644 index f3f65b67eb..0000000000 --- a/doc/src/widgets-and-layouts/widgets.qdoc +++ /dev/null @@ -1,162 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page widgets-and-layouts.html - \title Widgets and Layouts - \ingroup qt-gui-concepts - \brief The primary elements for designing user interfaces in Qt. - - \section1 Widgets - - Widgets are the primary elements for creating user interfaces in Qt. - \l{The Widget Classes}{Widgets} can display data and status information, - receive user input, and provide a container for other widgets that - should be grouped together. A widget that is not embedded in a - parent widget is called a \l{Window and Dialog Widgets} {window}. - - \image parent-child-widgets.png A parent widget containing various child widgets. - - The QWidget class provides the basic capability to render to the - screen, and to handle user input events. All UI elements that Qt - provides are either subclasses of QWidget, or are used in connection - with a QWidget subclass. Creating custom widgets is done by - subclassing QWidget or a suitable subclass and reimplementing the - virtual event handlers. - - \section1 Layouts - - \l{Layout Management}{Layouts} are an elegant and flexible way to - automatically arrange child widgets within their container. Each - widget reports its size requirements to the layout through the - \l{QWidget::}{sizeHint} and \l{QWidget::}{sizePolicy} properties, - and the layout distributes the available space accordingly. - - \table - \row - \o \image qgridlayout-with-5-children.png - \o \image qformlayout-with-6-children.png - \endtable - - \l{Qt Designer Manual}{\QD} is a powerful tool for interactively creating and - arranging widgets in layouts. - - \section1 Widget Styles - - \l{Styles and Style Aware Widgets}{Styles} draw on behalf of - widgets and encapsulate the look and feel of a GUI. Qt's built-in - widgets use the QStyle class to perform nearly all of their drawing, - ensuring that they look exactly like the equivalent native widgets. - - \table - \row - \o \image windowsxp-tabwidget.png - \o \image plastique-tabwidget.png - \o \image macintosh-tabwidget.png - \endtable - - \l{Qt Style Sheets} are a powerful mechanism that allows you to customize the - appearance of widgets, in addition to what is already possible by subclassing QStyle. - - \section1 The Widget Classes - - The following sections list the widget classes. See the \l{Qt Widget - Gallery} for some examples. - - \section2 Basic Widgets - - These basic widgets (controls), e.g. buttons, comboboxes and - scroll bars, are designed for direct use. - - \table - \row - \o \image windows-label.png - \o \image windowsvista-pushbutton.png - \o \image gtk-progressbar.png - \row - \o \image plastique-combobox.png - \o \image macintosh-radiobutton.png - \o \image cde-lineedit.png - \endtable - - \annotatedlist basicwidgets - - \section2 Advanced Widgets - - Advanced GUI widgets, e.g. tab widgets and progress bars, provide - more complex user interface controls. - - \table - \row - \o \image windowsxp-treeview.png - \o \image gtk-calendarwidget.png - \o \image qundoview.png - \endtable - - \annotatedlist advanced - - \table - \row - \o \image windowsvista-tabwidget.png - \o \image macintosh-groupbox.png - \endtable - - \section2 Organizer Widgets - - Classes like splitters, tab bars, button groups, etc are used for - organizing and grouping GUI primitives into more complex - applications and dialogs. - - \annotatedlist organizers - - \section2 Abstract Widget Classes - - The abstract widget classes are base classes. They are not usable as - standalone classes but provide functionality when they are subclassed. - - \annotatedlist abstractwidgets -*/ - -/*! - \group advanced - \title Advanced Widgets -*/ - -/*! - \group abstractwidgets - \title Abstract Widget Classes -*/ - -/*! - \group basicwidgets - \title Basic Widgets -*/ - -/*! - \group organizers - \title Organizers -*/ diff --git a/doc/src/widgets/addressbook-fr.qdoc b/doc/src/widgets/addressbook-fr.qdoc new file mode 100644 index 0000000000..53b3e6fc15 --- /dev/null +++ b/doc/src/widgets/addressbook-fr.qdoc @@ -0,0 +1,1036 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page tutorials-addressbook-fr.html + + \title Tutoriel "Carnet d'adresses" + \brief Une introduction à la programation d'interface graphique montrant comment construire une application simple avec Qt. + + Ce tutoriel est une introduction à la programmation de GUI (interface utilisateur) + à l'aide des outils fournis par la plateforme multiplate-forme Qt. + + \image addressbook-tutorial-screenshot.png + + Ce tutoriel va nous amener à découvrir quelques technologies fondamentales fournies + par Qt, tel que: + + \list + \o Les Widgets et leur mise en page à l'aide des layouts + \o Les signaux et slots + \o Les structures de données de collections + \o Les entrées/sorties + \endlist + + Si c'est votre premier contact avec Qt, lisez \l{How to Learn Qt}{Comment apprendre Qt} + si ce n'est déjà fait. + + Le code source du tutoriel est distribué avec Qt dans le dossier \c examples/tutorials/addressbook + + Les chapitres du tutoriel: + + \list 1 + \o \l{tutorials/addressbook-fr/part1}{Conception de l'interface utilisateur} + \o \l{tutorials/addressbook-fr/part2}{Ajouter des adresses} + \o \l{tutorials/addressbook-fr/part3}{Navigation entre les éléments} + \o \l{tutorials/addressbook-fr/part4}{éditer et supprimer des adresses} + \o \l{tutorials/addressbook-fr/part5}{Ajout d'une fonction de recherche} + \o \l{tutorials/addressbook-fr/part6}{Sauvegarde et chargement} + \o \l{tutorials/addressbook-fr/part7}{Fonctionnalités avancées} + \endlist + + La petite application que nous développerons ici ne possède pas tous les éléments + des interfaces dernier cri, elle va nous permettre d'utiliser les techniques de base + utilisées dans les applications plus complexes. + + Lorsque vous aurez terminé ce tutoriel, nous vous recommandons de poursuivre avec l'exemple + "\l{mainwindows/application}{Application}", qui présente une interface simple utilisant + les menus et barres d'outils, la barre d'état, etc. + +*/ + +/*! + \page tutorials-addressbook-fr-part1.html + + \example tutorials/addressbook-fr/part1 + \title Carnet d'adresses 1 - Conception de l'interface utilisateur + + La première partie de ce tutoriel traite de la conception d'une interface graphique + (GUI) basique, que l'on utilisera pour l'application Carnet d'adresses. + + La première étape dans la création d'applications graphiques est la conception de + l'interface utilisateur. Dans ce chapitre, nous verrons comment créer les labels + et champs de saisie nécessaires à l'implementation d'un carnet d'adresses de base. + Le résultat attendu est illustré par la capture d'écran ci-dessous. + + \image addressbook-tutorial-part1-screenshot.png + + Nous allons avoir besoin de deux objets QLabel, \c nameLabel et \c addressLabel, + ainsi que deux champs de saisie: un objet QLineEdit, \c nameLine, et un objet + QTextEdit, \c addressText, afin de permettre à l'utilisateur d'entrer le nom d'un + contact et son adresse. Les widgets utilisés ainsi que leur placement sont visibles ci-dessous. + + \image addressbook-tutorial-part1-labeled-screenshot.png + + Trois fichiers sont nécessaires à l'implémentation de ce carnet d'adresses: + + \list + \o \c{addressbook.h} - le fichier de définition (header) pour la classe \c AddressBook, + \o \c{addressbook.cpp} - le fichier source, qui comprend l'implémentation de la classe + \c AddressBook + \o \c{main.cpp} - le fichier qui contient la méthode \c main() , et + une instance de la classe \c AddressBook. + \endlist + + \section1 Programmation en Qt - héritage + + + Lorsque l'on écrit des programmes avec Qt, on a généralement recours à + l'héritage depuis des objets Qt, afin d'y ajouter des fonctionnalités. + C'est l'un des concepts fondamentaux de la création de widgets personnalisés + ou de collections de widgets. Utiliser l'héritage afin de compléter + ou modifier le comportement d'un widget présente les avantages suivants: + + \list + \o La possibilité d'implémenter des méthodes virtuelles et des méthodes + virtuelles pures pour obtenir exactement ce que l'on souhaite, avec la possibilité + d'utiliser l'implémentation de la classe mère si besoin est. + \o Cela permet l'encapsulation partielle de l'interface utilisateur dans une classe, + afin que les autres parties de l'application n'aient pas à se soucier de chacun des + widgets qui forment l'interface utilisateur. + \o La classe fille peut être utilisée pour créer de nombreux widgets personnalisés + dans une même application ou bibliothèque, et le code de la classe fille peut être + réutilisé dans d'autres projets + \endlist + + Comme Qt ne fournit pas de widget standard pour un carnet d'adresses, nous + partirons d'une classe de widget Qt standard et y ajouterons des fonctionnalités. + La classe \c AddressBook crée dans ce tutoriel peut être réutilisée si on a besoin d'un + widget carnet d'adresses basique. + + + \section1 La classe AddressBook + + Le fichier \l{tutorials/addressbook-fr/part1/addressbook.h}{\c addressbook.h} permet de + définir la classe \c AddressBook. + + On commence par définir \c AddressBook comme une classe fille de QWidget et déclarer + un constructeur. On utilise également la macro Q_OBJECT pour indiquer que la classe + exploite les fonctionnalités de signaux et slots offertes par Qt ainsi que + l'internationalisation, bien que nous ne les utilisions pas à ce stade. + + \snippet tutorials/addressbook-fr/part1/addressbook.h class definition + + La classe contient les déclarations de \c nameLine et \c addressText, + les instances privées de QLineEdit et QTextEdit mentionnées précédemment. + Vous verrez, dans les chapitres à venir que les informations contenues + dans \c nameLine et \c addressText sont nécessaires à de nombreuses méthodes + du carnet d'adresses. + + Il n'est pas nécessaire de déclarer les objets QLabel que nous allons utiliser + puisque nous n'aurons pas besoin d'y faire référence après leur création. + La façon dont Qt gère la parenté des objets est traitée dans la section suivante. + + La macro Q_OBJECT implémente des fonctionnalités parmi les plus avancées de Qt. + Pour le moment, il est bon de voir la macro Q_OBJECT comme un raccourci nous + permettant d'utiliser les méthodes \l{QObject::}{tr()} et \l{QObject::}{connect()}. + + Nous en avons maintenant terminé avec le fichier \c addressbook.h et allons + passer à l'implémentation du fichier \c addressbook.cpp. + + \section1 Implémentation de la classe AddressBook + + Le constructeur de la classe \c{AddressBook} prend en paramètre un QWidget, \e parent. + Par convention, on passe ce paramètre au constructeur de la classe mère. + Ce concept de parenté, où un parent peut avoir un ou plusieurs enfants, est utile + pour regrouper les Widgets avec Qt. Par exemple, si vous détruisez le parent, + tous ses enfants seront détruits égalament. + + + \snippet tutorials/addressbook/part1/addressbook.cpp constructor and input fields + + à l'intérieur de ce constructeur, on déclare et instancie deux objets locaux + QLabel, \c nameLabel et \c addressLabel, de même on instancie \c nameLine et + \c addressText. La méthode \l{QObject::tr()}{tr()} renvoie une version traduite + de la chaîne de caractères, si elle existe; dans le cas contraire, elle renvoie + la chaîne elle même. On peut voir cette méthode comme un marqueur \tt{}, permettant de repérer les objets QString à considérer + pour traduire une application. Vous remarquerez, dans les chapitres à venir + comme dans les \l{Qt Examples}{exemples Qt}, qu'elle est utilisée chaque fois + que l'on utilise une chaîne susceptible d'être traduite. + + Lorsque l'on programme avec Qt, il est utile de savoir comment fonctionnent les + agencements ou layouts. Qt fournit trois classes principales de layouts pour + contrôler le placement des widgets: QHBoxLayout, QVBoxLayout et QGridLayout. + + \image addressbook-tutorial-part1-labeled-layout.png + + On utilise un QGridLayout pour positionner nos labels et champs de saisie de manière + structurée. QGridLayout divise l'espace disponible en une grille, et place les + widgets dans les cellules que l'on spécifie par les numéros de ligne et de colonne. + Le diagramme ci-dessus présente les cellules et la position des widgets, et cette + organisation est obtenue à l'aide du code suivant: + + \snippet tutorials/addressbook/part1/addressbook.cpp layout + + On remarque que le label \c AddressLabel est positionné en utilisant Qt::AlignTop + comme argument optionnel. Ceci est destiné à assurer qu'il ne sera pas centré + verticalement dans la cellule (1,0). Pour un aperçu rapide des layouts de Qt, + consultez la section \l{Layout Management}. + + Afin d'installer l'objet layout dans un widget, il faut appeler la méthode + \l{QWidget::setLayout()}{setLayout()} du widget en question: + + \snippet tutorials/addressbook/part1/addressbook.cpp setting the layout + + Enfin, on initialise le titre du widget à "Simple Address Book" + + \section1 Exécution de l'application + + Un fichier séparé, \c main.cpp, est utilisé pour la méthode \c main(). Dans cette + fonction, on crée une instance de QApplication, \c app. QApplication se charge de + des ressources communes à l'ensemble de l'application, tel que les polices de + caractères et le curseur par défaut, ainsi que de l'exécution de la boucle d'évènements. + De ce fait, il y a toujours un objet QApplication dans toute application graphique en Qt. + + \snippet tutorials/addressbook/part1/main.cpp main function + + On construit un nouveau widget \c AddressBook sur la pile et on invoque + sa méthode \l{QWidget::show()}{show()} pour l'afficher. + Cependant, le widget ne sera pas visible tant que la boucle d'évènements + n'aura pas été lancée. On démarre la boucle d'évènements en appelant la + méthode \l{QApplication::}{exec()} de l'application; le résultat renvoyé + par cette méthode est lui même utilisé comme valeur de retour pour la méthode + \c main(). + On comprend maintenant pourquoi \c AddressBook a été créé sur la pile: à la fin + du programme, l'objet sort du scope de la fonction \c main() et tous ses widgets enfants + sont supprimés, assurant ainsi qu'il n'y aura pas de fuites de mémoire. +*/ + +/*! + \page tutorials-addressbook-fr-part2.html + + \example tutorials/addressbook-fr/part2 + \title Carnet d'adresses 2 - Ajouter des adresses + + La prochaine étape pour créer notre carnet d'adresses est d'ajouter un soupçon + d'interactivité. + + \image addressbook-tutorial-part2-add-contact.png + + Nous allons fournir un bouton que l'utilisateur peut + cliquer pour ajouter un nouveau contact. Une structure de données est aussi + nécessaire afin de pouvoir stocker les contacts en mémoire. + + \section1 Définition de la classe AddressBook + + Maintenant que nous avons mis en place les labels et les champs de saisie, + nous ajoutons les boutons pour compléter le processus d'ajout d'un contact. + Cela veut dire que notre fichier \c addressbook.h a maintenant trois + objets QPushButton et trois slots publics correspondant. + + \snippet tutorials/addressbook/part2/addressbook.h slots + + Un slot est une méthode qui répond à un signal. Nous allons + voir ce concept en détail lorsque nous implémenterons la classe \c{AddressBook}. + Pour une explication détaillée du concept de signal et slot, vous pouvez + vous référer au document \l{Signals and Slots}. + + Les trois objets QPushButton \c addButton, \c submitButton et \c cancelButton + sont maintenant inclus dans la déclaration des variables privées, avec + \c nameLine et \c addressText du chapitre précédent. + + \snippet tutorials/addressbook/part2/addressbook.h pushbutton declaration + + Nous avons besoin d'un conteneur pour stocker les contacts du carnet + d'adresses, de façon à pouvoir les énumérer et les afficher. + Un objet QMap, \c contacts, est utilisé pour ça, car il permet de stocker + des paires clé-valeur: le nom du contact est la \e{clé} et l'adresse du contact + est la \e{valeur}. + + \snippet tutorials/addressbook/part2/addressbook.h remaining private variables + + Nous déclarons aussi deux objects QString privés: \c oldName et \c oldAddress. + Ces objets sont nécessaires pour conserver le nom et l'adresse du dernier contact + affiché avant que l'utilisateur ne clique sur le bouton "Add". Grâce à ces variables + si l'utilisateur clique sur "Cancel", il est possible de revenir + à l'affichage du dernier contact. + + \section1 Implémentation de la classe AddressBook + + Dans le constructeur de \c AddressBook, \c nameLine et + \c addressText sont mis en mode lecture seule, de façon à autoriser l'affichage + mais pas la modification du contact courant. + + \dots + \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 1 + \dots + \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 2 + + Ensuite, nous instancions les boutons \c addButton, \c submitButton, et + \c cancelButton. + + \snippet tutorials/addressbook/part2/addressbook.cpp pushbutton declaration + + Le bouton \c addButton est affiché en invoquant la méthode \l{QPushButton::show()} + {show()}, tandis que \c submitButton et \c cancelButton sont cachés en invoquant + \l{QPushButton::hide()}{hide()}. Ces deux boutons ne seront affichés que lorsque + l'utilisateur cliquera sur "Add", et ceci est géré par la méthode \c addContact() + décrite plus loin. + + \snippet tutorials/addressbook/part2/addressbook.cpp connecting signals and slots + + Nous connectons le signal \l{QPushButton::clicked()}{clicked()} de chaque bouton + au slot qui gèrera l'action. + L'image ci-dessous illustre ceci: + + \image addressbook-tutorial-part2-signals-and-slots.png + + Ensuite, nous arrangeons proprement les boutons sur la droite du widget + AddressBook, et nous utilisons un QVBoxLayout pour les aligner verticalement. + + \snippet tutorials/addressbook/part2/addressbook.cpp vertical layout + + La methode \l{QBoxLayout::addStretch()}{addStretch()} est utilisée pour + assurer que les boutons ne sont pas répartis uniformément, mais regroupés + dans la partie supperieure du widget. La figure ci-dessous montre la différence + si \l{QBoxLayout::addStretch()}{addStretch()} est utilisé ou pas. + + \image addressbook-tutorial-part2-stretch-effects.png + + Ensuite nous ajoutons \c buttonLayout1 à \c mainLayout, en utilisant + \l{QGridLayout::addLayout()}{addLayout()}. Ceci nous permet d'imbriquer les + mises en page puisque \c buttonLayout1 est maintenant un enfant de \c mainLayout. + + \snippet tutorials/addressbook/part2/addressbook.cpp grid layout + + Les coordonnées du layout global ressemblent maintenant à ça: + + \image addressbook-tutorial-part2-labeled-layout.png + + Dans la méthode \c addContact(), nous stockons les détails du dernier + contact affiché dans \c oldName et \c oldAddress. Ensuite, nous + vidons ces champs de saisie et nous désactivons le mode + lecture seule. Le focus est placé sur \c nameLine et on affiche + \c submitButton et \c cancelButton. + + \snippet tutorials/addressbook/part2/addressbook.cpp addContact + + La méthode \c submitContact() peut être divisée en trois parties: + + \list 1 + \o Nous extrayons les détails du contact depuis \c nameLine et \c addressText + et les stockons dans des objets QString. Nous les validons pour s'assurer + que l'utilisateur n'a pas cliqué sur "Add" avec des champs de saisie + vides; sinon un message est affiché avec QMessageBox pour rappeller à + l'utilisateur que les deux champs doivent être complétés. + + \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part1 + + \o Ensuite, nous vérifions si le contact existe déjà. Si aucun contacts + existant n'entre en conflit avec le nouveau, nous l'ajoutons à + \c contacts et nous affichons un QMessageBox pour informer l'utilisateur + que le contact a été ajouté. + + \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part2 + + Si le contact existe déjà, nous affichons un QMessageBox pour informer + l'utilisateur du problème. + Notre objet \c contacts est basé sur des paires clé-valeur formés par + le nom et l'adresse, nous voulons nous assurer que la \e clé est unique. + + \o Une fois que les deux vérifications précédentes ont été traitées, + nous restaurons les boutons à leur état normal à l'aide du code + suivant: + + \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part3 + + \endlist + + La capture d'écran ci-dessous montre l'affichage fournit par un objet + QMessageBox, utilisé ici pour afficher un message d'information + à l'utilisateur: + + \image addressbook-tutorial-part2-add-successful.png + + La méthode \c cancel() restaure les détails du dernier contact, active + \c addButton, et cache \c submitButton et \c cancelButton. + + \snippet tutorials/addressbook/part2/addressbook.cpp cancel + + L'idée générale pour augmenter la flexibilité lors de l'ajout d'un + contact est de donner la possiblité de cliquer sur "Add" + ou "Cancel" à n'importe quel moment. + L'organigramme ci-dessous reprend l'ensemble des interactions dévelopées + jusqu'ici: + + \image addressbook-tutorial-part2-add-flowchart.png +*/ + +/*! + \page tutorials-addressbook-fr-part3.html + + \example tutorials/addressbook-fr/part3 + \title Carnet d'adresses 3 - Navigation entre les éléments + + L'application "Carnet d'adresses" est maintenant à moitié terminée. Il + nous faut maintenant ajouter quelques fonctions pour naviguer entre + les contacts. Avant de commencer, il faut se décider sur le type de structure de + données le plus approprié pour stocker les contacts. + + Dans le chapitre 2, nous avons utilisé un QMap utilisant des paires clé-valeur, + avec le nom du contact comme \e clé, et l'adresse du contact comme \e valeur. + Cela fonctionnait bien jusqu'ici, mais pour ajouter la navigation entre les + entrées, quelques améliorations sont nécessaires. + + Nous améliorerons le QMap en le faisant ressembler à une structure de données + similaire à une liste liée, où tous les éléments sont connectés, y compris + le premier et le dernier élément. La figure ci-dessous illustre cette structure + de donnée. + + \image addressbook-tutorial-part3-linkedlist.png + + \section1 Définition de la classe AddressBook + + Pour ajouter les fonctions de navigation au carnet d'adresses, nous avons + besoin de deux slots supplémentaires dans notre classe \c AddressBook: + \c next() et \c previous(). Ceux-ci sont ajoutés au fichier addressbook.h: + + \snippet tutorials/addressbook/part3/addressbook.h navigation functions + + Nous avons aussi besoin de deux nouveaux objets QPushButton, nous ajoutons + donc les variables privées \c nextButton et \c previousButton. + + \snippet tutorials/addressbook/part3/addressbook.h navigation pushbuttons + + \section1 Implémentation de la classe AddressBook + + A l'intérieur du constructeur de \c AddressBook, dans \c addressbook.cpp, nous + instancions \c nextButton et \c previousButton et nous les désactivons + par défaut. Nous faisons ceci car la navigation ne doit être activée + que lorsqu'il y a plus d'un contact dans le carnet d'adresses. + + \snippet tutorials/addressbook/part3/addressbook.cpp navigation pushbuttons + + Nous connectons alors ces boutons à leur slots respectifs: + + \snippet tutorials/addressbook/part3/addressbook.cpp connecting navigation signals + + L'image ci-dessous montre l'interface utilisateur que nous allons créer. + Remarquez que cela ressemble de plus en plus à l'interface du programme + complet. + + \image addressbook-tutorial-part3-screenshot.png + + Nous suivons les conventions pour les fonctions \c next() et \c previous() + en plaçant \c nextButton à droite et \c previousButton à gauche. Pour + faire cette mise en page intuitive, nous utilisons un QHBoxLayout pour + placer les widgets côte à côte: + + \snippet tutorials/addressbook/part3/addressbook.cpp navigation layout + + L'objet QHBoxLayout, \c buttonLayout2, est ensuite ajouté à \c mainLayout. + + \snippet tutorials/addressbook/part3/addressbook.cpp adding navigation layout + + La figure ci-dessous montre les systèmes de coordonnées pour les widgets du + \c mainLayout. + \image addressbook-tutorial-part3-labeled-layout.png + + Dans notre méthode \c addContact(), nous avons desactivé ces boutons + pour être sûr que l'utilisateur n'utilise pas la navigation lors de + l'ajout d'un contact. + + \snippet tutorials/addressbook/part3/addressbook.cpp disabling navigation + + Dans notre méthode \c submitContact(), nous activons les boutons de + navigation, \c nextButton et \c previousButton, en fonction de la + taille de \c contacts. Commen mentionné plus tôt, la navigation n'est + activée que si il y a plus d'un contact dans le carnet d'adresses. + Les lignes suivantes montrent comment faire cela: + + \snippet tutorials/addressbook/part3/addressbook.cpp enabling navigation + + Nous incluons aussi ces lignes de code dans le bouton \c cancel(). + + Souvenez vous que nous voulons émuler une liste-liée ciruculaire à + l'aide de l'objet QMap, \c contacts. Pour faire cela, nous obtenons un itérateur + sur \c contact dans la méthode \c next(), et ensuite: + + \list + \o Si l'itérateur n'est pas à la fin de \c contacts, nous l'incrémentons + \o Si l'itérateur est à la fin de \c contacts, nous changeons sa position + jusqu'au début de \c contacts. Cela donne l'illusion que notre QMap + fonctionne comme une liste circulaire. + \endlist + + \snippet tutorials/addressbook/part3/addressbook.cpp next() function + + Une fois que nous avons itéré jusqu'à l'objet recherché dans \c contacts, + nous affichons son contenu sur \c nameLine et \c addressText. + + De la même façon, pour la méthode \c previous(), nous obtenons un + itérateur sur \c contacts et ensuite: + + \list + \o Si l'itérateur est à la fin de \c contacts, on réinitialise + l'affichage et on retourne. + \o Si l'itérateur est au début de \c contacts, on change sa + position jusqu'à la fin + \o Ensuite, on décrémente l'itérateur + \endlist + + \snippet tutorials/addressbook/part3/addressbook.cpp previous() function + + à nouveau, nous affichons le contenu de l'objet courant dans \c contacts. + +*/ + +/*! + + \page tutorials-addressbook-fr-part4.html + + \example tutorials/addressbook-fr/part4 + \title Carnet d'Adresses 4 - éditer et supprimer des adresses + + + Dans ce chapitre, nous verrons comment modifier les données des contacts + contenus dans l'application carnet d'adresses. + + + \image addressbook-tutorial-screenshot.png + + Nous avons maintenant un carnet d'adresses qui ne se contente pas de + lister des contacts de façon ordonnée, mais permet également la + navigation. Il serait pratique d'inclure des fonctions telles qu'éditer et + supprimer, afin que les détails associés à un contact puissent être + modifiés lorsque c'est nécessaire. Cependant, cela requiert une légère + modification, sous la forme d'énumérations. Au chapitre précédent, nous avions deux + modes: \c {AddingMode} et \c {NavigationMode}, mais ils n'étaient pas + définis en tant qu'énumérations. Au lieu de ça, on activait et désactivait les + boutons correspondants manuellement, au prix de multiples redondances dans + le code. + + Dans ce chapitre, on définit l'énumération \c Mode avec trois valeurs possibles. + + \list + \o \c{NavigationMode}, + \o \c{AddingMode}, et + \o \c{EditingMode}. + \endlist + + \section1 Définition de la classe AddressBook + + Le fichier \c addressbook.h est mis a jour pour contenir l'énumération \c Mode : + + \snippet tutorials/addressbook/part4/addressbook.h Mode enum + + On ajoute également deux nouveaux slots, \c editContact() et + \c removeContact(), à notre liste de slots publics. + + \snippet tutorials/addressbook/part4/addressbook.h edit and remove slots + + Afin de basculer d'un mode à l'autre, on introduit la méthode + \c updateInterface() pour contrôller l'activation et la désactivation de + tous les objets QPushButton. On ajoute également deux nouveaux boutons, + \c editButton et \c removeButton, pour les fonctions d'édition + et de suppression mentionnées plus haut. + + \snippet tutorials/addressbook/part4/addressbook.h updateInterface() declaration + \dots + \snippet tutorials/addressbook/part4/addressbook.h buttons declaration + \dots + \snippet tutorials/addressbook/part4/addressbook.h mode declaration + + Enfin, on déclare \c currentMode pour garder une trace du mode + actuellement utilisé. + + \section1 Implémentation de la classe AddressBook + + Il nous faut maintenant implémenter les fonctionnalités de changement de + mode de l'application carnet d'adresses. Les boutons \c editButton et + \c removeButton sont instanciés et désactivés par défaut, puisque le + carnet d'adresses démarre sans aucun contact en mémoire. + + \snippet tutorials/addressbook/part4/addressbook.cpp edit and remove buttons + + Ces boutons sont ensuite connectés à leurs slots respectifs, + \c editContact() et \c removeContact(), avant d'être ajoutés à + \c buttonLayout1. + + \snippet tutorials/addressbook/part4/addressbook.cpp connecting edit and remove + \dots + \snippet tutorials/addressbook/part4/addressbook.cpp adding edit and remove to the layout + + La methode \c editContact() place les anciens détails du contact dans + \c oldName et \c oldAddress, avant de basculer vers le mode + \c EditingMode. Dans ce mode, les boutons \c submitButton et + \c cancelButton sont tous deux activés, l'utilisateur peut par conséquent + modifier les détails du contact et cliquer sur l'un de ces deux boutons + par la suite. + + \snippet tutorials/addressbook/part4/addressbook.cpp editContact() function + + La méthode \c submitContact() a été divisée en deux avec un bloc + \c{if-else}. On teste \c currentMode pour voir si le mode courant est + \c AddingMode. Si c'est le cas, on procède à l'ajout. + + \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function beginning + \dots + \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part1 + + Sinon, on s'assure que \c currentMode est en \c EditingMode. Si c'est le + cas, on compare \c oldName et \c name. Si le nom a changé, on supprime + l'ancien contact de \c contacts et on insère le contact mis a jour. + + \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part2 + + Si seule l'adresse a changé (i.e. \c oldAddress n'est pas identique à + \c address), on met à jour l'adresse du contact. Enfin on règle + \c currentMode à \c NavigationMode. C'est une étape importante puisque + c'est cela qui réactive tous les boutons désactivés. + + Afin de retirer un contact du carnet d'adresses, on implémente la méthode + \c removeContact(). Cette méthode vérifie que le contact est présent dans + \c contacts. + + \snippet tutorials/addressbook/part4/addressbook.cpp removeContact() function + + Si c'est le cas, on affiche une boîte de dialogue QMessageBox, demandant + confirmation de la suppression à l'utilisateur. Une fois la confirmation + effectuée, on appelle \c previous(), afin de s'assurer que l'interface + utilisateur affiche une autre entrée, et on supprime le contact en + utilisant le méthode \l{QMap::remove()}{remove()} de \l{QMap}. Dans un + souci pratique, on informe l'utilisateur de la suppression par le biais + d'une autre QMessageBox. Les deux boîtes de dialogue utilisées dans cette + méthode sont représentées ci-dessous. + + \image addressbook-tutorial-part4-remove.png + + \section2 Mise à jour de l'Interface utilisateur + + On a évoqué plus haut la méthode \c updateInterface() comme moyen + d'activer et de désactiver les différents boutons de l'interface en + fonction du mode. Cette méthode met à jour le mode courant selon + l'argument \c mode qui lui est passé, en l'assignant à \c currentMode, + avant de tester sa valeur. + + Chacun des boutons est ensuite activé ou désactivé, en fonction du mode. + Le code source pour les cas \c AddingMode et \c EditingMode est visible + ci-dessous: + + \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 1 + + Dans le cas de \c NavigationMode, en revanche, des tests conditionnels + sont passés en paramètre de QPushButton::setEnabled(). Ceci permet de + s'assurer que les boutons \c editButton et \c removeButton ne sont activés + que s'il existe au moins un contact dans le carnet d'adresses; + \c nextButton et \c previousButton ne sont activés que lorsqu'il existe + plus d'un contact dans le carnet d'adresses. + + \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 2 + + En effectuant les opérations de réglage du mode et de mise à jour de + l'interface utilisateur au sein de la même méthode, on est à l'abri de + l'éventualité où l'interface utilisateur se "désynchronise" de l'état + interne de l'application. + +*/ + +/*! + \page tutorials-addressbook-fr-part5.html + + \example tutorials/addressbook-fr/part5 + \title Carnet d'adresse 5 - Ajout d'une fonction de recherche + + Dans ce chapitre, nous allons voir les possibilités pour rechercher + des contacts dans le carnet d'adresse. + + \image addressbook-tutorial-part5-screenshot.png + + Plus nous ajoutons des contacts dans l'application, plus + il devient difficile de naviguer avec les boutons \e Next et \e Previous. + Dans ce cas, une fonction de recherche serait plus efficace pour rechercher + les contacts. + La capture d'écran ci-dessus montre le bouton de recherche \e Find et sa position + dans le paneau de bouton. + + Lorsque l'utilisateur clique sur le bouton \e Find, il est courant d'afficher + une boîte de dialogue qui demande à l'utilisateur d'entrer un nom de contact. + Qt fournit la classe QDialog, que nous sous-classons dans ce chapitre pour + implémenter la class \c FindDialog. + + \section1 Définition de la classe FindDialog + + \image addressbook-tutorial-part5-finddialog.png + + Pour sous-classer QDialog, nous commençons par inclure le header de + QDialog dans le fichier \c finddialog.h. De plus, nous déclarons les + classes QLineEdit et QPushButton car nous utilisons ces widgets dans + notre classe dialogue. + + Tout comme dans la classe \c AddressBook, la classe \c FindDialog utilise + la macro Q_OBJECT et son constructeur est défini de façon à accepter + un QWidget parent, même si cette boîte de dialogue sera affichée dans une + fenêtre séparée. + + \snippet tutorials/addressbook/part5/finddialog.h FindDialog header + + Nous définissons la méthode publique \c getFindText() pour être utilisée + par les classes qui instancient \c FindDialog, ce qui leur permet d'obtenir + le texte entré par l'utilisateur. Un slot public, \c findClicked(), est + défini pour prendre en charge le texte lorsque l'utilisateur clique sur + le bouton \gui Find. + + Finalement, nous définissons les variables privées \c findButton, + \c lineEdit et \c findText, qui correspondent respectivement au bouton + \gui Find, au champ de texte dans lequel l'utilisateur tape le texte + à rechercher, et à une variable interne stockant le texte pour une + utilisation ultérieure. + + \section1 Implémentation de la classe FindDialog + + Dans le constructeur de \c FindDialog, nous instancions les objets des + variables privées \c lineEdit, \c findButton et \c findText. Nous utilisons ensuite + un QHBoxLayout pour positionner les widgets. + + \snippet tutorials/addressbook/part5/finddialog.cpp constructor + + Nous mettons en place la mise en page et le titre de la fenêtre, et + nous connectons les signaux aux slots. Remarquez que le signal + \l{QPushButton::clicked()}{clicked()} de \c{findButton} est connecté + à \c findClicked() et \l{QDialog::accept()}{accept()}. Le slot + \l{QDialog::accept()}{accept()} fourni par le QDialog ferme + la boîte de dialogue et lui donne le code de retour \l{QDialog::}{Accepted}. + Nous utilisons cette fonction pour aider la méthode \c findContact() de la classe + \c{AddressBook} à savoir si l'objet \c FindDialog a été fermé. Ceci sera + expliqué plus loin lorsque nous verrons la méthode \c findContact(). + + \image addressbook-tutorial-part5-signals-and-slots.png + + Dans \c findClicked(), nous validons le champ de texte pour nous + assurer que l'utilisateur n'a pas cliqué sur le bouton \gui Find sans + avoir entré un nom de contact. Ensuite, nous stockons le texte du champ + d'entrée \c lineEdit dans \c findText. Et finalement nous vidons le + contenu de \c lineEdit et cachons la boîte de dialogue. + + \snippet tutorials/addressbook/part5/finddialog.cpp findClicked() function + + La variable \c findText a un accesseur publique associé: \c getFindText(). + Étant donné que nous ne modifions \c findText directement que dans le + constructeur et la méthode \c findClicked(), nous ne créons pas + de manipulateurs associé à \c getFindText(). + Puisque \c getFindText() est publique, les classes instanciant et + utilisant \c FindDialog peuvent toujours accéder à la chaîne de + caractères que l'utilisateur a entré et accepté. + + \snippet tutorials/addressbook/part5/finddialog.cpp getFindText() function + + \section1 Définition de la classe AddressBook + + Pour utiliser \c FindDialog depuis la classe \c AddressBook, nous + incluons \c finddialog.h dans le fichier \c addressbook.h. + + \snippet tutorials/addressbook/part5/addressbook.h include finddialog's header + + Jusqu'ici, toutes les fonctionnalités du carnet d'adresses ont un + QPushButton et un slot correspondant. De la même façon, pour la + fonctionnalité \gui Find, nous avons \c findButton et \c findContact(). + + Le \c findButton est déclaré comme une variable privée et la + méthode \c findContact() est déclarée comme un slot public. + + \snippet tutorials/addressbook/part5/addressbook.h findContact() declaration + \dots + \snippet tutorials/addressbook/part5/addressbook.h findButton declaration + + Finalement, nous déclarons la variable privée \c dialog que nous allons + utiliser pour accéder à une instance de \c FindDialog. + + \snippet tutorials/addressbook/part5/addressbook.h FindDialog declaration + + Une fois que nous avons instancié la boîte de dialogue, nous voulons l'utiliser + plus qu'une fois. Utiliser une variable privée nous permet d'y référer + à plus d'un endroit dans la classe. + + \section1 Implémentation de la classe AddressBook + + Dans le constructeur de \c AddressBook, nous instancions nos objets privés, + \c findbutton et \c findDialog: + + \snippet tutorials/addressbook/part5/addressbook.cpp instantiating findButton + \dots + \snippet tutorials/addressbook/part5/addressbook.cpp instantiating FindDialog + + Ensuite, nous connectons le signal \l{QPushButton::clicked()}{clicked()} de + \c{findButton} à \c findContact(). + + \snippet tutorials/addressbook/part5/addressbook.cpp signals and slots for find + + Maintenant, tout ce qui manque est le code de notre méthode \c findContact(): + + \snippet tutorials/addressbook/part5/addressbook.cpp findContact() function + + Nous commençons par afficher l'instance de \c FindDialog, \c dialog. + L'utilisateur peut alors entrer le nom du contact à rechercher. Lorsque + l'utilisateur clique sur le bouton \c findButton, la boîte de dialogue est + masquée et le code de retour devient QDialog::Accepted. Ce code de retour + vient remplir la condition du premier if. + + Ensuite, nous extrayons le texte que nous utiliserons pour la recherche, + il s'agit ici de \c contactName obtenu à l'aide de la méthode \c getFindText() + de \c FindDialog. Si le contact existe dans le carnet d'adresse, nous + l'affichons directement. Sinon, nous affichons le QMessageBox suivant pour + indiquer que la recherche à échouée. + + \image addressbook-tutorial-part5-notfound.png +*/ + +/*! + \page tutorials-addressbook-part6.html + + \example tutorials/addressbook-fr/part6 + \title Carnet d'Adresses 6 - Sauvegarde et chargement + + Ce chapitre couvre les fonctionnalités de gestion des fichiers de Qt que + l'on utilise pour écrire les procédures de sauvegarde et chargement pour + l'application carnet d'adresses. + + \image addressbook-tutorial-part6-screenshot.png + + Bien que la navigation et la recherche de contacts soient des + fonctionnalités importantes, notre carnet d'adresses ne sera pleinement + utilisable qu'une fois que l'on pourra sauvegarder les contacts existants + et les charger à nouveau par la suite. + Qt fournit de nombreuses classes pour gérer les \l{Input/Output and + Networking}{entrées et sorties}, mais nous avons choisi de nous contenter d'une + combinaison de deux classes simples à utiliser ensemble: QFile et QDataStream. + + Un objet QFile représente un fichier sur le disque qui peut être lu, et + dans lequel on peut écrire. QFile est une classe fille de la classe plus + générique QIODevice, qui peut représenter différents types de + périphériques. + + Un objet QDataStream est utilisé pour sérialiser des données binaires + dans le but de les passer à un QIODevice pour les récupérer dans le + futur. Pour lire ou écrire dans un QIODevice, il suffit d'ouvrir le + flux, avec le périphérique approprié en paramètre, et d'y lire ou + écrire. + + \section1 Définition de la classe AddressBook + + On déclare deux slots publics, \c saveToFile() et \c loadFromFile(), + ainsi que deux objets QPushButton, \c loadButton et \c saveButton. + + \snippet tutorials/addressbook/part6/addressbook.h save and load functions declaration + \dots + \snippet tutorials/addressbook/part6/addressbook.h save and load buttons declaration + + \section1 Implémentation de la classe AddressBook + + Dans notre constructeur, on instancie \c loadButton et \c saveButton. + Idéalement, l'interface serait plus conviviale avec des boutons + affichant "Load contacts from a file" et "Save contacts to a file". Mais + compte tenu de la dimension des autres boutons, on initialise les labels + des boutons à \gui{Load...} et \gui{Save...}. Heureusement, Qt offre une + façon simple d'ajouter des info-bulles avec + \l{QWidget::setToolTip()}{setToolTip()}, et nous l'exploitons de la façon + suivante pour nos boutons: + + \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 1 + \dots + \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 2 + + Bien qu'on ne cite pas le code correspondant ici, nous ajoutons ces deux boutons au + layout de droite, \c button1Layout, comme pour les fonctionnalités précédentes, et + nous connectons leurs signaux + \l{QPushButton::clicked()}{clicked()} à leurs slots respectifs. + + Pour la sauvegarde, on commence par récupérer le nom de fichier + \c fileName, en utilisant QFileDialog::getSaveFileName(). C'est une + méthode pratique fournie par QFileDialog, qui ouvre une boîte de + dialogue modale et permet à l'utilisateur d'entrer un nom de fichier ou + de choisir un fichier \c{.abk} existant. Les fichiers \c{.abk} + correspondent à l'extension choisie pour la sauvegarde des contacts de + notre carnet d'adresses. + + \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part1 + + La boîte de dialogue affichée est visible sur la capture d'écran ci- + dessous. + + \image addressbook-tutorial-part6-save.png + + Si \c fileName n'est pas vide, on crée un objet QFile, \c file, à partir + de \c fileName. QFile fonctionne avec QDataStream puisqu'il dérive de + QIODevice. + + Ensuite, on essaie d'ouvrir le fichier en écriture, ce qui correspond au + mode \l{QIODevice::}{WriteOnly}. Si cela échoue, on en informe + l'utilisateur avec une QMessageBox. + + \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part2 + + Dans le cas contraire, on instancie un objet QDataStream, \c out, afin + d'écrire dans le fichier ouvert. QDataStream nécessite que la même + version de flux soit utilisée pour la lecture et l'écriture. On s'assure + que c'est le cas en spécifiant explicitement d'utiliser la + \l{QDataStream::Qt_4_5}{version introduite avec Qt 4.5} avant de + sérialiser les données vers le fichier \c file. + + \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part3 + + Pour le chargement, on récupère également \c fileName en utilisant + QFileDialog::getOpenFileName(). Cette méthode est l'homologue de + QFileDialog::getSaveFileName() et affiche également une boîte de + dialogue modale permettant à l'utilisateur d'entrer un nom de fichier ou + de selectionner un fichier \c{.abk} existant, afin de le charger dans le + carnet d'adresses. + + \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part1 + + Sous Windows, par exemple, cette méthode affiche une boîte de dialogue + native pour la sélection de fichier, comme illustré sur la capture + d'écran suivante: + + \image addressbook-tutorial-part6-load.png + + Si \c fileName n'est pas vide, on utilise une fois de plus un objet + QFile, \c file, et on tente de l'ouvrir en lecture, avec le mode + \l{QIODevice::}{ReadOnly}. De même que précédemment dans notre + implémentation de \c saveToFile(), si cette tentative s'avère + infructueuse, on en informe l'utilisateur par le biais d'une + QMessageBox. + + \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part2 + + Dans le cas contraire, on instancie un objet QDataStream, \c in, en + spécifiant la version à utiliser comme précédemment, et on lit les + informations sérialisées vers la structure de données \c contacts. Notez + qu'on purge \c contacts avant d'y mettre les informations lues afin de + simplifier le processus de lecture de fichier. Une façon plus avancée de + procéder serait de lire les contacts dans un objet QMap temporaire, et + de copier uniquement les contacts n'existant pas encore dans + \c contacts. + + \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part3 + + Pour afficher les contacts lus depuis le fichier, on doit d'abord + valider les données obtenues afin de s'assurer que le fichier lu + contient effectivement des entrées de carnet d'adresses. Si c'est le + cas, on affiche le premier contact; sinon on informe l'utilisateur du + problème par une QMessageBox. Enfin, on met à jour l'interface afin + d'activer et de désactiver les boutons de façon appropriée. +*/ + +/*! + \page tutorials-addressbook-fr-part7.html + + \example tutorials/addressbook-fr/part7 + \title Carnet d'adresse 7 - Fonctionnalités avancées + + Ce chapitre couvre quelques fonctionnalités additionnelles qui + feront de notre carnet d'adresses une application plus pratique + pour une utilisation quotidienne. + + \image addressbook-tutorial-part7-screenshot.png + + Bien que notre application carnet d'adresses soit utile en tant que telle, + il serait pratique de pouvoir échanger les contacts avec d'autres applications. + Le format vCard est un un format de fichier populaire pour échanger + ce type de données. + Dans ce chapitre, nous étendrons notre carnet d'adresses pour permettre + d'exporter des contacts dans des fichiers vCard \c{.vcf}. + + \section1 Définition de la classe AddressBook + + Nous ajoutons un objet QPushButton, \c exportButton, et un slot + public correspondant, \c exportAsVCard(), à notre classe \c AddressBook + dans le fichier \c addressbook.h. + + \snippet tutorials/addressbook/part7/addressbook.h exportAsVCard() declaration + \dots + \snippet tutorials/addressbook/part7/addressbook.h exportButton declaration + + \section1 Implémentation de la classe AddressBook + + Dans le constructeur de \c AddressBook, nous connectons le signal + \l{QPushButton::clicked()}{clicked()} de \c{exportButton} au slot + \c exportAsVCard(). + Nous ajoutons aussi ce bouton à \c buttonLayout1, le layout responsable + du groupe de boutons sur la droite. + + Dans la méthode \c exportAsVCard(), nous commençons par extraire le + nom du contact dans \n name. Nous déclarons \c firstname, \c lastName et + \c nameList. + Ensuite, nous cherchons la position du premier espace blanc de \c name. + Si il y a un espace, nous séparons le nom du contact en \c firstName et + \c lastName. Finalement, nous remplaçons l'espace par un underscore ("_"). + Si il n'y a pas d'espace, nous supposons que le contact ne comprend que + le prénom. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part1 + + Comme pour la méthode \c saveToFile(), nous ouvrons une boîte de dialogue + pour donner la possibilité à l'utilisateur de choisir un emplacement pour + le fichier. Avec le nom de fichier choisi, nous créons une instance de QFile + pour y écrire. + + Nous essayons d'ouvrir le fichier en mode \l{QIODevice::}{WriteOnly}. Si + cela échoue, nous affichons un QMessageBox pour informer l'utilisateur + à propos de l'origine du problème et nous quittons la méthode. Sinon, nous passons le + fichier comme paramètre pour créer un objet QTextStream, \c out. De la même façon que + QDataStream, la classe QTextStream fournit les fonctionnalités pour + lire et écrire des fichiers de texte. Grâce à celà, le fichier \c{.vcf} + généré pourra être ouvert et édité à l'aide d'un simple éditeur de texte. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part2 + + Nous écrivons ensuite un fichier vCard avec la balise \c{BEGIN:VCARD}, + suivit par \c{VERSION:2.1}. + Le nom d'un contact est écrit à l'aide de la balise \c{N:}. Pour la balise + \c{FN:}, qui remplit le titre du contact, nous devons vérifier si le contact + à un nom de famille défini ou non. Si oui, nous utilions les détails de + \c nameList pour remplir le champ, dans le cas contraire on écrit uniquement le contenu + de \c firstName. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part3 + + Nous continuons en écrivant l'adresse du contact. Les points-virgules + dans l'adresse sont échappés à l'aide de "\\", les retours de ligne sont + remplacés par des points-virgules, et les vigules sont remplacées par des espaces. + Finalement nous écrivons les balises \c{ADR;HOME:;} suivies par l'adresse + et la balise \c{END:VCARD}. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part4 + + À la fin de la méthode, un QMessageBox est affiché pour informer l'utilisateur + que la vCard a été exportée avec succès. + + \e{vCard est une marque déposée de \l{http://www.imc.org} + {Internet Mail Consortium}}. +*/ diff --git a/doc/src/widgets/addressbook.qdoc b/doc/src/widgets/addressbook.qdoc new file mode 100644 index 0000000000..d75e2cac2a --- /dev/null +++ b/doc/src/widgets/addressbook.qdoc @@ -0,0 +1,981 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page tutorials-addressbook.html + + \title Address Book Tutorial + \brief An introduction to GUI programming, showing how to put together a + simple yet fully-functioning application. + + This tutorial is an introduction to GUI programming with the Qt + cross-platform framework. + + \image addressbook-tutorial-screenshot.png + + \omit + It doesn't cover everything; the emphasis is on teaching the programming + philosophy of GUI programming, and Qt's features are introduced as needed. + Some commonly used features are never used in this tutorial. + \endomit + + In this tutorial, you will learn about some of the basic + components of Qt, including: + + \list + \o Widgets and layout managers + \o Container classes + \o Signals and slots + \o Input and output devices + \endlist + + If you are new to Qt, we recommend reading \l{How to Learn Qt} first. + + Tutorial contents: + + \list 1 + \o \l{tutorials/addressbook/part1}{Designing the User Interface} + \o \l{tutorials/addressbook/part2}{Adding Addresses} + \o \l{tutorials/addressbook/part3}{Navigating between Entries} + \o \l{tutorials/addressbook/part4}{Editing and Removing Addresses} + \o \l{tutorials/addressbook/part5}{Adding a Find Function} + \o \l{tutorials/addressbook/part6}{Loading and Saving} + \o \l{tutorials/addressbook/part7}{Additional Features} + \endlist + + The tutorial source code is located in \c{examples/tutorials/addressbook}. + + Although this little application does not look much like a + fully-fledged modern GUI application, it uses many of the basic + elements that are used in more complex applications. After you + have worked through this tutorial, we recommend reading the + \l{mainwindows/application}{Application} example, which presents a + small GUI application, with menus, toolbars, a status bar, and so + on. +*/ + +/*! + \page tutorials-addressbook-part1.html + + \example tutorials/addressbook/part1 + \title Part 1 - Designing the User Interface + + This first part covers the design of the basic graphical user + interface (GUI) for our address book application. + + The first step in creating a GUI program is to design the user + interface. Here the our goal is to set up the labels and input + fields to implement a basic address book. The figure below is a + screenshot of the expected output. + + \image addressbook-tutorial-part1-screenshot.png + + We require two QLabel objects, \c nameLabel and \c addressLabel, as well + as two input fields, a QLineEdit object, \c nameLine, and a QTextEdit + object, \c addressText, to enable the user to enter a contact's name and + address. The widgets used and their positions are shown in the figure + below. + + \image addressbook-tutorial-part1-labeled-screenshot.png + + There are three files used to implement this address book: + + \list + \o \c{addressbook.h} - the definition file for the \c AddressBook + class, + \o \c{addressbook.cpp} - the implementation file for the + \c AddressBook class, and + \o \c{main.cpp} - the file containing a \c main() function, with + an instance of \c AddressBook. + \endlist + + \section1 Qt Programming - Subclassing + + When writing Qt programs, we usually subclass Qt objects to add + functionality. This is one of the essential concepts behind creating + custom widgets or collections of standard widgets. Subclassing to + extend or change the behavior of a widget has the following advantages: + + \list + \o We can write implementations of virtual or pure virtual functions to + obtain exactly what we need, falling back on the base class's implementation + when necessary. + \o It allows us to encapsulate parts of the user interface within a class, + so that the other parts of the application don't need to know about the + individual widgets in the user interface. + \o The subclass can be used to create multiple custom widgets in the same + application or library, and the code for the subclass can be reused in other + projects. + \endlist + + Since Qt does not provide a specific address book widget, we subclass a + standard Qt widget class and add features to it. The \c AddressBook class + we create in this tutorial can be reused in situations where a basic address + book widget is needed. + + \section1 Defining the AddressBook Class + + The \l{tutorials/addressbook/part1/addressbook.h}{\c addressbook.h} file is + used to define the \c AddressBook class. + + We start by defining \c AddressBook as a QWidget subclass and declaring + a constructor. We also use the Q_OBJECT macro to indicate that the class + uses internationalization and Qt's signals and slots features, even + if we do not use all of these features at this stage. + + \snippet tutorials/addressbook/part1/addressbook.h class definition + + The class holds declarations of \c nameLine and \c addressText, + the private instances of QLineEdit and QTextEdit mentioned + earlier. The data stored in \c nameLine and \c addressText will + be needed for many of the address book functions. + + We don't include declarations of the QLabel objects we will use + because we will not need to reference them once they have been + created. The way Qt tracks the ownership of objects is explained + in the next section. + + The Q_OBJECT macro itself implements some of the more advanced features of Qt. + For now, it is useful to think of the Q_OBJECT macro as a shortcut which allows + us to use the \l{QObject::}{tr()} and \l{QObject::}{connect()} functions. + + We have now completed the \c addressbook.h file and we move on to + implement the corresponding \c addressbook.cpp file. + + \section1 Implementing the AddressBook Class + + The constructor of \c AddressBook accepts a QWidget parameter, \a parent. + By convention, we pass this parameter to the base class's constructor. + This concept of ownership, where a parent can have one or more children, + is useful for grouping widgets in Qt. For example, if you delete a parent, + all of its children will be deleted as well. + + \snippet tutorials/addressbook/part1/addressbook.cpp constructor and input fields + + In this constructor, the QLabel objects \c nameLabel and \c + addressLabel are instantiated, as well as \c nameLine and \c + addressText. The \l{QObject::tr()}{tr()} function returns a + translated version of the string, if there is one + available. Otherwise it returns the string itself. This function + marks its QString parameter as one that should be translated into + other languages. It should be used wherever a translatable string + appears. + + When programming with Qt, it is useful to know how layouts work. + Qt provides three main layout classes: QHBoxLayout, QVBoxLayout + and QGridLayout to handle the positioning of widgets. + + \image addressbook-tutorial-part1-labeled-layout.png + + We use a QGridLayout to position our labels and input fields in a + structured manner. QGridLayout divides the available space into a grid and + places widgets in the cells we specify with row and column numbers. The + diagram above shows the layout cells and the position of our widgets, and + we specify this arrangement using the following code: + + \snippet tutorials/addressbook/part1/addressbook.cpp layout + + Notice that \c addressLabel is positioned using Qt::AlignTop as an + additional argument. This is to make sure it is not vertically centered in + cell (1,0). For a basic overview on Qt Layouts, refer to the + \l{Layout Management} documentation. + + In order to install the layout object onto the widget, we have to invoke + the widget's \l{QWidget::setLayout()}{setLayout()} function: + + \snippet tutorials/addressbook/part1/addressbook.cpp setting the layout + + Lastly, we set the widget's title to "Simple Address Book". + + \section1 Running the Application + + A separate file, \c main.cpp, is used for the \c main() function. Within + this function, we instantiate a QApplication object, \c app. QApplication + is responsible for various application-wide resources, such as the default + font and cursor, and for running an event loop. Hence, there is always one + QApplication object in every GUI application using Qt. + + \snippet tutorials/addressbook/part1/main.cpp main function + + We construct a new \c AddressBook widget on the stack and invoke + its \l{QWidget::show()}{show()} function to display it. + However, the widget will not be shown until the application's event loop + is started. We start the event loop by calling the application's + \l{QApplication::}{exec()} function; the result returned by this function + is used as the return value from the \c main() function. At this point, + it becomes apparent why we instanciated \c AddressBook on the stack: It + will now go out of scope. Therefore, \c AddressBook and all its child widgets + will be deleted, thus preventing memory leaks. +*/ + +/*! + \page tutorials-addressbook-part2.html + + \example tutorials/addressbook/part2 + \title Part 2 - Adding Addresses + + The next step in creating the address book is to implement some + user interactions. + + \image addressbook-tutorial-part2-add-contact.png + + We will provide a push button that the user can click to add a new contact. + Also, some form of data structure is needed to store these contacts in an + organized way. + + \section1 Defining the AddressBook Class + + Now that we have the labels and input fields set up, we add push buttons to + complete the process of adding a contact. This means that our + \c addressbook.h file now has three QPushButton objects declared and three + corresponding public slots. + + \snippet tutorials/addressbook/part2/addressbook.h slots + + A slot is a function that responds to a particular signal. We will discuss + this concept in further detail when implementing the \c AddressBook class. + However, for an overview of Qt's signals and slots concept, you can refer + to the \l{Signals and Slots} document. + + Three QPushButton objects (\c addButton, \c submitButton, and + \c cancelButton) are now included in our private variable declarations, + along with \c nameLine and \c addressText. + + \snippet tutorials/addressbook/part2/addressbook.h pushbutton declaration + + We need a container to store our address book contacts, so that we can + traverse and display them. A QMap object, \c contacts, is used for this + purpose as it holds a key-value pair: the contact's name as the \e key, + and the contact's address as the \e{value}. + + \snippet tutorials/addressbook/part2/addressbook.h remaining private variables + + We also declare two private QString objects, \c oldName and \c oldAddress. + These objects are needed to hold the name and address of the contact that + was last displayed, before the user clicked \gui Add. So, when the user clicks + \gui Cancel, we can revert to displaying the details of the last contact. + + \section1 Implementing the AddressBook Class + + Within the constructor of \c AddressBook, we set the \c nameLine and + \c addressText to read-only, so that we can only display but not edit + existing contact details. + + \dots + \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 1 + \dots + \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 2 + + Then, we instantiate our push buttons: \c addButton, \c submitButton, and + \c cancelButton. + + \snippet tutorials/addressbook/part2/addressbook.cpp pushbutton declaration + + The \c addButton is displayed by invoking the \l{QPushButton::show()} + {show()} function, while the \c submitButton and \c cancelButton are + hidden by invoking \l{QPushButton::hide()}{hide()}. These two push + buttons will only be displayed when the user clicks \gui Add and this is + handled by the \c addContact() function discussed below. + + \snippet tutorials/addressbook/part2/addressbook.cpp connecting signals and slots + + We connect the push buttons' \l{QPushButton::clicked()}{clicked()} signal + to their respective slots. The figure below illustrates this. + + \image addressbook-tutorial-part2-signals-and-slots.png + + Next, we arrange our push buttons neatly to the right of our address book + widget, using a QVBoxLayout to line them up vertically. + + \snippet tutorials/addressbook/part2/addressbook.cpp vertical layout + + The \l{QBoxLayout::addStretch()}{addStretch()} function is used to ensure + the push buttons are not evenly spaced, but arranged closer to the top of + the widget. The figure below shows the difference between using + \l{QBoxLayout::addStretch()}{addStretch()} and not using it. + + \image addressbook-tutorial-part2-stretch-effects.png + + We then add \c buttonLayout1 to \c mainLayout, using + \l{QGridLayout::addLayout()}{addLayout()}. This gives us nested layouts + as \c buttonLayout1 is now a child of \c mainLayout. + + \snippet tutorials/addressbook/part2/addressbook.cpp grid layout + + Our layout coordinates now look like this: + + \image addressbook-tutorial-part2-labeled-layout.png + + In the \c addContact() function, we store the last displayed contact + details in \c oldName and \c oldAddress. Then we clear these input + fields and turn off the read-only mode. The focus is set on \c nameLine + and we display \c submitButton and \c cancelButton. + + \snippet tutorials/addressbook/part2/addressbook.cpp addContact + + The \c submitContact() function can be divided into three parts: + + \list 1 + \o We extract the contact's details from \c nameLine and \c addressText + and store them in QString objects. We also validate to make sure that the + user did not click \gui Submit with empty input fields; otherwise, a + QMessageBox is displayed to remind the user for a name and address. + + \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part1 + + \o We then proceed to check if the contact already exists. If it does not + exist, we add the contact to \c contacts and we display a QMessageBox to + inform the user that the contact has been added. + + \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part2 + + If the contact already exists, again, we display a QMessageBox to inform + the user about this, preventing the user from adding duplicate contacts. + Our \c contacts object is based on key-value pairs of name and address, + hence, we want to ensure that \e key is unique. + + \o Once we have handled both cases mentioned above, we restore the push + buttons to their normal state with the following code: + + \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part3 + + \endlist + + The screenshot below shows the QMessageBox object we use to display + information messages to the user. + + \image addressbook-tutorial-part2-add-successful.png + + The \c cancel() function restores the last displayed contact details and + enables \c addButton, as well as hides \c submitButton and + \c cancelButton. + + \snippet tutorials/addressbook/part2/addressbook.cpp cancel + + The general idea behind adding a contact is to give the user the + flexibility to click \gui Submit or \gui Cancel at any time. The flowchart below + further explains this concept: + + \image addressbook-tutorial-part2-add-flowchart.png +*/ + +/*! + \page tutorials-addressbook-part3.html + + \example tutorials/addressbook/part3 + \title Part 3 - Navigating between Entries + + The address book is now about half complete. We should add the + capability to navigate among the contacts, but first we must + decide what sort of a data structure we need for containing these + contacts. + + In the previous section, we used a QMap of key-value pairs with + the contact's name as the \e key, and the contact's address as the + \e value. This works well for our case. However, in order to + navigate and display each entry, a little bit of enhancement is + needed. + + We enhance the QMap by making it replicate a data structure similar to a + circularly-linked list, where all elements are connected, including the + first element and the last element. The figure below illustrates this data + structure. + + \image addressbook-tutorial-part3-linkedlist.png + + \section1 Defining the AddressBook Class + + To add navigation functions to the address book, we must add two + more slots to the \c AddressBook class: \c next() and \c + previous() to the \c addressbook.h file: + + \snippet tutorials/addressbook/part3/addressbook.h navigation functions + + We also require another two QPushButton objects, so we declare \c nextButton + and \c previousButton as private variables: + + \snippet tutorials/addressbook/part3/addressbook.h navigation pushbuttons + + \section1 Implementing the AddressBook Class + + In the \c AddressBook constructor in \c addressbook.cpp, we instantiate + \c nextButton and \c previousButton and disable them by default. This is + because navigation is only enabled when there is more than one contact + in the address book. + + \snippet tutorials/addressbook/part3/addressbook.cpp navigation pushbuttons + + We then connect these push buttons to their respective slots: + + \snippet tutorials/addressbook/part3/addressbook.cpp connecting navigation signals + + The image below is the expected graphical user interface. + + \image addressbook-tutorial-part3-screenshot.png + + We follow basic conventions for \c next() and \c previous() functions by + placing the \c nextButton on the right and the \c previousButton on the + left. In order to achieve this intuitive layout, we use QHBoxLayout to + place the widgets side-by-side: + + \snippet tutorials/addressbook/part3/addressbook.cpp navigation layout + + The QHBoxLayout object, \c buttonLayout2, is then added to \c mainLayout. + + \snippet tutorials/addressbook/part3/addressbook.cpp adding navigation layout + + The figure below shows the coordinates of the widgets in \c mainLayout. + \image addressbook-tutorial-part3-labeled-layout.png + + Within our \c addContact() function, we have to disable these buttons so + that the user does not attempt to navigate while adding a contact. + + \snippet tutorials/addressbook/part3/addressbook.cpp disabling navigation + + Also, in our \c submitContact() function, we enable the navigation + buttons, \c nextButton and \c previousButton, depending on the size + of \c contacts. As mentioned earlier, navigation is only enabled when + there is more than one contact in the address book. The following lines + of code demonstrates how to do this: + + \snippet tutorials/addressbook/part3/addressbook.cpp enabling navigation + + We also include these lines of code in the \c cancel() function. + + Recall that we intend to emulate a circularly-linked list with our QMap + object, \c contacts. So, in the \c next() function, we obtain an iterator + for \c contacts and then: + + \list + \o If the iterator is not at the end of \c contacts, we increment it + by one. + \o If the iterator is at the end of \c contacts, we move it to the + beginning of \c contacts. This gives us the illusion that our QMap is + working like a circularly-linked list. + \endlist + + \snippet tutorials/addressbook/part3/addressbook.cpp next() function + + Once we have iterated to the correct object in \c contacts, we display + its contents on \c nameLine and \c addressText. + + Similarly, for the \c previous() function, we obtain an iterator for + \c contacts and then: + + \list + \o If the iterator is at the end of \c contacts, we clear the + display and return. + \o If the iterator is at the beginning of \c contacts, we move it to + the end. + \o We then decrement the iterator by one. + \endlist + + \snippet tutorials/addressbook/part3/addressbook.cpp previous() function + + Again, we display the contents of the current object in \c contacts. + +*/ + +/*! + \page tutorials-addressbook-part4.html + + \example tutorials/addressbook/part4 + \title Part 4 - Editing and Removing Addresses + + Now we look at ways to modify the contents of contacts stored in + the address book. + + \image addressbook-tutorial-screenshot.png + + We now have an address book that not only holds contacts in an + organized manner, but also allows navigation. It would be + convenient to include edit and remove functions so that a + contact's details can be changed when needed. However, this + requires a little improvement, in the form of enums. We defined + two modes: \c{AddingMode} and \c{NavigationMode}, but they were + not defined as enum values. Instead, we enabled and disabled the + corresponding buttons manually, resulting in multiple lines of + repeated code. + + Here we define the \c Mode enum with three different values: + + \list + \o \c{NavigationMode}, + \o \c{AddingMode}, and + \o \c{EditingMode}. + \endlist + + \section1 Defining the AddressBook Class + + The \c addressbook.h file is updated to contain the \c Mode enum: + + \snippet tutorials/addressbook/part4/addressbook.h Mode enum + + We also add two new slots, \c editContact() and \c removeContact(), to + our current list of public slots. + + \snippet tutorials/addressbook/part4/addressbook.h edit and remove slots + + In order to switch between modes, we introduce the \c updateInterface() function + to control the enabling and disabling of all QPushButton objects. We also + add two new push buttons, \c editButton and \c removeButton, for the edit + and remove functions mentioned earlier. + + \snippet tutorials/addressbook/part4/addressbook.h updateInterface() declaration + \dots + \snippet tutorials/addressbook/part4/addressbook.h buttons declaration + \dots + \snippet tutorials/addressbook/part4/addressbook.h mode declaration + + Lastly, we declare \c currentMode to keep track of the enum's current mode. + + \section1 Implementing the AddressBook Class + + We now implement the mode-changing features of the address + book. The \c editButton and \c removeButton are instantiated and + disabled by default. The address book starts with zero contacts + in memory. + + \snippet tutorials/addressbook/part4/addressbook.cpp edit and remove buttons + + These buttons are then connected to their respective slots, \c editContact() + and \c removeContact(), and we add them to \c buttonLayout1. + + \snippet tutorials/addressbook/part4/addressbook.cpp connecting edit and remove + \dots + \snippet tutorials/addressbook/part4/addressbook.cpp adding edit and remove to the layout + + The \c editContact() function stores the contact's old details in + \c oldName and \c oldAddress, before switching the mode to \c EditingMode. + In this mode, the \c submitButton and \c cancelButton are both enabled, + hence, the user can change the contact's details and click either button. + + \snippet tutorials/addressbook/part4/addressbook.cpp editContact() function + + The \c submitContact() function has been divided in two with an \c{if-else} + statement. We check \c currentMode to see if it's in \c AddingMode. If it is, + we proceed with our adding process. + + \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function beginning + \dots + \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part1 + + Otherwise, we check to see if \c currentMode is in \c EditingMode. If it + is, we compare \c oldName with \c name. If the name has changed, we remove + the old contact from \c contacts and insert the newly updated contact. + + \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part2 + + If only the address has changed (i.e., \c oldAddress is not the same as \c address), + we update the contact's address. Lastly, we set \c currentMode to + \c NavigationMode. This is an important step as it re-enables all the + disabled push buttons. + + To remove a contact from the address book, we implement the + \c removeContact() function. This function checks to see if the contact + exists in \c contacts. + + \snippet tutorials/addressbook/part4/addressbook.cpp removeContact() function + + If it does, we display a QMessageBox, to confirm the removal with the + user. Once the user has confirmed, we call \c previous() to ensure that the + user interface shows another contact, and we remove the contact using \l{QMap}'s + \l{QMap::remove()}{remove()} function. As a courtesy, we display a QMessageBox + to inform the user. Both the message boxes used in this function are shown below: + + \image addressbook-tutorial-part4-remove.png + + \section2 Updating the User Interface + + We mentioned the \c updateInterface() function earlier as a means to + enable and disable the push buttons depending on the current mode. + The function updates the current mode according to the \c mode argument + passed to it, assigning it to \c currentMode before checking its value. + + Each of the push buttons is then enabled or disabled, depending on the + current mode. The code for \c AddingMode and \c EditingMode is shown below: + + \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 1 + + For \c NavigationMode, however, we include conditions within the parameters + of the QPushButton::setEnabled() function. This is to ensure that + \c editButton and \c removeButton are enabled when there is at least one + contact in the address book; \c nextButton and \c previousButton are only + enabled when there is more than one contact in the address book. + + \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 2 + + By setting the mode and updating the user interface in the same + function, we avoid the possibility of the user interface getting + out of sync with the internal state of the application. + */ + +/*! + \page tutorials-addressbook-part5.html + + \example tutorials/addressbook/part5 + \title Part 5 - Adding a Find Function + + Here we look at ways to locate contacts and addresses in the + address book. + + \image addressbook-tutorial-part5-screenshot.png + + As we add contacts to our address book, it becomes tedious to + navigate the list with the \e Next and \e Previous buttons. A \e + Find function would be more efficient. The screenshot above shows + the \e Find button and its position on the panel of buttons. + + When the user clicks on the \e Find button, it is useful to + display a dialog that prompts for a contact's name. Qt provides + QDialog, which we subclass here to implement a \c FindDialog + class. + + \section1 Defining the FindDialog Class + + \image addressbook-tutorial-part5-finddialog.png + + In order to subclass QDialog, we first include the header for QDialog in + the \c finddialog.h file. Also, we use forward declaration to declare + QLineEdit and QPushButton since we will be using those widgets in our + dialog class. + + As in our \c AddressBook class, the \c FindDialog class includes + the Q_OBJECT macro and its constructor is defined to accept a parent + QWidget, even though the dialog will be opened as a separate window. + + \snippet tutorials/addressbook/part5/finddialog.h FindDialog header + + We define a public function, \c getFindText(), to be used by classes that + instantiate \c FindDialog. This function allows these classes to obtain the + search string entered by the user. A public slot, \c findClicked(), is also + defined to handle the search string when the user clicks the \gui Find + button. + + Lastly, we define the private variables, \c findButton, \c lineEdit + and \c findText, corresponding to the \gui Find button, the line edit + into which the user types the search string, and an internal string + used to store the search string for later use. + + \section1 Implementing the FindDialog Class + + Within the constructor of \c FindDialog, we set up the private variables, + \c lineEdit, \c findButton and \c findText. We use a QHBoxLayout to + position the widgets. + + \snippet tutorials/addressbook/part5/finddialog.cpp constructor + + We set the layout and window title, as well as connect the signals to their + respective slots. Notice that \c{findButton}'s \l{QPushButton::clicked()} + {clicked()} signal is connected to to \c findClicked() and + \l{QDialog::accept()}{accept()}. The \l{QDialog::accept()}{accept()} slot + provided by QDialog hides the dialog and sets the result code to + \l{QDialog::}{Accepted}. We use this function to help \c{AddressBook}'s + \c findContact() function know when the \c FindDialog object has been + closed. We will explain this logic in further detail when discussing the + \c findContact() function. + + \image addressbook-tutorial-part5-signals-and-slots.png + + In \c findClicked(), we validate \c lineEdit to ensure that the user + did not click the \gui Find button without entering a contact's name. Then, we set + \c findText to the search string, extracted from \c lineEdit. After that, + we clear the contents of \c lineEdit and hide the dialog. + + \snippet tutorials/addressbook/part5/finddialog.cpp findClicked() function + + The \c findText variable has a public getter function, \c getFindText(), + associated with it. Since we only ever set \c findText directly in both the + constructor and in the \c findClicked() function, we do not create a + setter function to accompany \c getFindText(). + Because \c getFindText() is public, classes instantiating and using + \c FindDialog can always access the search string that the user has + entered and accepted. + + \snippet tutorials/addressbook/part5/finddialog.cpp getFindText() function + + \section1 Defining the AddressBook Class + + To ensure we can use \c FindDialog from within our \c AddressBook class, we + include \c finddialog.h in the \c addressbook.h file. + + \snippet tutorials/addressbook/part5/addressbook.h include finddialog's header + + So far, all our address book features have a QPushButton and a + corresponding slot. Similarly, for the \gui Find feature we have + \c findButton and \c findContact(). + + The \c findButton is declared as a private variable and the + \c findContact() function is declared as a public slot. + + \snippet tutorials/addressbook/part5/addressbook.h findContact() declaration + \dots + \snippet tutorials/addressbook/part5/addressbook.h findButton declaration + + Lastly, we declare the private variable, \c dialog, which we will use to + refer to an instance of \c FindDialog. + + \snippet tutorials/addressbook/part5/addressbook.h FindDialog declaration + + Once we have instantiated a dialog, we will want to use it more than once; + using a private variable allows us to refer to it from more than one place + in the class. + + \section1 Implementing the AddressBook Class + + Within the \c AddressBook class's constructor, we instantiate our private + objects, \c findButton and \c findDialog: + + \snippet tutorials/addressbook/part5/addressbook.cpp instantiating findButton + \dots + \snippet tutorials/addressbook/part5/addressbook.cpp instantiating FindDialog + + Next, we connect the \c{findButton}'s + \l{QPushButton::clicked()}{clicked()} signal to \c findContact(). + + \snippet tutorials/addressbook/part5/addressbook.cpp signals and slots for find + + Now all that is left is the code for our \c findContact() function: + + \snippet tutorials/addressbook/part5/addressbook.cpp findContact() function + + We start out by displaying the \c FindDialog instance, \c dialog. This is + when the user enters a contact name to look up. Once the user clicks + the dialog's \c findButton, the dialog is hidden and the result code is + set to QDialog::Accepted. This ensures that + our \c if statement is always true. + + We then proceed to extract the search string, which in this case is + \c contactName, using \c{FindDialog}'s \c getFindText() function. If the + contact exists in our address book, we display it immediately. Otherwise, + we display the QMessageBox shown below to indicate that their search + failed. + + \image addressbook-tutorial-part5-notfound.png +*/ + +/*! + \page tutorials-addressbook-part6.html + + \example tutorials/addressbook/part6 + \title Part 6 - Loading and Saving + + This part covers the Qt file handling features we use to write + loading and saving routines for the address book. + + \image addressbook-tutorial-part6-screenshot.png + + Although browsing and searching the contact list are useful + features, our address book is not complete until we can save + existing contacts and load them again at a later time. + + Qt provides a number of classes for \l{Input/Output and Networking} + {input and output}, but we have chosen to use two which are simple to use + in combination: QFile and QDataStream. + + A QFile object represents a file on disk that can be read from and written + to. QFile is a subclass of the more general QIODevice class which + represents many different kinds of devices. + + A QDataStream object is used to serialize binary data so that it can be + stored in a QIODevice and retrieved again later. Reading from a QIODevice + and writing to it is as simple as opening the stream - with the respective + device as a parameter - and reading from or writing to it. + + + \section1 Defining the AddressBook Class + + We declare two public slots, \c saveToFile() and \c loadFromFile(), as well + as two QPushButton objects, \c loadButton and \c saveButton. + + \snippet tutorials/addressbook/part6/addressbook.h save and load functions declaration + \dots + \snippet tutorials/addressbook/part6/addressbook.h save and load buttons declaration + + \section1 Implementing the AddressBook Class + + In our constructor, we instantiate \c loadButton and \c saveButton. + Ideally, it would be more user-friendly to set the push buttons' labels + to "Load contacts from a file" and "Save contacts to a file". However, due + to the size of our other push buttons, we set the labels to \gui{Load...} + and \gui{Save...}. Fortunately, Qt provides a simple way to set tooltips with + \l{QWidget::setToolTip()}{setToolTip()} and we use it in the following way + for our push buttons: + + \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 1 + \dots + \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 2 + + Although it is not shown here, just like the other features we implemented, + we add the push buttons to the layout panel on the right, \c buttonLayout1, + and we connect the push buttons' \l{QPushButton::clicked()}{clicked()} + signals to their respective slots. + + For the saving feature, we first obtain \c fileName using + QFileDialog::getSaveFileName(). This is a convenience function provided + by QFileDialog, which pops up a modal file dialog and allows the user to + enter a file name or select any existing \c{.abk} file. The \c{.abk} file + is our Address Book extension that we create when we save contacts. + + \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part1 + + The file dialog that pops up is displayed in the screenshot below: + + \image addressbook-tutorial-part6-save.png + + If \c fileName is not empty, we create a QFile object, \c file, with + \c fileName. QFile works with QDataStream as QFile is a QIODevice. + + Next, we attempt to open the file in \l{QIODevice::}{WriteOnly} mode. + If this is unsuccessful, we display a QMessageBox to inform the user. + + \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part2 + + Otherwise, we instantiate a QDataStream object, \c out, to write the open + file. QDataStream requires that the same version of the stream is used + for reading and writing. We ensure that this is the case by setting the + version used to the \l{QDataStream::Qt_4_5}{version introduced with Qt 4.5} + before serializing the data to \c file. + + \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part3 + + For the loading feature, we also obtain \c fileName using + QFileDialog::getOpenFileName(). This function, the counterpart to + QFileDialog::getSaveFileName(), also pops up the modal file dialog and + allows the user to enter a file name or select any existing \c{.abk} file + to load it into the address book. + + \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part1 + + On Windows, for example, this function pops up a native file dialog, as + shown in the following screenshot. + + \image addressbook-tutorial-part6-load.png + + If \c fileName is not empty, again, we use a QFile object, \c file, and + attempt to open it in \l{QIODevice::}{ReadOnly} mode. Similar to our + implementation of \c saveToFile(), if this attempt is unsuccessful, we + display a QMessageBox to inform the user. + + \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part2 + + Otherwise, we instantiate a QDataStream object, \c in, set its version as + above and read the serialized data into the \c contacts data structure. + The \c contacts object is emptied before data is read into it to simplify + the file reading process. A more advanced method would be to read the + contacts into a temporary QMap object, and copy over non-duplicate contacts + into \c contacts. + + \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part3 + + To display the contacts that have been read from the file, we must first + validate the data obtained to ensure that the file we read from actually + contains address book contacts. If it does, we display the first contact; + otherwise, we display a QMessageBox to inform the user about the problem. + Lastly, we update the interface to enable and disable the push buttons + accordingly. +*/ + +/*! + \page tutorials-addressbook-part7.html + + \example tutorials/addressbook/part7 + \title Part 7 - Additional Features + + This part covers some additional features that make the address + book more convenient for the frequent user. + + \image addressbook-tutorial-part7-screenshot.png + + Although our address book is useful in isolation, it would be + better if we could exchange contact data with other applications. + The vCard format is a popular file format that can be used for + this purpose. Here we extend our address book client to allow + contacts to be exported to vCard \c{.vcf} files. + + \section1 Defining the AddressBook Class + + We add a QPushButton object, \c exportButton, and a corresponding public + slot, \c exportAsVCard() to our \c AddressBook class in the + \c addressbook.h file. + + \snippet tutorials/addressbook/part7/addressbook.h exportAsVCard() declaration + \dots + \snippet tutorials/addressbook/part7/addressbook.h exportButton declaration + + \section1 Implementing the AddressBook Class + + Within the \c AddressBook constructor, we connect \c{exportButton}'s + \l{QPushButton::clicked()}{clicked()} signal to \c exportAsVCard(). + We also add this button to our \c buttonLayout1, the layout responsible + for our panel of buttons on the right. + + In our \c exportAsVCard() function, we start by extracting the contact's + name into \c name. We declare \c firstName, \c lastName and \c nameList. + Next, we look for the index of the first white space in \c name. If there + is a white space, we split the contact's name into \c firstName and + \c lastName. Then, we replace the space with an underscore ("_"). + Alternately, if there is no white space, we assume that the contact only + has a first name. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part1 + + As with the \c saveToFile() function, we open a file dialog to let the user + choose a location for the file. Using the file name chosen, we create an + instance of QFile to write to. + + We attempt to open the file in \l{QIODevice::}{WriteOnly} mode. If this + process fails, we display a QMessageBox to inform the user about the + problem and return. Otherwise, we pass the file as a parameter to a + QTextStream object, \c out. Like QDataStream, the QTextStream class + provides functionality to read and write plain text to files. As a result, + the \c{.vcf} file generated can be opened for editing in a text editor. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part2 + + We then write out a vCard file with the \c{BEGIN:VCARD} tag, followed by + the \c{VERSION:2.1} tag. The contact's name is written with the \c{N:} + tag. For the \c{FN:} tag, which fills in the "File as" property of a vCard, + we have to check whether the contact has a last name or not. If the contact + does, we use the details in \c nameList to fill it. Otherwise, we write + \c firstName only. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part3 + + We proceed to write the contact's address. The semicolons in the address + are escaped with "\\", the newlines are replaced with semicolons, and the + commas are replaced with spaces. Lastly, we write the \c{ADR;HOME:;} + tag, followed by \c address and then the \c{END:VCARD} tag. + + \snippet tutorials/addressbook/part7/addressbook.cpp export function part4 + + In the end, a QMessageBox is displayed to inform the user that the vCard + has been successfully exported. + + \e{vCard is a trademark of the \l{http://www.imc.org} + {Internet Mail Consortium}}. +*/ diff --git a/doc/src/widgets/modelview.qdoc b/doc/src/widgets/modelview.qdoc new file mode 100644 index 0000000000..9cbba47b60 --- /dev/null +++ b/doc/src/widgets/modelview.qdoc @@ -0,0 +1,897 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page modelview.html + \ingroup tutorials + \startpage {index.html}{Qt Reference Documentation} + + \title Model/View Tutorial + \brief An introduction to ModelView programming + + Every UI developer should know about ModelView programming and the goal of + this tutorial is to provide you with an easily understandable introduction + to this topic. + + Table, list and tree widgets are components frequently used in GUIs. There + are 2 different ways how these widgets can access their data. The + traditional way involves widgets which include internal containers for + storing data. This approach is very intuitive, however, in many non-trivial + applications, it leads to data synchronization issues. + The second approach is model/view programming, in + which widgets do not maintain internal data containers. They access external + data through a standardized interface and therefore avoid data duplication. + This may seem complicated at first, but once you take a closer look, it is + not only easy to grasp, but the many benefits of model/view programming also + become clearer. + + \image treeview.png + + In the process, we will learn about some basic technologies provided by Qt, + such as: + + \list + \o The difference between standard and model/view widgets + \o Adapters betweeen forms and models + \o Developing a simple model/view application + \o Predefined models + \o Intermediate topics such as: + \list + \o Tree views + \o Selection + \o Delegates + \o Debugging with model test + \endlist + \endlist + + You will also learn whether your new application can be written easier with + model/view programming or if classic widgets will work just as well. + + This tutorial includes example code for you to edit and integrate into your + project. The tutorial's source code is located in Qt's + \c examples/tutorials/modelview directory. + + For more detailed information you may also want to look at the + \l{model-view-programming.html}{reference documentation} + + If you are completely new to Qt, please read \l{How to Learn Qt} if you + have not already done so. + + + \section1 1. Introduction + + Model/View is a technology used to separate data from views in widgets that + handle data sets. Standard widgets are not designed for separating data + from views and this is why Qt 4 has two different types of widgets. Both + types of widgets look the same, but they interact with data differently. + + \table + \row + \o Standard widgets use data that is part of the widget. + \o \image standardwidget.png + \row + \o View classes operate on external data (the model) + \o \image modelview.png + \endtable + + \section2 1.1 Standard Widgets + + Let's have a closer look at a standard table widget. A table widget is a 2D + array of the data elements that the user can change. The table widget can be + integrated into a program flow by reading and writing the data elements that + the table widget provides. + This method is very intuitive and useful in many applications, but displaying + and editing a database table with a standard table widget can be problematic. + Two copies of the data have to be coordinated: one outside the + widget; one inside the widget. The developer is responsible for + synchronizing both versions. Besides this, the tight coupling of presentation and data + makes it harder to write unit tests. + + \section2 1.2 Model/View to the Rescue + + Model/view stepped up to provide a solution that uses a more versatile + architecture. Model/view eliminates the data consistency problems that may + occur with standard widgets. Model/view also makes it easier to use more + than one view of the same data because one model can be passed on to many + views. The most important difference is that model/view widgets do not store + data behind the table cells. In fact, they operate directly from your data. + Since view classes do not know your data's structure, you need to provide a + wrapper to make your data conform to the QAbstractItemModel interface. A + view uses this interface to read from and write to your data. Any instance + of a class that implements QAbstractItemModel is said to be a model. Once + the view receives a pointer to a model, it will read and display its content + and be its editor. + + \section2 1.3 Overview of the Model/View Widgets + + Here is an overview of the model/view widgets and their corresponding + standard widgets. + + \table + \header + \o Widget + \o Standard Widget\br + (an item based convenience class) + \o Model/View View Class\br + (for use with external data) + \row + \o \inlineimage listview.png + \o \l QListWidget + \o \l QListView + \row + \o \inlineimage tableview.png + \o \l QTableWidget + \o \l QTableView + \row + \o \inlineimage treeview.png + \o \l QTreeWidget + \o \l QTreeView + \row + \o \inlineimage columnview.png + \o + \o \l QColumnView shows a tree as a hierarchy of lists + \row + \o \inlineimage modelview-combobox.png + \o {2, 1} \l QComboBox can work as both a view class and also + as a traditional widget + \endtable + + \section2 1.4 Using Adapters between Forms and Models + + Having adapters between forms and models can come in handy. + + We can edit data stored in tables directly from within the table itself, but + it's much more comfortable to edit data in text fields. There is no direct + model/view counterpart that separates data and views for widgets that + operate on one value (QLineEdit, QCheckBox ...) instead of a dataset, so we + need an adapter in order to connect the form to the source of data. + + \l QDataWidgetMapper is a great solution because it maps form widgets to a + table row and makes it very easy to build forms for database tables. + + \image widgetmapper.png + + Another example of an adapter is \l QCompleter. Qt has \l QCompleter for + providing auto-completions in Qt widgets such as \l QComboBox and, as shown + below, \l QLineEdit. \l QCompleter uses a model as its data source. + + \image qcompleter.png + + + \section1 2. A Simple Model/View Application + If you want to develop a model/view application, where should you start? + We recommend starting with a simple example and extending it step-by-step. + This makes understanding the architecture a lot easier. Trying to understand + the model/view architecture in detail before invoking the IDE has proven + to be less convenient for many developers. It is substantially easier to + start with a simple model/view application that has demo data. Give it a + try! Simply replace the data in the examples below with your own. + + Below are 7 very simple and independent applications that show different + sides of model/view programming. The source code can be found inside the + \c{examples/tutorials/modelview} directory. + + \section2 2.1 A Read Only Table + + We start with an application that uses a QTableView to show data. We will + add editing capabilities later. + + (file source: examples/tutorials/modelview/1_readonly/main.cpp) + \snippet examples/tutorials/modelview/1_readonly/main.cpp Quoting ModelView Tutorial + + We have the usual \l {modelview-part2-main-cpp.html}{main()} function: + + Here is the interesting part: We create an instance of MyModel and use + \l{QTableView::setModel()}{tableView.setModel(&myModel);} to pass a + pointer of it to to \l{QTableView}{tableView}. \l{QTableView}{tableView} + will invoke the methods of the pointer it has received to find out two + things: + + \list + \o How many rows and columns should be displayed. + \o What content should be printed into each cell. + \endlist + + The model needs some code to respond to this. + + We have a table data set, so let's start with QAbstractTableModel since it + is easier to use than the more general QAbstractItemModel. + + (file source: examples/tutorials/modelview/1_readonly/mymodel.h) + \snippet examples/tutorials/modelview/1_readonly/mymodel.h Quoting ModelView Tutorial + + QAbstractTableModel requires the implementation of three abstract methods. + + (file source: examples/tutorials/modelview/1_readonly/mymodel.cpp) + \snippet examples/tutorials/modelview/1_readonly/mymodel.cpp Quoting ModelView Tutorial + + The number of rows and columns is provided by + \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and + \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. When the view + has to know what the cell's text is, it calls the method + \l{QAbstractItemModel::data()}{MyModel::data()}. Row and column information + is specified with parameter \c index and the role is set to + \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are covered in the next + section. In our example, the data that should be displayed is generated. In + a real application, \c MyModel would have a member called \c MyData, which + serves as the target for all reading and writing operations. + + This small example demonstrates the passive nature of a model. The model + does not know when it will be used or which data is needed. It simply + provides data each time the view requests it. + + What happens when the model's data needs to be changed? How does the view + realize that data has changed and needs to be read again? The model has to + emit a signal that indicates what range of cells has changed. This will be + demonstrated in section 2.3. + + \section2 2.2 Extending the Read Only Example with Roles + + In addition to controlling what text the view displays, the model also + controls the text's appearance. When we slightly change the model, we get + the following result: \image readonlytable_role.png + + In fact, nothing except for the \l{QAbstractItemModel::}{data()} method + needs to be changed to set fonts, background colour, alignment and a + checkbox. + Below is the \l{QAbstractItemModel::data()}{data()} method that produces the + result shown above. The difference is that this time we use parameter int + role to return different pieces of information depending on its value. + + (file source: examples/tutorials/modelview/2_formatting/mymodel.cpp) + \snippet examples/tutorials/modelview/2_formatting/mymodel.cpp Quoting ModelView Tutorial + + Each formatting property will be requested from the model with a separate + call to the \l{QAbstractItemModel::data()}{data()} method. The \c role + parameter is used to let the model know which property is being requested: + + \table + \header + \o \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} + \o Meaning + \o Type + \row + \o \l{Qt::ItemDataRole}{}Qt::DisplayRole + \o text + \o QString + \row + \o \l{Qt::ItemDataRole}{Qt::FontRole} + \o font + \o QFont + \row + \o \l{Qt::ItemDataRole}{BackgroundRole} + \o brush for the background of the cell + \o QBrush + \row + \o \l{Qt::ItemDataRole}{Qt::TextAlignmentRole} + \o text alignment + \o \l{Qt::AlignmentFlag}{enum Qt::AlignmentFlag} + \row + \o {1, 3} \l{Qt::ItemDataRole}{Qt::CheckStateRole} + \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()}, + + sets checkboxes with \l{Qt::CheckState}{Qt::Checked} + + or \l{Qt::CheckState}{Qt::Unchecked} + \o {1, 3} \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} + \endtable + + Refer to the Qt namespace documentation to learn more about the + \l{Qt::ItemDataRole}{Qt::ItemDataRole} enum's capabilities. + + Now we need to determine how using a separated model impacts the + application's performance, so let's trace how often the view calls the + \l{QAbstractItemModel::}{data()} method. In order to track how often the + view calls the model, we have put a debug statement in the + \l{QAbstractItemModel::}{data()} method, which logs onto the error output + stream. In our small example, \l{QAbstractItemModel::}{data()} will be + called 42 times. + Each time you hover the cursor over the field, + \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for + each cell. That's why it is important to make sure that your data is + available when \l{QAbstractItemModel::}{data()} is invoked and expensive + lookup operations are cached. + + \section2 2.3 A Clock inside a Table Cell + + \image clock.png + + We still have a read only table, but this time the content changes every + second because we are showing the current time. + + (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) + \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_QVariant + + Something is missing to make the clock tick. We need to tell the view every + second that the time has changed and that it needs to be read again. We do + this with a timer. In the constructor, we set its interval to 1 second and + connect its timeout signal. + + (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) + \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_a + + Here is the corresponding slot: + + (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) + \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_b + + We ask the view to read the data in the top left cell again by emitting the + \l{QAbstractItemModel::}{dataChanged()} signal. Note that we did not + explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to the + view. This happened automatically when we called \l{QTableView::}{setModel()}. + + \section2 2.4 Setting up Headers for Columns and Rows + + Headers can be hidden via a view method: \c{tableView->verticalHeader()->hide();} + \image modelview-header.png + + The header content, however, is set via the model, so we reimplement the + \l{QAbstractItemModel::headerData()}{headerData()} method: + + (file source: examples/tutorials/modelview/4_headers/mymodel.cpp) + \snippet examples/tutorials/modelview/4_headers/mymodel.cpp quoting mymodel_c + + Note that method \l{QAbstractItemModel::headerData()}{headerData()} also has + a parameter role which has the same meaning as in + \l{QAbstractItemModel::data()}{MyModel::data()}. + + \section2 2.5 The Minimal Editing Example + + In this example, we are going to build an application that automatically + populates a window title with content by repeating values entered into table + cells. To be able to access the window title easily we put the QTableView in + a QMainWindow. + + The model decides whether editing capabilities are available. We only have + to modify the model in order for the available editing capabilities to be + enabled. This is done by reimplementing the following virtual methods: + \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}. + + (file source: examples/tutorials/modelview/5_edit/mymodel.h) + \snippet examples/tutorials/modelview/5_edit/mymodel.h Quoting ModelView Tutorial + + We use \c the two-dimensional array QString \c m_gridData to store our data. + This makes \c m_gridData the core of \c MyModel. The rest of \c MyModel acts + like a wrapper and adapts \c m_gridData to the QAbstractItemModel + interface. We have also introduced the \c editCompleted() signal, which + makes it possible to transfer the modified text to the window title. + + (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) + \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_e + + \l{QAbstractItemModel::setData()}{setData()} will be called each time the + user edits a cell. The \c index parameter tells us which field has been + edited and \c value provides the result of the editing process. The role + will always be set to \l Qt::EditRole because our cells only contain text. + If a checkbox were present and user permissions are set to allow the + checkbox to be selected, calls would also be made with the role set to + \l Qt::CheckStateRole. + + (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) + \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_f + + Various properties of a cell can be adjusted with + \l{QAbstractItemModel::flags()}{flags()}. + + Returning \l{Qt::ItemFlag}{Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled} + is enough to show an editor that a cell can be selected. + + If editing one cell modifies more data than the data in that particular + cell, the model must emit a \l{QAbstractItemModel::}{dataChanged()} signal + in order for the data that has been changed to be read. + + + \section1 3. Intermediate Topics + + \section2 3.1 TreeView + + You can convert the example above into an application with a tree view. + Simply replace QTableView with QTreeView, which results in a read/write + tree. No changes have to be made to the model. The tree won't have any + hierarchies because there aren't any hierarchies in the model itself. + + \image dummy_tree.png + + QListView, QTableView and QTreeView all use a model abstraction, which is a + merged list, table and tree. This makes it possible to use several different + types of view classes from the same model. + + \image list_table_tree.png + + This is how our example model looks so far: + + \image example_model.png + + We want to present a real tree. We have wrapped our data in the examples + above in order to make a model. This time we use QStandardItemModel, which + is a container for hierarchical data that also implements + QAbstractItemModel. To show a tree, QStandardItemModel must be populated + with \l{QStandardItem}s, which are able to hold all the standard properties + of items like text, fonts, checkboxes or brushes. + + \image tree_2_with_algorithm.png + + (file source: examples/tutorials/modelview/6_treeview/mainwindow.cpp) + \snippet examples/tutorials/modelview/6_treeview/mainwindow.cpp Quoting ModelView Tutorial + + We simply instantiate a QStandardItemModel and add a couple of + \l{QStandardItem}{QStandardItems} to the constructor. We can then make a + hierarchical data structure because a QStandardItem can hold other + \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within + the view. + + \section2 3.2 Working with Selections + + We want to access a selected item's content in order to output it into the + window title together with the hierarchy level. + + \image selection2.png + + So let's create a couple of items: + + (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) + \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_a + + Views manage selections within a separate selection model, which can be + retrieved with the \l{QAbstractItemView::}{selectionModel()} method. We + retrieve the selection Model in order to connect a slot to its + \l{QAbstractItemView::}{selectionChanged()} signal. + + (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) + \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_b + + We get the model index that corresponds to the selection by calling + \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()} + and we get the the field's string by using the model index. Then we just + calculate the item's \c hierarchyLevel. Top level items do not have parents + and the \l{QAbstractItemModel::}{parent()} method will return a default + constructed \l{QModelIndex}{QModelIndex()}. This is why we use the + \l{QAbstractItemModel::}{parent()} method to iterate to the top level while + counting the steps performed during iteration. + + The selection model (as shown above) can be retrieved, but it can also be + set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This + is how it's possible to have 3 view classes with synchronised selections + because only one instance of a selection model is used. To share a selection + model between 3 views use \l{QAbstractItemView::}{selectionModel()} and + assign the result to the second and third view class with + \l{QAbstractItemView::}{setSelectionModel()}. + + \section2 3.3 Predefined Models + + The typical way to use model/view is to wrap specific data to make it usable + with view classes. Qt, however, also provides predefined models for common + underlying data structures. If one of the available data structures is + suitable for your application, a predefined model can be a good choice. + + \table + \row + \o QStringListModel + \o Stores a list of strings + \row + \o QStandardItemModel + \o Stores arbitrary hierarchical items + \row + \o QFileSystemModel\br + QDirModel + \o Encapsulate the local file system + \row + \o QSqlQueryModel + \o Encapsulate an SQL result set + \row + \o QSqlTableModel + \o Encapsulates an SQL table + \row + \o QSqlRelationalTableModel + \o Encapsulates an SQL table with foreign keys + \row + \o QSortFilterProxyModel + \o Sorts and/or filters another model + + \endtable + + \section2 3.4 Delegates + + In all examples so far, data is presented as text or a checkbox in a cell + and is edited as text or a checkbox. The component that provides these + presentation and editing services is called a \e delegate. We are only just + beginning to work with the delegate because the view uses a default + delegate. But imagine that we want to have a different editor (e.g., a + slider or a drop down list) Or imagine that we want to present data as + graphics. + Let's take a look at an example called \l{Star Delegate Example}{Star + Delegate}, in which stars are used to show a rating: + + \image stardelegate.png + + The view has a \l{QAbstractItemView::}{setItemDelegate()} method that + replaces the default delegate and installs a custom delegate. + A new delegate can be written by creating a class that inherits from + QStyledItemDelegate. In order to write a delegate that displays stars and + has no input capabilities, we only need to override 2 methods. + + \code + class StarDelegate : public QStyledItemDelegate + { + Q_OBJECT + public: + StarDelegate(QWidget *parent = 0); + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + QSize sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const; + }; + \endcode + + \l{QStyledItemDelegate::}{paint()} draws stars depending on the content of + the underlying data. The data can be looked up by calling + \l{QModelIndex::data()}{index.data()}. The delegate's + \l{QAbstractItemDelegate::}{sizeHint()} method is used to obtain each + star's dimensions, so the the cell will provide enough height and width to + accommodate the stars. + + Writing custom delegates is the right choice if you want to show your data + with a custom graphical representation inside the grid of the view class. If + you want to leave the grid, you would not use a custom delegate but a custom + view class. + + Other references to delegates in Qt Documentation: + + \list + \o \l{Spin Box Delegate Example} + \o \l{QAbstractItemDelegate}{QAbstractItemDelegate Class Reference} + \o \l{QSqlRelationalDelegate}{QSqlRelationalDelegate Class Reference} + \o \l{QStyledItemDelegate}{QStyledItemDelegate Class Reference} + \o \l{QItemDelegate}{QItemDelegate Class Reference} + \endlist + + + \section2 3.5 Debugging with ModelTest + + The passive nature of models provides new challenges for programmers. + Inconsistencies in the model can cause the application to crash. Since the + model is hit by numerous calls from the view, it is hard to find out which + call has crashed the application and which operation has introduced the + problem. + + Qt Labs provides software called + \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest}, + which checks models while your programming is running. Every time the model + is changed, ModelTest scans the model and reports errors with an assert. + This is especially important for tree models, since their hierarchical + nature leaves many possibilities for subtle inconsistencies. + + Unlike view classes, ModelTest uses out of range indexes to test the model. + This means your application may crash with ModelTest even if it runs + perfectly without it. So you also need to handle all of the indexes that are + out of range when using ModelTest. + + + \section1 4. Good Sources of Additional Information + + \section2 4.1 Books + + Model/View programming is covered quite extensively in the documentation of + Qt but also in several good books. + + \list 1 + \o \bold{C++ GUI Programming with Qt 4} / Jasmin Blanchette, Mark Summerfield, + \e{Prentice Hall, 2nd edition}, ISBN 0-13-235416-0. Also available in + German: \bold{C++ GUI Programmierung mit Qt 4: Die offizielle Einführung}, + \e{Addison-Wesley}, ISBN 3-827327-29-6 + \o \bold{The Book of Qt4, The Art of Building Qt Applications} / Daniel Molkentin, + \e{Open Source Press}, ISBN 1-59327-147-6. + Translated from \bold{Qt 4, Einführung in die Applikationsentwicklung}, + \e{Open Source Press}, ISBN 3-937514-12-0. + \o \bold{Foundations of Qt Development} / Johan Thelin, \e{Apress}, ISBN 1-59059-831-8. + \o \bold{Advanced Qt Programming} / Mark Summerfield, \e{Prentice Hall}, ISBN 0-321-63590-6. + This book covers Model/View programming on more than 150 pages. + \endlist + + More information about these books is available on the + \l{Books about Qt Programming}{Qt Web site}. + + The following list provides an overview of example programs contained in the first three + books listed above. Some of them make very good templates for developing similar + applications. + + \table + \header + \o Example name + \o View class used + \o Model used + \o Aspects covered + \o + \row + \o Team Leaders + \o QListview + \o QStringListModel + \o + \o Book 1, Chapter 10, Figure 10.6 + \row + \o Directory Viewer + \o QTreeView + \o QDirModel + \o + \o Book 1, Chapter 10, Figure 10.7 + \row + \o Color Names + \o QListView + \o QSortFilterProxyModel + applied to QStringListModel + \o + \o Book 1, Chapter 10, Figure 10.8 + \row + \o Currencies + \o QTableView + \o custom model based on + QAbstractTableModel + \o Read only + \o Book 1, Chapter 10, Figure 10.10 + \row + \o Cities + \o QTableView + \o Custom model based on + QAbstractTableModel + \o Read / write + \o Book 1, Chapter 10, Figure 10.12 + \row + \o Boolean Parser + \o QTreeView + \o Custom model based on + QAbstractItemModel + \o Read only + \o Book 1, Chapter 10, Figure 10.14 + \row + \o Track Editor + \o {2, 1} QTableWidget + \o Custom delegate providing a custom editor + \o Book 1, Chapter 10, Figure 10.15 + + \row + \o Four directory views + \o QListView + QTableView + QTreeView + \o QDirModel + \o Demonstrates the use of multiple views + \o Book2, Chapter 8.2 + \row + \o Address Book + \o QListView + QTableView + QTreeView + \o Custom model based on + QAbstractTableModel + \o Read / write + \o Book2, Chapter 8.4 + \row + \o Address Book with sorting + \o + \o QProxyModel + \o Introducing sort and filter capabilities + \o Book2, Chapter 8.5 + \row + \o Address Book + with checkboxes + \o + \o + \o Introducing checkboxes in model/view + \o Book2, Chapter 8.6 + \row + \o Address Book with transposed grid + \o + \o Custom proxy Model based on QAbstractProxyModel + \o Introducing a custom model + \o Book2, Chapter 8.7 + \row + \o Address Book with drag and drop + \o + \o + \o Introducing drag and drop support + \o Book2, Chapter 8.8 + \row + \o Address Book with custom editor + \o + \o + \o Introducing custom delegates + \o Book2, Chapter 8.9 + \row + \o Views + \o QListView + QTableView + QTreeView + \o QStandardItemModel + \o Read only + \o Book 3, Chapter 5, figure 5-3 + \row + \o Bardelegate + \o QTableView + \o + \o Custom delegate for presentation based on QAbstractItemDelegate + \o Book 3, Chapter 5, figure 5-5 + \row + \o Editdelegate + \o QTableView + \o + \o Custom delegate for editing based on QAbstractItemDelegate + \o Book 3, Chapter 5, figure 5-6 + \row + \o Singleitemview + \o Custom view based on QAbstractItemView + \o + \o Custom view + \o Book 3, + Chapter 5, + figure 5-7 + \row + \o listmodel + \o QTableView + \o Custom Model based on QAbstractTableModel + \o Read only + \o Book 3, Chapter 5, Figure 5-8 + \row + \o treemodel + \o QTreeView + \o Custom Model based on QAbstractItemModel + \o Read only + \o Book 3, Chapter 5, Figure 5-10 + \row + \o edit integers + \o QListView + \o Custom Model based on QAbstractListModel + \o Read / write + \o Book 3, Chapter 5, Listing 5-37, Figure 5-11 + \row + \o sorting + \o QTableView + \o QSortFilterProxyModel applied to QStringListModel + \o Demonstrates sorting + \o Book 3, Chapter 5, Figure 5-12 + \endtable + + + \section2 4.2 Qt Documentation + + Qt 5.0 comes with 19 examples for model/view. + The examples can be found on the \l{Item Views Examples} page. + + \table + \header + \o Example name + \o View class used + \o Model used + \o Aspects covered + \row + \o Address Book + \o QTableView + \o QAbstractTableModel + QSortFilterProxyModel + \o Usage of QSortFilterProxyModel to generate different + subsets from one data pool + \row + \o Basic Sort/Filter Model + \o QTreeView + \o QStandardItemModel + QSortFilterProxyModel + \o + \row + \o Chart + \o Custom view + \o QStandardItemModel + \o Designing custom views that cooperate with selection models + \row + \o Color Editor Factory + \o {2, 1} QTableWidget + \o Enhancing the standard delegate with a new custom editor to choose colours + \row + \o Combo Widget Mapper + \o QDataWidgetMapper to map QLineEdit, QTextEdit and QComboBox + \o QStandardItemModel + \o Shows how a QComboBox can serve as a view class + \row + \o Custom Sort/Filter Model + \o QTreeView + \o QStandardItemModel + QSortFilterProxyModel + \o Subclass QSortFilterProxyModel for advanced sorting and filtering + \row + \o Dir View + \o QTreeView + \o QDirModel + \o Very small example to demonstrate how to assign a model to a view + \row + \o Editable Tree Model + \o QTreeView + \o Custom tree model + \o Comprehensive example for working with trees, demonstrates + editing cells and tree structure with an underlying custom + model + \row + \o Fetch More + \o QListView + \o Custom list model + \o Dynamically changing model + \row + \o Frozen Column + \o QTableView + \o QStandardItemModel + \o + \row + \o Interview + \o Multiple + \o Custom item model + \o Multiple views + \row + \o Pixelator + \o QTableView + \o Custom table model + \o Implementation of a custom delegate + \row + \o Puzzle + \o QListView + \o Custom list model + \o Model/view with drag and drop + \row + \o Simple DOM Model + \o QTreeView + \o Custom tree model + \o Read only example for a custom tree model + \row + \o Simple Tree Model + \o QTreeView + \o Custom tree model + \o Read only example for a custom tree model + \row + \o Simple Widget Mapper + \o QDataWidgetMapper to map QLineEdit, QTextEdit and QSpinBox + \o QStandardItemModel + \o Basic QDataWidgetMapper usage + \row + \o Spin Box Delegate + \o QTableView + \o QStandardItemModel + \o Custom delegate that uses a spin box as a cell editor + \row + \o Spreadsheet + \o {2, 1} QTableView + \o Custom delegates + \row + \o Star Delegate + \o {2, 1} QTableWidget + \o Comprehensive custom delegate example. + \endtable + + A \l{Model/View Programming}{reference document} for model/view technology + is also available. +*/ + +/*! + \page modelview-part2-main-cpp.html + \title main.cpp + \quotefile tutorials/modelview/1_readonly/main.cpp +*/ diff --git a/doc/src/widgets/qtwidgets.qdoc b/doc/src/widgets/qtwidgets.qdoc new file mode 100644 index 0000000000..05062b52db --- /dev/null +++ b/doc/src/widgets/qtwidgets.qdoc @@ -0,0 +1,18 @@ +/*! + \module QtWidgets + \title QtWidgets Module + \ingroup modules + + \brief The QtWidgets module extends QtGui with C++ widget functionality. + + To include the definitions of the module's classes, use the + following directive: + + \snippet doc/src/snippets/code/doc_src_qtwidgets.cpp 1 + + To link against the module, add this line to your \l qmake \c + .pro file: + + \snippet doc/src/snippets/code/doc_src_qtwidgets.pro 0 +*/ + diff --git a/doc/src/widgets/widgets-and-layouts/focus.qdoc b/doc/src/widgets/widgets-and-layouts/focus.qdoc new file mode 100644 index 0000000000..316893edc4 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/focus.qdoc @@ -0,0 +1,186 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page focus.html + \title Keyboard Focus + \brief Keyboard focus management and handling. + \ingroup frameworks-technologies + + \keyword keyboard focus + + Qt's widgets handle keyboard focus in the ways that have become + customary in GUIs. + + The basic issue is that the user's key strokes can be directed at any + of several windows on the screen, and any of several widgets inside + the intended window. When the user presses a key, they expect it to go + to the right place, and the software must try to meet this + expectation. The system must determine which application the key stroke + is directed at, which window within that application, and which widget + within that window. + + \section1 Focus Motion + + The customs which have evolved for directing keyboard focus to a + particular widget are these: + + \list 1 + + \o The user presses \key Tab (or \key Shift+Tab). + \o The user clicks a widget. + \o The user presses a keyboard shortcut. + \o The user uses the mouse wheel. + \o The user moves the focus to a window, and the application must + determine which widget within the window should get the focus. + \endlist + + Each of these motion mechanisms is different, and different types of + widgets receive focus in only some of them. We'll cover each of them + in turn. + + \section2 Tab or Shift+Tab + + Pressing \key Tab is by far the most common way to move focus + using the keyboard. (Sometimes in data-entry applications Enter + does the same as \key{Tab}; this can easily be achieved in Qt by + implementing an \l{The Event System}{event filter}.) + + Pressing \key Tab, in all window systems in common use today, + moves the keyboard focus to the next widget in a circular + per-window list. \key Tab moves focus along the circular list in + one direction, \key Shift+Tab in the other. The order in which + \key Tab presses move from widget to widget is called the tab order. + + You can customize the tab order using QWidget::setTabOrder(). (If + you don't, \key Tab generally moves focus in the order of widget + construction.) \l{Qt Designer} provides a means of visually + changing the tab order. + + Since pressing \key Tab is so common, most widgets that can have focus + should support tab focus. The major exception is widgets that are + rarely used, and where there is some keyboard accelerator or error + handler that moves the focus. + + For example, in a data entry dialog, there might be a field that + is only necessary in one per cent of all cases. In such a dialog, + \key Tab could skip this field, and the dialog could use one of + these mechanisms: + + \list 1 + + \o If the program can determine whether the field is needed, it can + move focus there when the user finishes entry and presses \gui OK, or when + the user presses Enter after finishing the other fields. Alternately, + include the field in the tab order but disable it. Enable it if it + becomes appropriate in view of what the user has set in the other + fields. + + \o The label for the field can include a keyboard shortcut that moves + focus to this field. + + \endlist + + Another exception to \key Tab support is text-entry widgets that + must support the insertion of tabs; almost all text editors fall + into this class. Qt treats \key Ctrl+Tab as \key Tab and \key + Ctrl+Shift+Tab as \key Shift+Tab, and such widgets can + reimplement QWidget::event() and handle Tab before calling + QWidget::event() to get normal processing of all other keys. + However, since some systems use \key Ctrl+Tab for other purposes, + and many users aren't aware of \key Ctrl+Tab anyway, this isn't a + complete solution. + + \section2 The User Clicks a Widget + + This is perhaps even more common than pressing \key Tab on + computers with a mouse or other pointing device. + + Clicking to move the focus is slightly more powerful than \key + Tab. While it moves the focus \e to a widget, for editor widgets + it also moves the text cursor (the widget's internal focus) to + the spot where the mouse is clicked. + + Since it is so common and people are used to it, it's a good idea to + support it for most widgets. However, there is also an important + reason to avoid it: you may not want to remove focus from the widget + where it was. + + For example, in a word processor, when the user clicks the 'B' (bold) + tool button, what should happen to the keyboard focus? Should it + remain where it was, almost certainly in the editing widget, or should + it move to the 'B' button? + + We advise supporting click-to-focus for widgets that support text + entry, and to avoid it for most widgets where a mouse click has a + different effect. (For buttons, we also recommend adding a keyboard + shortcut: QAbstractButton and its subclasses make this very easy.) + + In Qt, only the QWidget::setFocusPolicy() function affects + click-to-focus. + + \section2 The User Presses a Keyboard Shortcut + + It's not unusual for keyboard shortcuts to move the focus. This + can happen implicitly by opening modal dialogs, but also + explicitly using focus accelerators such as those provided by + QLabel::setBuddy(), QGroupBox, and QTabBar. + + We advise supporting shortcut focus for all widgets that the user + may want to jump to. For example, a tab dialog can have keyboard + shortcuts for each of its pages, so the user can press e.g. \key + Alt+P to step to the \underline{P}rinting page. It is easy to + overdo this: there are only a few keys, and it's also important + to provide keyboard shortcuts for commands. \key Alt+P is also + used for Paste, Play, Print, and Print Here in the \l{Standard + Accelerator Keys} list, for example. + + \section2 The User Rotates the Mouse Wheel + + On Microsoft Windows, mouse wheel usage is always handled by the + widget that has keyboard focus. On Mac OS X and X11, it's handled by + the widget that gets other mouse events. + + The way Qt handles this platform difference is by letting widgets move + the keyboard focus when the wheel is used. With the right focus policy + on each widget, applications can work idiomatically correctly on + Windows, Mac OS X, and X11. + + \section2 The User Moves the Focus to This Window + + In this situation the application must determine which widget within + the window should receive the focus. + + This can be simple: If the focus has been in this window before, + then the last widget to have focus should regain it. Qt does this + automatically. + + If focus has never been in this window before and you know where + focus should start out, call QWidget::setFocus() on the widget + which should receive focus before you call QWidget::show() it. If + you don't, Qt will pick a suitable widget. +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-cde.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-cde.qdoc new file mode 100644 index 0000000000..6d6fea7d1e --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-cde.qdoc @@ -0,0 +1,133 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-cde.html + + \title CDE Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "cde" style. + +\section2 Buttons + +\table 100% +\row +\o \image cde-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image cde-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\o \image cde-pushbutton.png + \image cde-toolbutton.png + \caption The QPushButton widget provides a command button. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image cde-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image cde-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image cde-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image cde-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image cde-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image cde-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image cde-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image cde-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image cde-label.png + The QLabel widget provides a text or image display. +\o \image cde-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image cde-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image cde-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image cde-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image cde-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image cde-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image cde-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image cde-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image cde-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image cde-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image cde-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image cde-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image cde-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image cde-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable + +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-cleanlooks.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-cleanlooks.qdoc new file mode 100644 index 0000000000..603650bc4b --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-cleanlooks.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-cleanlooks.html + + \title Cleanlooks Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "cleanlooks" style. + +\section2 Buttons + +\table 100% +\row +\o \image cleanlooks-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image cleanlooks-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image cleanlooks-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image cleanlooks-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image cleanlooks-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image cleanlooks-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image cleanlooks-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image cleanlooks-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image cleanlooks-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image cleanlooks-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image cleanlooks-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image cleanlooks-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image cleanlooks-label.png + The QLabel widget provides a text or image display. +\o \image cleanlooks-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image cleanlooks-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image cleanlooks-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image cleanlooks-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image cleanlooks-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image cleanlooks-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image cleanlooks-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image cleanlooks-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image cleanlooks-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image cleanlooks-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image cleanlooks-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image cleanlooks-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image cleanlooks-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image cleanlooks-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-gtk.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-gtk.qdoc new file mode 100644 index 0000000000..ce6a773776 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-gtk.qdoc @@ -0,0 +1,141 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-gtk.html + + \title GTK Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "gtk" style. + + Take a look at the \l{Qt Widget Gallery} to see how Qt + applications appear in other styles. + +\section2 Buttons + +\table 100% +\row +\o \image gtk-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image gtk-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image gtk-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image gtk-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image gtk-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image gtk-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image gtk-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image gtk-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image gtk-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image gtk-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image gtk-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image gtk-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image gtk-label.png + The QLabel widget provides a text or image display. +\o \image gtk-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image gtk-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image gtk-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image gtk-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image gtk-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image gtk-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image gtk-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image gtk-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image gtk-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image gtk-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image gtk-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image gtk-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image gtk-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image gtk-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-macintosh.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-macintosh.qdoc new file mode 100644 index 0000000000..58622151b7 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-macintosh.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-macintosh.html + + \title Macintosh Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "macintosh" style. + +\section2 Buttons + +\table 100% +\row +\o \image macintosh-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image macintosh-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image macintosh-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image macintosh-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image macintosh-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image macintosh-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image macintosh-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image macintosh-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image macintosh-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image macintosh-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image macintosh-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image macintosh-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image macintosh-label.png + The QLabel widget provides a text or image display. +\o \image macintosh-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image macintosh-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image macintosh-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image macintosh-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image macintosh-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image macintosh-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image macintosh-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image macintosh-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image macintosh-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image macintosh-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image macintosh-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image macintosh-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image macintosh-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image macintosh-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-motif.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-motif.qdoc new file mode 100644 index 0000000000..91485a088f --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-motif.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-motif.html + + \title Motif Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "motif" style. + +\section2 Buttons + +\table 100% +\row +\o \image motif-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image motif-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image motif-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image motif-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image motif-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image motif-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image motif-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image motif-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image motif-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image motif-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image motif-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image motif-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image motif-label.png + The QLabel widget provides a text or image display. +\o \image motif-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image motif-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image motif-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image motif-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image motif-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image motif-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image motif-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image motif-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image motif-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image motif-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image motif-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image motif-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image motif-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image motif-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-plastique.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-plastique.qdoc new file mode 100644 index 0000000000..473d7e8da5 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-plastique.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-plastique.html + + \title Plastique Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "plastique" style. + +\section2 Buttons + +\table 100% +\row +\o \image plastique-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image plastique-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image plastique-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image plastique-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image plastique-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image plastique-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image plastique-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image plastique-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image plastique-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image plastique-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image plastique-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image plastique-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image plastique-label.png + The QLabel widget provides a text or image display. +\o \image plastique-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image plastique-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image plastique-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image plastique-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image plastique-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image plastique-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image plastique-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image plastique-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image plastique-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image plastique-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image plastique-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image plastique-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image plastique-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image plastique-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-windows.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-windows.qdoc new file mode 100644 index 0000000000..1f600b9814 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-windows.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-windows.html + + \title Windows Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "windows" style. + +\section2 Buttons + +\table 100% +\row +\o \image windows-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image windows-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image windows-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image windows-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image windows-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image windows-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image windows-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image windows-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image windows-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image windows-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image windows-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image windows-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image windows-label.png + The QLabel widget provides a text or image display. +\o \image windows-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image windows-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image windows-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image windows-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image windows-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image windows-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image windows-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image windows-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image windows-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image windows-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image windows-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image windows-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image windows-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image windows-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-windowsvista.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-windowsvista.qdoc new file mode 100644 index 0000000000..534da3e2bd --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-windowsvista.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-windowsvista.html + + \title Windows Vista Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "windowsvista" style. + +\section2 Buttons + +\table 100% +\row +\o \image windowsvista-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image windowsvista-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image windowsvista-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image windowsvista-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image windowsvista-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image windowsvista-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image windowsvista-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image windowsvista-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image windowsvista-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image windowsvista-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image windowsvista-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image windowsvista-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image windowsvista-label.png + The QLabel widget provides a text or image display. +\o \image windowsvista-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image windowsvista-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image windowsvista-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image windowsvista-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image windowsvista-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image windowsvista-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image windowsvista-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image windowsvista-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image windowsvista-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image windowsvista-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image windowsvista-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image windowsvista-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image windowsvista-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image windowsvista-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery-windowsxp.qdoc b/doc/src/widgets/widgets-and-layouts/gallery-windowsxp.qdoc new file mode 100644 index 0000000000..4d1c79cc9a --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery-windowsxp.qdoc @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page gallery-windowsxp.html + + \title Windows XP Style Widget Gallery + \ingroup gallery + + This page shows some of the widgets available in Qt + when configured to use the "windowsxp" style. + +\section2 Buttons + +\table 100% +\row +\o \image windowsxp-pushbutton.png + \caption The QPushButton widget provides a command button. +\o \image windowsxp-toolbutton.png + \caption The QToolButton class provides a quick-access button to commands + or options, usually used inside a QToolBar. +\endtable + +\table 100% +\row +\o \image windowsxp-checkbox.png + \caption The QCheckBox widget provides a checkbox with a text label. +\o \image windowsxp-radiobutton.png + \caption The QRadioButton widget provides a radio button with a text or pixmap label. +\endtable + +\section2 Containers + +\table 100% +\row +\o \image windowsxp-groupbox.png + The The QGroupBox widget provides a group box frame with a title. +\o \image windowsxp-tabwidget.png + The QTabWidget class provides a stack of tabbed widgets. +\o \image windowsxp-frame.png + The QFrame widget provides a simple decorated container for other widgets. +\o \image windowsxp-toolbox.png + The QToolBox class provides a column of tabbed widget items. +\endtable + +\section2 Item Views + +\table 100% +\row +\o \image windowsxp-listview.png + The QListView class provides a default model/view implementation of a list/icon view. The QListWidget class provides a classic item-based list/icon view. +\o \image windowsxp-treeview.png + The QTreeView class provides a default model/view implementation of a tree view. The QTreeWidget class provides a classic item-based tree view. +\o \image windowsxp-tableview.png + The QTableView class provides a default model/view implementation of a table view. The QTableWidget class provides a classic item-based table view.\o +\o +\endtable + +\section2 Display Widgets + +\table 100% +\row +\o \image windowsxp-progressbar.png + The QProgressBar widget provides a horizontal progress bar. +\o \image windowsxp-label.png + The QLabel widget provides a text or image display. +\o \image windowsxp-lcdnumber.png + The QLCDNumber widget displays a number with LCD-like digits. +\endtable + +\section2 Input Widgets + +\table 100% +\row +\o \image windowsxp-lineedit.png + The QLineEdit widget is a one-line text editor. +\o \image windowsxp-dateedit.png + The QDateEdit class provides a widget for editing dates. +\o \image windowsxp-timeedit.png + The QTimeEdit class provides a widget for editing times. +\o \image windowsxp-datetimeedit.png + The QDateTimeEdit class provides a widget for editing dates and times. +\endtable + +\table 100% +\row +\o \image windowsxp-slider.png + The QSlider widget provides a vertical or horizontal slider. +\o \image windowsxp-combobox.png + The QComboBox widget is a combined button and pop-up list. +\o \image windowsxp-spinbox.png + The QSpinBox class provides a spin box widget. +\endtable + +\table 100% +\row +\o \image windowsxp-fontcombobox.png + The QFontComboBox widget is a specialized combobox that enables fonts to be selected from a pop-up list containing previews of available fonts. +\o \image windowsxp-doublespinbox.png + The QDoubleSpinBox class provides a spin box widget that allows double precision floating point numbers to be entered. +\o \image windowsxp-horizontalscrollbar.png + The QScrollBar widget provides a vertical or horizontal scroll bar. Here, we show a scroll bar with horizontal orientation. +\endtable + +\table 100% +\row +\o \image windowsxp-dial.png + The QDial class provides a rounded range control (like a speedometer or potentiometer). +\o \image windowsxp-textedit.png + The QTextEdit class provides a widget that is used to edit and display both plain and rich text. +\o \image windowsxp-calendarwidget.png + The QCalendarWidget class provides a monthly calendar widget that can be used to select dates. +\endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/gallery.qdoc b/doc/src/widgets/widgets-and-layouts/gallery.qdoc new file mode 100644 index 0000000000..eb27ec97db --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/gallery.qdoc @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group gallery + \title Qt Widget Gallery + \brief Qt widgets shown in different styles on various platforms. + + Qt's support for widget styles and themes enables your application to fit in + with the native desktop enviroment. Below, you can find links to the various + widget styles that are supplied with Qt 4. + + \table + \row + \o \image plastique-tabwidget.png Plastique Style Widget Gallery + \caption \l{Plastique Style Widget Gallery} + + The Plastique style is provided by QPlastiqueStyle. + \o \image windowsxp-tabwidget.png Windows XP Style Widget Gallery + \caption \l{Windows XP Style Widget Gallery} + + The Windows XP style is provided by QWindowsXPStyle. + \o \image windows-tabwidget.png Windows Style Widget Gallery + \caption \l{Windows Style Widget Gallery} + + The Windows style is provided by QWindowsStyle. + \endtable + + \table + \row + \o \image macintosh-tabwidget.png Macintosh Style Widget Gallery + \caption \l{Macintosh Style Widget Gallery} + + The Macintosh style is provided by QMacStyle. + \o \image cleanlooks-tabwidget.png Cleanlooks Style Widget Gallery + \caption \l{Cleanlooks Style Widget Gallery} + + The Cleanlooks style is provided by QCleanlooksStyle. + \o \image windowsvista-tabwidget.png Windows Vista Style Widget Gallery + \caption \l{Windows Vista Style Widget Gallery} + + The Windows Vista style is provided by QWindowsVistaStyle. + \endtable + + \table + \row + \o \image gtk-tabwidget.png GTK Style Widget Gallery + \caption \l{GTK Style Widget Gallery} + + The GTK style is provided by QGtkStyle. + \o \image motif-tabwidget.png Motif Style Widget Gallery + \caption \l{Motif Style Widget Gallery} + + The Motif style is provided by QMotifStyle. + \o \image cde-tabwidget.png CDE Style Widget Gallery + \caption \l{CDE Style Widget Gallery} + + The Common Desktop Environment style is provided by QCDEStyle. + \endtable +*/ diff --git a/doc/src/widgets/widgets-and-layouts/layout.qdoc b/doc/src/widgets/widgets-and-layouts/layout.qdoc new file mode 100644 index 0000000000..3db58c21f9 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/layout.qdoc @@ -0,0 +1,396 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group geomanagement + \title Layout Classes +*/ + +/*! + \page layout.html + \title Layout Management + \ingroup qt-basic-concepts + \ingroup qt-gui-concepts + \brief A tour of the standard layout managers and an introduction to custom + layouts. + + \previouspage Widgets and Layouts + \contentspage Widgets and Layouts + \nextpage {Styles and Style Aware Widgets}{Styles} + + \ingroup frameworks-technologies + + The Qt layout system provides a simple and powerful way of automatically + arranging child widgets within a widget to ensure that they make good use + of the available space. + + \tableofcontents + + \section1 Introduction + + Qt includes a set of layout management classes that are used to describe + how widgets are laid out in an application's user interface. These layouts + automatically position and resize widgets when the amount of space + available for them changes, ensuring that they are consistently arranged + and that the user interface as a whole remains usable. + + All QWidget subclasses can use layouts to manage their children. The + QWidget::setLayout() function applies a layout to a widget. When a layout + is set on a widget in this way, it takes charge of the following tasks: + + \list + \o Positioning of child widgets. + \o Sensible default sizes for windows. + \o Sensible minimum sizes for windows. + \o Resize handling. + \o Automatic updates when contents change: + \list + \o Font size, text or other contents of child widgets. + \o Hiding or showing a child widget. + \o Removal of child widgets. + \endlist + \endlist + + \section1 Qt's Layout Classes + + Qt's layout classes were designed for hand-written C++ code, allowing + measurements to be specified in pixels for simplicity, so they are easy to + understand and use. The code generated for forms created using \QD also + uses the layout classes. \QD is useful to use when experimenting with the + design of a form since it avoids the compile, link and run cycle usually + involved in user interface development. + + \annotatedlist geomanagement + + \section1 Horizontal, Vertical, Grid, and Form Layouts + + The easiest way to give your widgets a good layout is to use the built-in + layout managers: QHBoxLayout, QVBoxLayout, QGridLayout, and QFormLayout. + These classes inherit from QLayout, which in turn derives from QObject (not + QWidget). They take care of geometry management for a set of widgets. To + create more complex layouts, you can nest layout managers inside each other. + + \list + \o A QHBoxLayout lays out widgets in a horizontal row, from left to + right (or right to left for right-to-left languages). + \image qhboxlayout-with-5-children.png + + \o A QVBoxLayout lays out widgets in a vertical column, from top to + bottom. + \image qvboxlayout-with-5-children.png + + \o A QGridLayout lays out widgets in a two-dimensional grid. Widgets + can occupy multiple cells. + \image qgridlayout-with-5-children.png + + \o A QFormLayout lays out widgets in a 2-column descriptive label- + field style. + \image qformlayout-with-6-children.png + \endlist + + + \section2 Laying Out Widgets in Code + + The following code creates a QHBoxLayout that manages the geometry of five + \l{QPushButton}{QPushButtons}, as shown on the first screenshot above: + + \snippet doc/src/snippets/layouts/layouts.cpp 0 + \snippet doc/src/snippets/layouts/layouts.cpp 1 + \snippet doc/src/snippets/layouts/layouts.cpp 2 + \codeline + \snippet doc/src/snippets/layouts/layouts.cpp 3 + \snippet doc/src/snippets/layouts/layouts.cpp 4 + \snippet doc/src/snippets/layouts/layouts.cpp 5 + + The code for QVBoxLayout is identical, except the line where the layout is + created. The code for QGridLayout is a bit different, because we need to + specify the row and column position of the child widget: + + \snippet doc/src/snippets/layouts/layouts.cpp 12 + \snippet doc/src/snippets/layouts/layouts.cpp 13 + \snippet doc/src/snippets/layouts/layouts.cpp 14 + \codeline + \snippet doc/src/snippets/layouts/layouts.cpp 15 + \snippet doc/src/snippets/layouts/layouts.cpp 16 + \snippet doc/src/snippets/layouts/layouts.cpp 17 + + The third QPushButton spans 2 columns. This is possible by specifying 2 as + the fifth argument to QGridLayout::addWidget(). + + QFormLayout will add two widgets on a row, commonly a QLabel and a QLineEdit + to create forms. Adding a QLabel and a QLineEdit on the same row will set + the QLineEdit as the QLabel's buddy. The following code will use the + QFormLayout to place three \l{QPushButton}{QPushButtons} and a corresponding + QLineEdit on a row. + + \snippet doc/src/snippets/layouts/layouts.cpp 18 + \snippet doc/src/snippets/layouts/layouts.cpp 19 + \snippet doc/src/snippets/layouts/layouts.cpp 20 + \codeline + \snippet doc/src/snippets/layouts/layouts.cpp 21 + \snippet doc/src/snippets/layouts/layouts.cpp 22 + \snippet doc/src/snippets/layouts/layouts.cpp 23 + + + \section2 Tips for Using Layouts + + When you use a layout, you do not need to pass a parent when constructing + the child widgets. The layout will automatically reparent the widgets + (using QWidget::setParent()) so that they are children of the widget on + which the layout is installed. + + \note Widgets in a layout are children of the widget on which the layout + is installed, \e not of the layout itself. Widgets can only have other + widgets as parent, not layouts. + + You can nest layouts using \c addLayout() on a layout; the inner layout + then becomes a child of the layout it is inserted into. + + + \section1 Adding Widgets to a Layout + + When you add widgets to a layout, the layout process works as follows: + + \list 1 + \o All the widgets will initially be allocated an amount of space in + accordance with their QWidget::sizePolicy() and + QWidget::sizeHint(). + + \o If any of the widgets have stretch factors set, with a value + greater than zero, then they are allocated space in proportion to + their stretch factor (explained below). + + \o If any of the widgets have stretch factors set to zero they will + only get more space if no other widgets want the space. Of these, + space is allocated to widgets with an + \l{QSizePolicy::Expanding}{Expanding} size policy first. + + \o Any widgets that are allocated less space than their minimum size + (or minimum size hint if no minimum size is specified) are + allocated this minimum size they require. (Widgets don't have to + have a minimum size or minimum size hint in which case the strech + factor is their determining factor.) + + \o Any widgets that are allocated more space than their maximum size + are allocated the maximum size space they require. (Widgets do not + have to have a maximum size in which case the strech factor is + their determining factor.) + \endlist + + + \section2 Stretch Factors + \keyword stretch factor + + Widgets are normally created without any stretch factor set. When they are + laid out in a layout the widgets are given a share of space in accordance + with their QWidget::sizePolicy() or their minimum size hint whichever is + the greater. Stretch factors are used to change how much space widgets are + given in proportion to one another. + + If we have three widgets laid out using a QHBoxLayout with no stretch + factors set we will get a layout like this: + + \img layout1.png Three widgets in a row + + If we apply stretch factors to each widget, they will be laid out in + proportion (but never less than their minimum size hint), e.g. + + \img layout2.png Three widgets with different stretch factors in a row + + + \section1 Custom Widgets in Layouts + + When you make your own widget class, you should also communicate its layout + properties. If the widget has a one of Qt's layouts, this is already taken + care of. If the widget does not have any child widgets, or uses manual + layout, you can change the behavior of the widget using any or all of the + following mechanisms: + + \list + \o Reimplement QWidget::sizeHint() to return the preferred size of the + widget. + \o Reimplement QWidget::minimumSizeHint() to return the smallest size + the widget can have. + \o Call QWidget::setSizePolicy() to specify the space requirements of + the widget. + \endlist + + Call QWidget::updateGeometry() whenever the size hint, minimum size hint or + size policy changes. This will cause a layout recalculation. Multiple + consecutive calls to QWidget::updateGeometry() will only cause one layout + recalculation. + + If the preferred height of your widget depends on its actual width (e.g., + a label with automatic word-breaking), set the + \l{QSizePolicy::hasHeightForWidth()}{height-for-width} flag in the + widget's \l{QWidget::sizePolicy}{size policy} and reimplement + QWidget::heightForWidth(). + + Even if you implement QWidget::heightForWidth(), it is still a good idea to + provide a reasonable sizeHint(). + + For further guidance when implementing these functions, see the + \e{Qt Quarterly} article + \l{http://doc.qt.nokia.com/qq/qq04-height-for-width.html} + {Trading Height for Width}. + + + \section1 Layout Issues + + The use of rich text in a label widget can introduce some problems to the + layout of its parent widget. Problems occur due to the way rich text is + handled by Qt's layout managers when the label is word wrapped. + + In certain cases the parent layout is put into QLayout::FreeResize mode, + meaning that it will not adapt the layout of its contents to fit inside + small sized windows, or even prevent the user from making the window too + small to be usable. This can be overcome by subclassing the problematic + widgets, and implementing suitable \l{QWidget::}{sizeHint()} and + \l{QWidget::}{minimumSizeHint()} functions. + + In some cases, it is relevant when a layout is added to a widget. When + you set the widget of a QDockWidget or a QScrollArea (with + QDockWidget::setWidget() and QScrollArea::setWidget()), the layout must + already have been set on the widget. If not, the widget will not be + visible. + + + \section1 Manual Layout + + If you are making a one-of-a-kind special layout, you can also make a + custom widget as described above. Reimplement QWidget::resizeEvent() to + calculate the required distribution of sizes and call + \l{QWidget::}{setGeometry()} on each child. + + The widget will get an event of type QEvent::LayoutRequest when the + layout needs to be recalculated. Reimplement QWidget::event() to handle + QEvent::LayoutRequest events. + + + \section1 How to Write A Custom Layout Manager + + An alternative to manual layout is to write your own layout manager by + subclassing QLayout. The \l{layouts/borderlayout}{Border Layout} and + \l{layouts/flowlayout}{Flow Layout} examples show how to do this. + + Here we present an example in detail. The \c CardLayout class is inspired + by the Java layout manager of the same name. It lays out the items (widgets + or nested layouts) on top of each other, each item offset by + QLayout::spacing(). + + To write your own layout class, you must define the following: + \list + \o A data structure to store the items handled by the layout. Each + item is a \link QLayoutItem QLayoutItem\endlink. We will use a + QList in this example. + \o \l{QLayout::}{addItem()}, how to add items to the layout. + \o \l{QLayout::}{setGeometry()}, how to perform the layout. + \o \l{QLayout::}{sizeHint()}, the preferred size of the layout. + \o \l{QLayout::}{itemAt()}, how to iterate over the layout. + \o \l{QLayout::}{takeAt()}, how to remove items from the layout. + \endlist + + In most cases, you will also implement \l{QLayout::}{minimumSize()}. + + + \section2 The Header File (\c card.h) + + \snippet doc/src/snippets/code/doc_src_layout.cpp 0 + + + \section2 The Implementation File (\c card.cpp) + + \snippet doc/src/snippets/code/doc_src_layout.cpp 1 + + First we define \c{count()} to fetch the number of items in the list. + + \snippet doc/src/snippets/code/doc_src_layout.cpp 2 + + Then we define two functions that iterate over the layout: \c{itemAt()} + and \c{takeAt()}. These functions are used internally by the layout system + to handle deletion of widgets. They are also available for application + programmers. + + \c{itemAt()} returns the item at the given index. \c{takeAt()} removes the + item at the given index, and returns it. In this case we use the list index + as the layout index. In other cases where we have a more complex data + structure, we may have to spend more effort defining a linear order for the + items. + + \snippet doc/src/snippets/code/doc_src_layout.cpp 3 + + \c{addItem()} implements the default placement strategy for layout items. + This function must be implemented. It is used by QLayout::add(), by the + QLayout constructor that takes a layout as parent. If your layout has + advanced placement options that require parameters, you must provide extra + access functions such as the row and column spanning overloads of + QGridLayout::addItem(), QGridLayout::addWidget(), and + QGridLayout::addLayout(). + + \snippet doc/src/snippets/code/doc_src_layout.cpp 4 + + The layout takes over responsibility of the items added. Since QLayoutItem + does not inherit QObject, we must delete the items manually. In the + destructor, we remove each item from the list using \c{takeAt()}, and + then delete it. + + \snippet doc/src/snippets/code/doc_src_layout.cpp 5 + + The \c{setGeometry()} function actually performs the layout. The rectangle + supplied as an argument does not include \c{margin()}. If relevant, use + \c{spacing()} as the distance between items. + + \snippet doc/src/snippets/code/doc_src_layout.cpp 6 + + \c{sizeHint()} and \c{minimumSize()} are normally very similar in + implementation. The sizes returned by both functions should include + \c{spacing()}, but not \c{margin()}. + + \snippet doc/src/snippets/code/doc_src_layout.cpp 7 + + + \section2 Further Notes + + \list + \o This custom layout does not handle height for width. + \o We ignore QLayoutItem::isEmpty(); this means that the layout will + treat hidden widgets as visible. + \o For complex layouts, speed can be greatly increased by caching + calculated values. In that case, implement + QLayoutItem::invalidate() to mark the cached data is dirty. + \o Calling QLayoutItem::sizeHint(), etc. may be expensive. So, you + should store the value in a local variable if you need it again + later within in the same function. + \o You should not call QLayoutItem::setGeometry() twice on the same + item in the same function. This call can be very expensive if the + item has several child widgets, because the layout manager must do + a complete layout every time. Instead, calculate the geometry and + then set it. (This does not only apply to layouts, you should do + the same if you implement your own resizeEvent(), for example.) + \endlist +*/ + diff --git a/doc/src/widgets/widgets-and-layouts/styles.qdoc b/doc/src/widgets/widgets-and-layouts/styles.qdoc new file mode 100644 index 0000000000..3b705de973 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/styles.qdoc @@ -0,0 +1,2102 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group appearance + \title Widget Appearance and Style + \brief Classes used for customizing UI appearance and style. +*/ + +/*! + \page style-reference.html + \title Styles and Style Aware Widgets + \ingroup qt-gui-concepts + \brief Styles and the styling of widgets. + + Styles (classes that inherit QStyle) draw on behalf of widgets + and encapsulate the look and feel of a GUI. The QStyle class is + an abstract base class that encapsulates the look and feel of a + GUI. Qt's built-in widgets use it to perform nearly all of their + drawing, ensuring that they look exactly like the equivalent + native widgets. + + Several styles are built into Qt (e.g., windows style and motif style). + Other styles are only available on specific platforms (such as + the windows XP style). Custom styles are made available as plugins + or by creating an instance of the style class in an application and + setting it with QApplication::setStyle(). + + To implement a new style, you inherit one of Qt's existing styles + - the one most resembling the style you want to create - and + reimplement a few virtual functions. This process is somewhat + involved, and we therefore provide this overview. We give a + step-by-step walkthrough of how to style individual Qt widgets. + We will examine the QStyle virtual functions, member variables, + and enumerations. + + The part of this document that does not concern the styling of + individual widgets is meant to be read sequentially because later + sections tend to depend on earlier ones. The description of the + widgets can be used for reference while implementing a style. + However, you may need to consult the Qt source code in some cases. + The sequence in the styling process should become clear after + reading this document, which will aid you in locating relevant code. + + To develop style aware widgets (i.e., widgets that conform to + the style in which they are drawn), you need to draw them using the + current style. This document shows how widgets draw themselves + and which possibilities the style gives them. + + \section1 Classes for Widget Styling + + These classes are used to customize an application's appearance and + style. + + \annotatedlist appearance + + \section1 The QStyle implementation + + The API of QStyle contains functions that draw the widgets, static + helper functions to do common and difficult tasks (e.g., + calculating the position of slider handles) and functions to do + the various calculations necessary while drawing (e.g., for the + widgets to calculate their size hints). The style also help some + widgets with the layout of their contents. In addition, it creates + a QPalette that contains \l{QBrush}es to draw with. + + QStyle draws graphical elements; an element is a widget or a + widget part like a push button bevel, a window frame, or a scroll + bar. Most draw functions now take four arguments: + + \list + \o an enum value specifying which graphical element to draw + \o a QStyleOption specifying how and where to render that element + \o a QPainter that should be used to draw the element + \o a QWidget on which the drawing is performed (optional) + \endlist + + When a widget asks a style to draw an element, it provides the style + with a QStyleOption, which is a class that contains the information + necessary for drawing. Thanks to QStyleOption, it is possible to make + QStyle draw widgets without linking in any code for the widget. This + makes it possible to use \l{QStyle}'s draw functions on any paint + device, i.e., you can draw a combobox on any widget, not just on a + QComboBox. + + The widget is passed as the last argument in case the style needs + it to perform special effects (such as animated default buttons on + Mac OS X), but it isn't mandatory. + + We will in the course of this section look at the style elements, + the style options, and the functions of QStyle. Finally, we describe + how the palette is used. + + Items in item views is drawn by \l{Delegate Classes}{delegates} in + Qt. The item view headers are still drawn by the style. Qt's + default delegate, QStyledItemDelegate, draws its items partially + through the current style; it draws the check box indicators and + calculate bounding rectangles for the elements of which the item + consists. In this document, we only describe how to implement a + QStyle subclass. If you wish to add support for other datatypes + than those supported by the QStyledItemDelegate, you need to + implement a custom delegate. Note that delegates must be set + programmatically for each individual widget (i.e., default + delegates cannot be provided as plugins). + + \section2 The Style Elements + + A style element is a graphical part of a GUI. A widget consists + of a hierarchy (or tree) of style elements. For instance, when a + style receives a request to draw a push button (from QPushButton, + for example), it draws a label (text and icon), a button bevel, + and a focus frame. The button bevel, in turn, consists of a frame + around the bevel and two other elements, which we will look at + later. Below is a conceptual illustration of the push button + element tree. We will see the actual tree for QPushButton when we + go through the individual widgets. + + \image javastyle/conceptualpushbuttontree.png + + Widgets are not necessarily drawn by asking the style to draw + only one element. Widgets can make several calls to the style to + draw different elements. An example is QTabWidget, which draws its + tabs and frame individually. + + There are three element types: primitive elements, control + elements, and complex control elements. The elements are defined + by the \l{QStyle::}{ComplexControl}, \l{QStyle::}{ControlElement}, + and \l{QStyle::}{PrimitiveElement} enums. The values of + each element enum has a prefix to identify their type: \c{CC_} for + complex elements, \c{CE_} for control elements, and \c{PE_} for + primitive elements. We will in the following three sections see what + defines the different elements and see examples of widgets that use + them. + + The QStyle class description contains a list of these elements and + their roles in styling widgets. We will see how they are used when + we style individual widgets. + + \section3 Primitive Elements + + Primitive elements are GUI elements that are common and often used + by several widgets. Examples of these are frames, button bevels, + and arrows for spin boxes, scroll bars, and combo boxes. + Primitive elements cannot exist on their own: they are always part + of a larger construct. They take no part in the interaction with + the user, but are passive decorations in the GUI. + + \section3 Control Elements + + A control element performs an action or displays information + to the user. Examples of control elements are push buttons, check + boxes, and header sections in tables and tree views. Control + elements are not necessarily complete widgets such as push + buttons, but can also be widget parts such as tab bar tabs and + scroll bar sliders. They differ from primitive elements in that + they are not passive, but fill a function in the interaction with + the user. Controls that consist of several elements often use the + style to calculate the bounding rectangles of the elements. The + available sub elements are defined by the \l{QStyle::}{SubElement} + enum. This enum is only used for calculating bounding rectangles, + and sub elements are as such not graphical elements to be drawn + like primitive, control, and complex elements. + + \section3 Complex Control Elements + + Complex control elements contain sub controls. Complex controls + behave differently depending on where the user handles them with + the mouse and which keyboard keys are pressed. This is dependent + on which sub control (if any) that the mouse is over or received a + mouse press. Examples of complex controls are scroll bars and + combo boxes. With a scroll bar, you can use the mouse to move the + slider and press the line up and line down buttons. The available + sub controls are defined by the \l{QStyle}{SubControl} enum. + + In addition to drawing, the style needs to provide the widgets + with information on which sub control (if any) a mouse press was + made on. For instance, a QScrollBar needs to know if the user + pressed the slider, the slider groove, or one of the buttons. + + Note that sub controls are not the same as the control elements + described in the previous section. You cannot use the style to + draw a sub control; the style will only calculate the bounding + rectangle in which the sub control should be drawn. It is common, + though, that complex elements use control and primitive elements + to draw their sub controls, which is an approach that is + frequently used by the built-in styles in Qt and also the Java + style. For instance, the Java style uses PE_IndicatorCheckBox to + draw the check box in group boxes (which is a sub control of + CC_GroupBox). Some sub controls have an equivalent control element, + e.g., the scroll bar slider (SC_SCrollBarSlider and + CE_ScrollBarSlider). + + \section3 Other QStyle Tasks + + The style elements and widgets, as mentioned, use the style to + calculate bounding rectangles of sub elements and sub controls, + and pixel metrics, which is a style dependent size in screen + pixels, for measures when drawing. The available rectangles and + pixel metrics are represented by three enums in QStyle: + \l{QStyle::}{SubElement}, \l{QStyle::}{SubControl}, and + \l{QStyle::}{PixelMetric}. Values of the enums can easily by + identified as they start with SE_, SC_ and PM_. + + The style also contain a set of style hints, which is + represented as values in the \l{QStyle::}{StyleHint} enum. All + widgets do not have the same functionality and look in the + different styles. For instance, when the menu items in a menu do not + fit in a single column on the screen, some styles support + scrolling while others draw more than one column to fit all items. + + A style usually has a set of standard images (such as a warning, a + question, and an error image) for message boxes, file dialogs, + etc. QStyle provides the \l{QStyle::}{StandardPixmap} enum. Its + values represent the standard images. Qt's widgets use these, so + when you implement a custom style you should supply the images + used by the style that is being implemented. + + The style calculates the spacing between widgets in layouts. There + are two ways the style can handle these calculations. You can set + the PM_LayoutHorizontalSpacing and PM_LayoutVerticalSpacing, which + is the way the java style does it (through QCommonStyle). + Alternatively, you can implement QStyle::layoutSpacing() and + QStyle::layoutSpacingImplementation() if you need more control over + this part of the layout. In these functions you can calculate the + spacing based on control types (QSizePolicy::ControlType) for + different size policies (QSizePolicy::Policy) and also the style + option for the widget in question. + + \section2 Style Options + + The sub-classes of QStyleOption contain all information necessary + to style the individual elements. Style options are instantiated - + usually on the stack - and filled out by the caller of the QStyle + function. Depending on what is drawn the style will expect + different a different style option class. For example, the + QStyle::PE_FrameFocusRect element expects a QStyleOptionFocusRect + argument, and it's possible to create custom subclasses that a + custom style can use. The style options keep public variables + for performance reasons. + + The widgets can be in a number of different states, which are + defined by the \l{QStyle::}{State} enum. Some of the state flags have + different meanings depending on the widget, but others are common + for all widgets like State_Disabled. It is QStyleOption that sets + the common states with QStyleOption::initFrom(); the rest of the + states are set by the individual widgets. + + Most notably, the style options contain the palette and bounding + rectangles of the widgets to be drawn. Most widgets have + specialized style options. QPushButton and QCheckBox, for + instance, use QStyleOptionButton as style option, which contain + the text, icon, and the size of their icon. The exact contents of + all options are described when we go through individual widgets. + + When reimplementing QStyle functions that take a + QStyleOption parameter, you often need to cast the + QStyleOption to a subclass (e.g., QStyleOptionFocusRect). For + safety, you can use qstyleoption_cast() to ensure that the + pointer type is correct. If the object isn't of the right type, + qstyleoption_cast() returns 0. For example: + + \snippet doc/src/snippets/code/doc_src_qt4-styles.cpp 0 + + The following code snippet illustrates how to use QStyle to + draw the focus rectangle from a custom widget's paintEvent(): + + \snippet doc/src/snippets/code/doc_src_qt4-styles.cpp 1 + + The next example shows how to derive from an existing style to + customize the look of a graphical element: + + \snippet doc/src/snippets/customstyle/customstyle.h 0 + \codeline + \snippet doc/src/snippets/customstyle/customstyle.cpp 2 + \snippet doc/src/snippets/customstyle/customstyle.cpp 3 + \snippet doc/src/snippets/customstyle/customstyle.cpp 4 + + \section2 QStyle Functions + + The QStyle class defines three functions for drawing the primitive, + control, and complex elements: + \l{QStyle::}{drawPrimitive()}, + \l{QStyle::}{drawControl()}, and + \l{QStyle::}{drawComplexControl()}. The functions takes the + following parameters: + + \list + \o the enum value of the element to draw + \o a QStyleOption which contains the information needed to + draw the element. + \o a QPainter with which to draw the element. + \o a pointer to a QWidget, typically the widget + that the element is painted on. + \endlist + + Not all widgets send a pointer to themselves. If the style + option sent to the function does not contain the information you + need, you should check the widget implementation to see if it + sends a pointer to itself. + + The QStyle class also provides helper functions that are used + when drawing the elements. The \l{QStyle::}{drawItemText()} + function draws text within a specified rectangle and taking a + QPalette as a parameter. The \l{QStyle::}{drawItemPixmap()} + function helps to align a pixmap within a specified bounding + rectangle. + + Other QStyle functions do various calculations for the + functions that draw. The widgets also use these functions for + calculating size hints and also for bounding rectangle + calculations if they draw several style elements themselves. + As with the functions that draw elements the helper functions + typically takes the same arguments. + + \list + \o The \l{QStyle::}{subElementRect()} function takes a + \l{QStyle::}{SubElement} enum value, and calculates a bounding + rectangle for a sub element. The style uses this function to + know where to draw the different parts of an element. This is + mainly done for reuse. If you create a new style, you can use + the same location of sub elements as the super class. + + \o The \l{QStyle::}{subControlRect()} function is used to + calculate bounding rectangles for sub controls in complex + controls. When you implement a new style, you reimplement \c + subControlRect() and calculate the rectangles that are different + from the super class. + + \o The \l{QStyle::}{pixelMetric()} function returns a pixel + metric, which is a style dependent size given in screen + pixels. It takes a value of the \l{QStyle::}{PixelMetric} enum + and returns the correct measure. Note that pixel metrics do + not necessarily have to be static measures, but can be + calculated with, for example, the style option. + + \o The \l{QStyle::}{hitTestComplexControl()} function returns the + sub control that the mouse pointer is over in a complex control. + Usually, this is simply a matter of using + \l{QStyle::}{subControlRect()} to get the bounding rectangles of + the sub controls, and see which rectangle contains the position of + the cursor. + \endlist + + QStyle also have the functions \l{QStyle::}{polish()} and + \l{QStyle::}{unpolish()}. All widgets are sent to the \c polish() + function before being shown and to \c unpolish() when they + are hidden. You can use these functions to set attributes on the + widgets or do other work that is required by your style. For + instance, if you need to know when the mouse is hovering over the + widget, you need to set the \l{Qt::}{WA_Hover} widget attribute. + The State_MouseOver state flag will then be set in the widget's + style options. + + QStyle has a few static helper functions that do some common and + difficult tasks. They can calculate the position of a slider + handle from the value of the slider and transform rectangles + and draw text considering reverse layouts; see the QStyle + class documentation for more details. + + The usual approach when one reimplements QStyle virtual + functions is to do work on elements that are different from the + super class; for all other elements, you can simply use the super + class implementation. + + \section2 The Palette + + Each style provides a color - that is, QBrush - palette that + should be used for drawing the widgets. There is one set of colors + for the different widget states (QPalette::ColorGroup): active + (widgets in the window that has keyboard focus), inactive (widgets + used for other windows), and disabled (widgets that are set + disabled). The states can be found by querying the State_Active + and State_Enabled state flags. Each set contains color certain + roles given by the QPalette::ColorRole enum. The roles describe in + which situations the colors should be used (e.g., for painting + widget backgrounds, text, or buttons). + + How the color roles are used is up to the style. For instance, if + the style uses gradients, one can use a palette color and make it + darker or lighter with QColor::darker() and QColor::lighter() to + create the gradient. In general, if you need a brush that is not + provided by the palette, you should try to derive it from one. + + QPalette, which provides the palette, stores colors for + different widget states and color roles. The palette for a style + is returned by \l{QStyle::}{standardPalette()}. The standard + palette is not installed automatically when a new style is set + on the application (QApplication::setStyle()) or widget + (QWidget::setStyle()), so you must set the palette yourself + with (QApplication::setPalette()) or (QWidget::setPalette()). + + It is not recommended to hard code colors as applications and + individual widgets can set their own palette and also use the + styles palette for drawing. Note that none of Qt's widgets set + their own palette. The java style does hard code some colors, but + its author looks past this in silence. Of course, it is not + intended that the style should look good with any palette. + + \section2 Implementation Issues + + When you implement styles, there are several issues to + consider. We will give some hints and advice on implementation + here. + + When implementing styles, it is necessary to look through the + code of the widgets and code of the base class and its ancestors. + This is because the widgets use the style differently, because the + implementation in the different styles virtual functions can + affect the state of the drawing (e.g., by altering the QPainter + state without restoring it and drawing some elements without using + the appropriate pixel metrics and sub elements). + + It is recommended that the styles do not alter the proposed size + of widgets with the QStyle::sizeFromContents() function but let + the QCommonStyle implementation handle it. If changes need to be + made, you should try to keep them small; application development + may be difficult if the layout of widgets looks considerably + different in the various styles. + + We recommend using the QPainter directly for drawing, i.e., not + use pixmaps or images. This makes it easier for the style conform + to the palette (although you can set your own color table on a + QImage with \l{QImage::}{setColorTable()}). + + It is, naturally, possible to draw elements without using the + style to draw the sub elements as intended by Qt. This is + discouraged as custom widgets may depend on these sub elements to + be implemented correctly. The widget walkthrough shows how Qt + uses the sub elements. + + \section1 Java Style + + We have implemented a style that resembles the Java default look + and feel (previously known as Metal). We have done this as it is + relatively simple to implement and we wanted to build a style for + this overview document. To keep it simple and not to extensive, we + have simplified the style somewhat, but Qt is perfectly able to + make an exact copy of the style. However, there are no concrete + plans to implement the style as a part of Qt. + + In this section we will have a look at some implementation + issues. Finally, we will see a complete example on the styling of + a Java widget. We will continue to use the java style + throughout the document for examples and widget images. The + implementation itself is somewhat involved, and it is not + intended that you should read through it. + + \section2 Design and Implementation + + The first step in designing the style was to select the base + class. We chose to subclass QWindowsStyle. This class implements + most of the functionality we need other than performing the actual + drawing. Also, windows and java share layout of sub controls for + several of the complex controls (which reduces the amount of code + required considerably). + + The style is implemented in one class. We have done this + because we find it convenient to keep all code in one file. Also, + it is an advantage with regards to optimization as we instantiate + less objects. We also keep the number of functions at a minimum by + using switches to identify which element to draw in the functions. + This results in large functions, but since we divide the code for + each element in the switches, the code should still be easy to + read. + + \section2 Limitations and Differences from Java + + We have not fully implemented every element in the Java style. + This way, we have reduced the amount and complexity of the code. + In general, the style was intended as a practical example for + this style overview document, and not to be a part of Qt + itself. + + Not all widgets have every state implemented. This goes for + states that are common, e.g., State_Disabled. Each state is, + however, implemented for at least one widget. + + We have only implemented ticks below the slider. Flat push + buttons are also left out. We do not handle the case where the + title bars and dock window titles grows to small for their + contents, but simply draw sub controls over each other. + + We have not tried to emulate the Java fonts. Java and Qt use very + different font engines, so we don't consider it worth the effort + as we only use the style as an example for this overview. + + We have hardcoded the colors (we don't use the QPalette) for + the linear gradients, which are used, for example, for button + bevels, tool bars, and check boxes. This is because the Java + palette cannot produce these colors. Java does not change these + colors based on widget color group or role anyway (they are not + dependent on the palette), so it does not present a problem in any + case. + + It is Qt's widgets that are styled. Some widgets do not exist + at all in Java, e.g., QToolBox. Others contain elements that the + Java widgets don't. The tree widget is an example of the latter in + which Java's JTree does not have a header. + + The style does not handle reverse layouts. We assume that the + layout direction is left to right. QWindowsStyle handles reverse + widgets; if we implemented reverse layouts, widgets that we change + the position of sub elements, or handle text alignment in labels + our selves would need to be updated. + + \section2 Styling Java Check Boxes + + As an example, we will examine the styling of check boxes in the + java style. We describe the complete process and print all code in + both the java style and Qt classes involved. In the rest of this + document, we will not examine the source code of the individual + widgets. Hopefully, this will give you an idea on how to search + through the code if you need to check specific implementation + details; most widgets follow the same structure as the check + boxes. We have edited the QCommonStyle code somewhat to remove + code that is not directly relevant for check box styling. + + We start with a look at how QCheckBox builds it style option, + which is QStyleOptionButton for checkboxes: + + \snippet doc/src/snippets/code/doc_src_styles.cpp 0 + + First we let QStyleOption set up the option with the information + that is common for all widgets with \c initFrom(). We will look at + this shortly. + + The down boolean is true when the user press the box down; this is + true whether the box is checked or not of the checkbox. The + State_NoChange state is set when we have a tristate checkbox and + it is partially checked. It has State_On if the box is checked and + State_Off if it is unchecked. State_MouseOver is set if the mouse + hovers over the checkbox and the widget has attribute Qt::WA_Hover + set - you set this in QStyle::polish(). In addition, the style + option also contains the text, icon, and icon size of the button. + + \l{QStyleOption::}{initFrom()} sets up the style option with the + attributes that are common for all widgets. We print its + implementation here: + + \snippet doc/src/snippets/code/doc_src_styles.cpp 1 + + The State_Enabled is set when the widget is enabled. When the + widget has focus the State_HasFocus flag is set. Equally, the + State_Active flag is set when the widget is a child of the active + window. The State_MouseOver will only be set if the widget has + the WA_HoverEnabled windows flag set. Notice that keypad + navigation must be enabled in Qt for the State_HasEditFocus to + be included; it is not included by default. + + In addition to setting state flags the QStyleOption contains + other information about the widget: \c direction is the layout + direction of the layout, \c rect is the bounding rectangle of the + widget (the area in which to draw), \c palette is the QPalette + that should be used for drawing the widget, and \c fontMetrics is + the metrics of the font that is used by the widget. + + We give an image of a checkbox and the style option to match + it. + + \image javastyle/checkboxexample.png A java style checkbox + + The above checkbox will have the following state flags in its + style option: + + \table 90% + \header + \o State flag + \o Set + \row + \o State_Sunken + \o Yes + \row + \o State_NoChange + \o No + \row + \o State_On + \o Yes + \row + \o State_Off + \o No + \row + \o State_MouseOver + \o Yes + \row + \o State_Enabled + \o Yes + \row + \o State_HasFocus + \o Yes + \row + \o State_KeyboardFocusChange + \o No + \row + \o State_Active + \o Yes + \endtable + + The QCheckBox paints itself in QWidget::paintEvent() with + style option \c opt and QStylePainter \c p. The QStylePainter + class is a convenience class to draw style elements. Most + notably, it wraps the methods in QStyle used for painting. The + QCheckBox draws itself as follows: + + \snippet doc/src/snippets/code/doc_src_styles.cpp 2 + + QCommonStyle handles the CE_CheckBox element. The QCheckBox + has two sub elements: SE_CheckBoxIndicator (the checked indicator) + and SE_CheckBoxContents (the contents, which is used for the + checkbox label). QCommonStyle also implements these sub element + bounding rectangles. We have a look at the QCommonStyle code: + + \snippet doc/src/snippets/code/doc_src_styles.cpp 3 + + As can be seen from the code extract, the common style gets + the bounding rectangles of the two sub elements of + CE_CheckBox, and then draws them. If the checkbox has focus, + the focus frame is also drawn. + + The java style draws CE_CheckBoxIndicator, while QCommonStyle + handles CE_CheckboxLabel. We will examine each implementation and + start with CE_CheckBoxLabel: + + \snippet doc/src/snippets/code/doc_src_styles.cpp 4 + + \l{QStyle::}{visualAlignment()} adjusts the alignment of text + according to the layout direction. We then draw an icon if it + exists, and adjust the space left for the text. + \l{QStyle::}{drawItemText()} draws the text taking alignment, + layout direction, and the mnemonic into account. It also uses the + palette to draw the text in the right color. + + The drawing of labels often get somewhat involved. Luckily, it + can usually be handled by the base class. The java style + implements its own push button label since Java-contrary to + windows-center button contents also when the button has an icon. + You can examine that implementation if you need an example of + reimplementing label drawing. + + We take a look at the java implementation + of CE_CheckBoxIndicator in \c drawControl(): + + \snippet doc/src/snippets/javastyle.cpp 0 + + We first save the state of the painter. This is not always + necessary but in this case the QWindowsStyle needs the painter in + the same state as it was when PE_IndicatorCheckBox was called (We + could also set the state with function calls, of course). We then + use \c drawButtonBackground() to draw the background of the check + box indicator. This is a helper function that draws the background + and also the frame of push buttons and check boxes. We take a look + at that function below. We then check if the mouse is hovering + over the checkbox. If it is, we draw the frame java checkboxes + have when the box is not pressed down and the mouse is over it. + You may note that java does not handle tristate boxes, so we have + not implemented it. + + Here we use a png image for our indicator. We could also check + here if the widget is disabled. We would then have to use + another image with the indicator in the disabled color. + + \snippet doc/src/snippets/javastyle.cpp 1 + + We have seen how check boxes are styled in the java style from the + widget gets a paint request to the style is finished painting. To + learn in detail how each widget is painted, you need to go through + the code step-by-step as we have done here. However, it is + usually enough to know which style elements the widgets draw. The + widget builds a style option and calls on the style one or more + times to draw the style elements of which it consists. Usually, + it is also sufficient to know the states a widget can be in and the + other contents of the style option, i.e., what we list in the next + section. + + \section1 Widget Walkthrough + + In this section, we will examine how most of Qt's widgets are + styled. Hopefully, this will save you some time and effort while + developing your own styles and widgets. You will not find + information here that is not attainable elsewhere (i.e., by + examining the source code or the class descriptions for the style + related classes). + + We mostly use java style widgets as examples. The java style does not + draw every element in the element trees. This is because they are + not visible for that widget in the java style. We still make sure + that all elements are implemented in a way that conforms with the + java style as custom widgets might need them (this does not + exclude leaving implementations to QWindowsStyle though). + + The following is given for each widget: + + \list + \o A table with the members (variables, etc.) of its style option. + \o A table over the state flags (QStyle::StateFlag) that + can be set on the widget and when the states are set. + \o Its element tree (see section \l{The Style Elements}). + \o An image of the widget in which the elements are outlined. + \omit This is not written yet - probably never will be + either + \o List of style hints that should be checked for the + widget. + \o List of standard pixmaps that could be used by the + elements. + \endomit + \endlist + + The element tree contains the primitive, control, and complex + style elements. By doing a top-down traversal of the element tree, + you get the sequence in which the elements should be drawn. In the + nodes, we have written the sub element rectangles, sub control + elements, and pixel metrics that should be considered when drawing + the element of the node. + + Our approach on styling center on the drawing of the widgets. The + calculations of sub elements rectangles, sub controls, and pixel + metrics used \bold during drawing is only listed as contents in + the element trees. Note that there are rectangles and pixel + metrics that are only used by widgets. This leaves these + calculations untreated in the walkthrough. For instance, the + \l{QStyle::}{subControlRect()} and + \l{QStyle::}{sizeFromContents()} functions often call + \l{QStyle::}{subElementRect()} to calculate their bounding + rectangles. We could draw trees for this as well. However, how + these calculations are done is completely up to the individual + styles, and they do not have to follow a specific structure (Qt + does not impose a specific structure). You should still make sure + that you use the appropriate pixel metrics, though. To limit the + size of the document, we have therefore chosen not to include + trees or describe the calculations made by the Java (or any other) + style. + + You may be confused about how the different pixel metrics, sub + element rectangles, and sub control rectangles should be used when + examining the trees. If you are in doubt after reading the QStyle + enum descriptions, we suggest that you examine the QCommonStyle + and QWindowsStyle implementations. + + Some of the bounding rectangles that we outline in the widget + images are equal. Reasons for this are that some elements draw + backgrounds while others draw frames and labels. If in doubt, + check the description of each element in QStyle. Also, some + elements are there to layout, i.e., decide where to draw, other + elements. + + \section2 Common Widget Properties + + Some states and variables are common for all widgets. These are + set with QStyleOption::initFrom(). Not all elements use this function; + it is the widgets that create the style options, and for some + elements the information from \l{QStyleOption::}{initFrom()} is not + necessary. + + A table with the common states follows: + + \table 90% + \header + \o State + \o State Set When + \row + \o State_Enabled + \o Set if the widget is not disabled (see + QWidget::setEnabled()) + \row + \o State_Focus + \o Set if the widget has focus (see + QWidget::hasFocus()) + \row + \o State_KeyobordFocusChange + \o Set when the user changes focus with the keyboard + (see Qt::WA_KeyboardFocusChange) + \row + \o State_MouseOver + \o Set if the mouse cursor is over the widget + \row + \o State_Active + \o Set if the widget is a child of the active window. + \row + \o State_HasEditFocus + \o Set if the widget has the edit focus + \endtable + + The other common members for widgets are: + + \table 90% + \header + \o Member + \o Content + \row + \o rect + \o The bounding rectangle of the element to draw. This + is set to the widget bounding rectangle + (QWidget::rect()). + \row + \o direction + \o The layout direction; a value of the + Qt::LayoutDirection enum. + \row + \o palette + \o The QPalette to use when drawing the element. This + is set to the widgets palette (QWidget::palette()). + \row + \o fontMetrics + \o The QFontMetrics to use when drawing text on the + widget. + \endtable + + The complex style options (classes that inherit + QStyleOptionComplex) used for complex style elements share two + variables: \l{QStyleOptionComplex::}{subControls} and + \l{QStyleOptionComplex::}{activeSubControls}. Both variables are + an OR'ed combination of QStyle::SubControl enum values. They + indicate which sub controls the complex control consists of and + which of these controls are currently active. + + As mentioned, the style calculates the size of the widgets + contents, which the widgets calculate their size hints from. In + addition, complex controls also use the style to test which + sub-controls the mouse is over. + + \section2 Widget Reference + + Without further delay, we present the widget walkthrough; each + widget has its own sub-section. + + \section3 Push Buttons + + The style structure for push buttons is shown below. By doing a + top-down traversal of the tree, you get the sequence in which the + elements should be drawn. + + \image javastyle/pushbutton.png The style structure for push buttons + + The layout of the buttons, with regard element bounds, varies from + style to style. This makes it difficult to show conceptual images + of this. Also, elements may - even be intended to - have the same + bounds; the PE_PushButtonBevel, for instance, is used in + QCommonStyle to draw the elements that contains it: + PE_FrameDefaultButton, PE_FrameButtonBevel, and + PE_PanelButtonCommand, all of which have the same bounds in common + and windows style. PE_PushButtonBevel is also responsible for + drawing the menu indicator (QCommonStyle draws + PE_IndicatorArrowDown). + + An image of a push button in the java style that show the bounding + rectangles of the elements is given below. Colors are used to + separate the bounding rectangles in the image; they do not fill + any other purpose. This is also true for similar images for the + other widgets. + + \image javastyle/button.png + + The java style, as well as all other styles implemented in Qt, + does not use PE_FrameButtonBevel. It is usual that a button + with a PE_DefaultFrame adjusts the PE_PanelButtonCommand's + rectangle by PM_ButtonDefaultIndicator. The CE_PushButtonLabel + is found by adjusting the rect by PM_DefaultFrameWidth. + + We will now examine the style option for push + buttons - QStyleOptionButton. A table for the states that + QPushButton can set on the style option follows: + + \table 90% + \header + \o State + \o State Set When + \row + \o State_Sunken + \o Button is down or menu is pressed shown + \row + \o State_On + \o Button is checked + \row + \o State_Raised + \o Button is not flat and not pressed down + \endtable + + Other members of QStyleOptionButton is: + + \table 90% + \header + \o Member + \o Content + \row + \o features + \o Flags of the QStyleOptionButton::ButtonFeatures enum, + which describes various button properties (see enum) + \row + \o icon + \o The buttons QIcon (if any) + \row + \o iconSize + \o The QSize of the icon + \row + \o text + \o a QString with the buttons text + \endtable + + \section3 Check and Radio Buttons + + The structures for radio and check buttons are identical. + We show the structure using QCheckBox element and pixel + metric names: + + \image javastyle/checkbox.png + + QStyleOptionButton is used as the style option for both check + and radio buttons. We first give a table of the states that + can be set in the option: + + \table 90% + \header + \o State + \o State Set When + \row + \o State_sunken + \o The box is pressed down + \row + \o State_NoChange + \o The box is partially checked (for tristate + checkboxes.) + \row + \o State_On + \o The box is checked + \row + \o State_Off + \o The box is unchecked + \endtable + + See \l{Push Buttons} for a table over other members in the + QStyleOptionButtonClass. + + \section3 Tabs + + In Qt, QTabBar uses the style to draw its tabs. Tabs exist either + in a QTabWidget, which contains a QTabBar, or as a separate bar. + If the bar is not part of a tab widget, it draws its own base. + + QTabBar lays out the tabs, so the style does not have control over + tab placement. However, while laying out its tabs, the bar asks + the style for PM_TabBarTabHSpace and PM_TabBarTabVSpace, which is + extra width and height over the minimum size of the tab bar tab + label (icon and text). The style can also further influence the + tab size before it is laid out, as the tab bar asks for + CT_TabBarTab. The bounding rectangle of the bar is decided by the + tab widget when it is part of the widget (still considering + CT_TabBarTab). + + The tab bar is responsible for drawing the buttons that appear on + the tab bar when all tabs do not fit. Their placement is not + controlled by the style, but the buttons are \l{QToolButton}s + and are therefore drawn by the style. + + Here is the style structure for QTabWidget and QTabBar: + + \image javastyle/tab.png + + The dotted lines indicate that the QTabWidget contains a tab bar, + but does not draw it itself, that QTabBar only draws its base line + when not part of a tab widget, and that the tab bar keeps two tool + buttons that scroll the bar when all tabs do not fit; see \l{Tool + Buttons} for their element tree. Also note that since the buttons + are children of the tab bar, they are drawn after the bar. The + tabs bounding rectangles overlap the base by PM_TabBarBaseOverlap. + + Here is a tab widget in the java style: + + \image javastyle/tabwidget.png + + In the java style (and also windows), the tab bar shape and label + have the same bounding rectangle as CE_TabBarTab. Notice that the + tabs overlap with the tab widget frame. The base of the tab bar + (if drawn) is the area where the tabs and frame overlap. + + The style option for tabs (QStyleOptionTab) contains the necessary + information for drawing tabs. The option contains the position of + the tab in the tab bar, the position of the selected tab, the + shape of the tab, the text, and icon. After Qt 4.1 the option + should be cast to a QStyleOptionTabV2, which also contains the + icons size. + + As the java style tabs don't overlap, we also present an image of + a tab widget in the windows style. Note that if you want the tabs + to overlap horizontally, you do that when drawing the tabs in + CE_TabBarTabShape; the tabs bounding rectangles will not be + altered by the tab bar. The tabs are drawn from left to right in a + north tab bar shape, top to bottom in an east tab bar shape, etc. + The selected tab is drawn last, so that it is easy to draw it over + the other tabs (if it is to be bigger). + + \image javastyle/windowstabimage.png + + A table of the states a tab bar can set on its tabs follows: + + \table 90% + \header + \o State + \o State Set When + \row + \o State_Sunken + \o The tab is pressed on with the mouse. + \row + \o State_Selected + \o If it is the current tab. + \row + \o State_HasFocus + \o The tab bar has focus and the tab is selected + \endtable + + Note that individual tabs may be disabled even if the tab bar + is not. The tab will be active if the tab bar is active. + + Here follows a table of QStyleOptionTabV2's members: + + \table 90% + \header + \o Member + \o Content + \row + \o cornerWidgets + \o Is flags of the CornerWidget enum, which indicate + if and which corner widgets the tab bar has. + \row + \o icon + \o The QIcon of the tab + \row + \o iconSize + \o The QSize of the icon + \row + \o position + \o A TabPosition enum value that indicates the tabs + position on the bar relative to the other tabs. + \row + \o row + \o holds which row the tab is in + \row + \o selectedPosition + \o A value of the SelectedPosition enum that indicates + whether the selected tab is adjacent to or is the + tab. + \row + \o shape + \o A value of the QTabBar::Shape enum indication + whether the tab has rounded or triangular corners + and the orientation of the tab. + \row + \o text + \o The tab text + \endtable + + The frame for tab widgets use QStyleOptionTabWidgetFrame as + style option. We list its members here. It does not have + states set besides the common flags. + + \table 90% + \header + \o Member + \o content + \row + \o leftCornerWidgetSize + \o The QSize of the left corner widget (if any). + \row + \o rightCornerWidgetSize + \o The QSize of the right corner widget (if any). + \row + \o lineWidth + \o holds the line with for drawing the panel. + \row + \o midLineWith + \o this value is currently always 0. + \row + \o shape + \o The shape of the tabs on the tab bar. + \row + \o tabBarSize + \o The QSize of the tab bar. + \endtable + + \section3 Scroll Bars + + Here is the style structure for scrollBars: + + \image javastyle/scrollbar.png + + QScrollBar simply creates its style option and then draws + CC_ScrollBar. Some styles draw the background of add page and sub + page with PE_PanelButtonBevel and also use indicator arrows to + draw the arrows in the nest and previous line indicators; we have + not included these in the tree as their use is up to the + individual style. The style's PM_MaximumDragDistance is the + maximum distance in pixels the mouse can move from the bounds + of the scroll bar and still move the handle. + + Here is an image of a scrollbar in the java style: + + \image javastyle/scrollbarimage.png + + You may notice that the scrollbar is slightly different from + Java's as it has two line up indicators. We have done this to show + how that you can have two separate bounding rectangles for a + single sub control. The scroll bar is an example of a widget that + is entirely implemented by the java style - neither QWindowsStyle + nor QCommonStyle are involved in the drawing. + + We have a look at the different states a scroll bar can set on + the style option: + + \table 90% + \header + \o State + \o State Set When + \row + \o State_Horizontal + \o The scroll bar is horizontal + \endtable + + The style option of QScrollBar is QStyleOptionSlider. Its + members are listed in the following table. The option is used + by all \l{QAbstractSlider}s; we only describe the members + relevant for scroll bars here. + + \table 90% + \header + \o Member + \o Content + \row + \o maximum + \o the maximum value of the scroll bar + \row + \o minimum + \o the minimum value of the scroll bar + \row + \o notchTarget + \o the number of pixels between notches + \row + \o orientation + \o a value of the Qt::Orientation enum that specifies + whether the scroll bar is vertical or horizontal + \row + \o pageStep + \o the number to increase or decrease the sliders + value (relative to the size of the slider and its value + range) on page steps. + \row + \o singleStep + \o the number to increase or decrease the sliders + value on single (or line) steps + \row + \o sliderValue + \o The value of the slider + \row + \o sliderPosition + \o the position of the slider handle. This is the same + as \c sliderValue if the scroll bar is + QAbstractSlider::tracking. If not, the scroll + bar does not update its value before the mouse + releases the handle. + \row + \o upsideDown + \o holds the direction in which the scroll bar + increases its value. This is used instead of + QStyleOption::direction for all abstract sliders. + \endtable + + \section3 Sliders + + When calculating the sliders size hint, PM_SliderTickness and + PM_SliderLength is queried from the style. As with scroll bars, + the QSlider only lets the user move the handle if the mouse is + within PM_MaximumDragDistance from the slider bounds. When it + draws itself it creates the style option and calls \c + drawComplexControl() with CC_Slider: + + \image javastyle/slider.png + + We also show a picture of a slider in the java style. We show + the bounding rectangles of the sub elements as all drawing is done + in CC_Slider. + + \image javastyle/sliderimage.png + + QSlider uses QStyleOptionSlider as all \l{QAbstractSlider}s do. We + present a table with the members that affect QSlider: + + \table 90% + \header + \o Member + \o Content + \row + \o maximum + \o the maximum value of the slider + \row + \o minimum + \o the minimum value of the slider + \row + \o notchTarget + \o this is the number of pixels between each notch + \row + \o orientation + \o a Qt::Orientation enum value that gives whether the + slider is vertical or horizontal. + \row + \o pageStep + \o a number in slider value to increase or decrease + for page steps + \row + \o singleStep + \o the number to increase or decrease the sliders + value on single (or line) steps. + \row + \o sliderValue + \o the value of the slider. + \row + \o sliderPosition + \o the position of the slider given as a slider value. + This will be equal to the \c sliderValue if the + slider is \l{QAbstractSlider::}{tracking}; if + not, the sliders value will not change until the handle is + released with the mouse. + \row + \o upsideDown + \o this member is used instead of QStyleOption::direction + for all abstract sliders. + \endtable + + You should note that the slider does not use direction for + reverse layouts; it uses \c upsideDown. + + \section3 Spin Boxes + + When QSpinBox paints itself it creates a QStyleOptionSpinBox and + asks the style to draw CC_SpinBox. The edit field is a line + edit that is a child of the spin box. The dimensions of the + field is calculated by the style with SC_SpinBoxEditField. + + Here follows the style tree for spin boxes. It is not + required that a style uses the button panel primitive to paint + the indicator backgrounds. You can see an image below the tree + showing the sub elements in QSpinBox in the java style. + + \image javastyle/spinbox.png + + \image javastyle/spinboximage.png + + The QStyleOptionSpinBox, which is the style option for spin + boxes. It can set the following states on the spin box.: + + \table 90% + \header + \o State + \o State Set When + \row + \o State_Sunken + \o Is set if one of the sub controls CC_SpinUp or + CC_SpinDown is pressed on with the mouse. + \endtable + + The rest of the members in the spin boxes style options are: + + \table 90% + \header + \o Property + \o Function + \row + \o frame + \o boolean that is true if the spin box is to draw a + frame. + \row + \o buttonSymbols + \o Value of the ButtonSymbols enum that decides the + symbol on the up/down buttons. + \row + \o stepEnabled + \o A value of the StepEnabled indication which of the + spin box buttons are pressed down. + \endtable + + \section3 Title Bar + + The title bar complex control, CC_TitleBar, is used to draw + the title bars of internal windows in QMdiArea. It typically + consists of a window title and close, minimize, system menu, and + maximize buttons. Some styles also provide buttons for shading + the window, and a button for context sensitive help. + + The bar is drawn in CC_TitleBar without using any sub elements. + How the individual styles draw their buttons is individual, but + there are standard pixmaps for the buttons that the style should + provide. + + \image javastyle/titlebar.png + + In an image over a title bar in the java style, we show the + bounding rectangles of the sub elements supported by the java style + (all of which are drawn with standard pixmaps). It is usual to + draw the button backgrounds using PE_PanelButtonTool, but it's no + rule. + + \image javastyle/titlebarimage.png + + The style option for title bars is QStyleOptionTitleBar. It's + members are: + + \table 90% + \header + \o Member + \o Content + \row + \o icon + \o The title bars icon + \row + \o text + \o the text for the title bar's label + \row + \o windowFlags + \o flags of the Qt::WindowFlag enum. The window flags + used by QMdiArea for window management. + \row + \o titleBarState + \o this is the QWidget::windowState() of the window + that contains the title bar. + \endtable + + \section3 Combo Box + + A QComboBox uses the style to draw the button and label of + non-editable boxes with CC_ComboBox and CE_ComboBoxLabel. + + The list that pops up when the user clicks on the combo box is + drawn by a \l{Delegate Classes}{delegate}, which we do not cover + in this overview. You can, however, use the style to control the + list's size and position with the sub element + SC_ComboBoxListBoxPopup. The style also decides where the edit + field for editable boxes should be with SC_ComboBoxEditField; the + field itself is a QLineEdit that is a child of the combo box. + + \image javastyle/combobox.png + + We show an image over a java style combo box in which we have + outlined its sub elements and sub element rectangles: + + \image javastyle/comboboximage.png + + Java combo boxes do not use the focus rect; it changes its + background color when it has focus. The SC_ComboBoxEdit field is + used both by QComboBox to calculate the size of the edit field and + the style for calculating the size of the combo box label. + + The style option for combo boxes is QStyleOptionComboBox. It + can set the following states: + + \table 90% + \header + \o State + \o Set When + \row + \o State_Selected + \o The box is not editable and has focus + \row + \o State_Sunken + \o SC_ComboBoxArrow is active + \row + \o State_on + \o The container (list) of the box is visible + \endtable + + The style options other members are: + + \table + \header + \o Member + \o Content + \row + \o currentIcon + \o the icon of the current (selected) item of the + combo box. + \row + \o currentText + \o the text of the current item in the box. + \row + \o editable + \o holds whether the combo box is editable or not + \row + \o frame + \o holds whether the combo box has a frame or not + \row + \o iconSize + \o the size of the current items icon. + \row + \o popupRect + \o the bounding rectangle of the combo box's popup + list. + \endtable + + \section3 Group Boxes + + When calculating the size hint, QGroupBox fetches three pixel + metrics from the style: PM_IndicatorWidth, + PM_CheckBoxLabelSpacing, and PM_IndicatorHeight. QGroupBox has + the following style element tree: + + \image javastyle/groupbox.png + + Qt does not impose restrictions on how the check box is drawn; the + java style draws it with CE_IndicatorCheckBox. See \l{Check and + Radio Buttons} for the complete tree. + + We also give an image of the widget with the sub controls and + sub control rectangles drawn: + + \image javastyle/groupboximage.png + + The style option for group boxes are QStyleOptionGroupBox. The + following states can be set on it: + + \table 90% + \header + \o State + \o Set When + \row + \o State_On + \o The check box is checked + \row + \o State_Sunken + \o The checkbox is pressed down + \row + \o State_Off + \o The check box is unchecked (or there is no check box) + \endtable + + The remaining members of QStyleOptionGroupBox are: + + \table + \header + \o Member + \o Content + \row + \o features + \o flags of the QStyleOptionFrameV2::FrameFeatures + enum describing the frame of the group box. + \row + \o lineWidth + \o the line width with which to draw the panel. This + is always 1. + \row + \o text + \o the text of the group box. + \row + \o textAlignment + \o the alignment of the group box title + \row + \o textColor + \o the QColor of the text + \endtable + + \section3 Splitters + + As the structure of splitters are simple and do not contain any + sub elements, we do not include image of splitters. CE_Splitter + does not use any other elements or metrics. + + For its style option, Splitters uses the base class QStyleOption. + It can set the following state flags on it: + + \table 90% + \header + \o State + \o Set When + \row + \o State_Horizontal + \o Set if it is a horizontal splitter + \endtable + + QSplitter does not use \l{QStyleOption::}{initFrom()} to set up its + option; it sets the State_MouseOver and State_Disabled flags + itself. + + \section3 Progress Bar + + The CE_ProgressBar element is used by QProgressBar, and it is the + only element used by this widget. We start with looking at the + style structure: + + \image javastyle/progressbar.png + + Here is a progress bar in the windows style (the java style + bounding rectangles are equal): + + \image javastyle/progressbarimage.png + + The style option for QProgressBar is QStyleOptionProgressBarV2. + The bar does not set any state flags, but the other members of the + option are: + + \table 90% + \header + \o Member + \o Content + \row + \o minimum + \o The minimum value of the bar + \row + \o maximum + \o The maximum value of the bar + \row + \o progress + \o The current value of the bar + \row + \o textAlignment + \o How the text is aligned in the label + \row + \o textVisible + \o Whether the label is drawn + \row + \o text + \o The label text + \row + \o orientation + \o Progress bars can be vertical or horizontal + \row + \o invertedAppearance + \o The progress is inverted (i.e., right to left in a + horizontal bar) + \row + \o bottomToTop + \o Boolean that if true, turns the label of vertical + progress bars 90 degrees. + \endtable + + \section3 Tool Buttons + + Tool buttons exist either independently or as part of tool bars. + They are drawn equally either way. The QToolButton draws only one + style element: CC_ToolButton. + + As you must be used to by now (at least if you have read this + document sequentially), we have a tree of the widget's style + structure: + + \image javastyle/toolbutton.png + + Note that PE_FrameButtonTool and PE_IndicatorArrowDown are + included in the tree as the java style draws them, but they can + safely be omitted if you prefer it. The structure may also be + different. QWindowsStyle, for instance, draws both + PE_IndicatorButtonDropDown and PE_IndicatorArrowDown in + CE_ToolButton. + + We also have an image of a tool button where we have outlined + the sub element bounding rectangles and sub controls. + + \image javastyle/toolbuttonimage.png + + Here is the states table for tool buttons: + + \table 90% + \header + \o State + \o Set When + \row + \o State_AutoRise + \o the tool button has the autoRise property set + \row + \o State_raised + \o the button is not sunken (i.e., by being checked or + pressed on with the mouse). + \row + \o State_Sunken + \o the button is down + \row + \o State_On + \o the button is checkable and checked. + \endtable + + QStyleOptionToolButton also contains the following members: + + \table + \header + \o Member + \o Content + \row + \o arrowType + \o a Qt::ArrowType enum value, which contains the + direction of the buttons arrow (if an arrow is to + be used in place of an icon) + \row + \o features + \o flags of the QStyleOptionToolButton::ButtonFeature + enum describing if the button has an arrow, a menu, + and/or has a popup-delay. + \row + \o font + \o the QFont of the buttons label + \row + \o icon + \o the QIcon of the tool button + \row + \o iconSize + \o the icon size of the button's icon + \row + \o pos + \o the position of the button, as given by + QWidget::pos() + \row + \o text + \o the text of the button + \row + \o toolButtonStyle + \o a Qt::ToolButtonStyle enum value which decides + whether the button shows the icon, the text, or both. + \endtable + + \section3 Toolbars + + Toolbars are part of the \l{QMainWindow}{main window framework} + and cooperates with the QMainWindow to which it belongs while it + builds its style option. A main window has 4 areas that toolbars + can be placed in. They are positioned next to the four sides of + the window (i.e., north, south, west, and east). Within each area + there can be more than one line of toolbars; a line consists of + toolbars with equal orientation (vertical or horizontal) placed + next to each other. + + \l{QToolbar}{QToolbar}s in Qt consists of three elements + CE_ToolBar, PE_IndicatorToolBarHandle, and + PE_IndicatorToolBarSeparator. It is QMainWindowLayout that + calculates the bounding rectangles (i.e., position and size of the + toolbars and their contents. The main window also uses the \c + sizeHint() of the items in the toolbars when calculating the size + of the bars. + + Here is the element tree for QToolBar: + + \image javastyle/toolbar.png + + The dotted lines indicate that the QToolBar keeps an instance of + QToolBarLayout and that QToolBarSeparators are kept by + QToolBarLayout. When the toolbar is floating (i.e., has its own + window) the PE_FrameMenu element is drawn, else QToolbar draws + CE_ToolBar. + + Here is an image of a toolbar in the java style: + + \image javastyle/toolbarimage.png + + QToolBarSaparator uses QStyleOption for their style option. It + sets the State_horizontal flag if the toolbar they live in is + horizontal. Other than that, they use \l{QStyleOption::}{initFrom()}. + + The style option for QToolBar is QStyleOptionToolBar. The only + state flag set (besides the common flags) is State_Horizontal + if the bar is horizontal (i.e., in the north or south toolbar area). + The member variables of the style option are: + + \table 90% + \header + \o Member + \o Content + \row + \o features + \o Holds whether the bar is movable in a value of the + ToolBarFeature, which is either Movable or None. + \row + \o lineWidth + \o The width of the tool bar frame. + \row + \o midLineWidth + \o This variable is currently not used and is always + 0. + \row + \o positionOfLine + \o The position of the toolbar line within the toolbar + area to which it belongs. + \row + \o positionWithinLine + \o The position of the toolbar within the toolbar line. + \row + \o toolBarArea + \o The toolbar area in which the toolbar lives. + \endtable + + \section3 Menus + + Menus in Qt are implemented in QMenu. The QMenu keeps a list of + action, which it draws as menu items. When QMenu receives paint + events ,it calculates the size of each menu item and draws them + individually with CE_MenuItem. (Menu items do not have a separate + element for their label (contents), so all drawing is done in + CE_MenuItem. The menu also draws the frame of the menu with + PE_FrameMenu. It also draws CE_MenuScroller if the style supports + scrolling. CE_MenuTearOff is drawn if the menu is to large for its + bounding rectangle. + + In the style structure tree, we also include QMenu as it also does + styling related work. The bounding rectangles of menu items are + calculated for the menus size hint and when the menu is displayed + or resized. + + \image javastyle/menu.png + + The CE_MenuScroller and CE_MenuTearOff elements are handled by + QCommonStyle and are not shown unless the menu is to large to fit + on the screen. PE_FrameMenu is only drawn for pop-up menus. + + QMenu calculates rectangles based on its actions and calls + CE_MenuItem and CE_MenuScroller if the style supports that. + + It is also usual to use PE_IndicatorCheckBox (instead of using + PE_IndicatorMenuCheckMark) and PE_IndicatorRadioButton for drawing + checkable menu items; we have not included them in the style tree + as this is optional and varies from style to style. + + \image javastyle/menuimage.png + + The style option for menu items is QStyleOptionMenuItem. The + following tables describe its state flags and other members. + + \table 90% + \header + \o State + \o Set When + \row + \o State_Selected + \o The mouse is over the action and the action is not + a separator. + \row + \o State_Sunken + \o The mouse is pressed down on the menu item. + \row + \o State_DownArrow + \o Set if the menu item is a menu scroller and it scrolls + the menu downwards. + \endtable + + \table 90% + \header + \o Member + \o Content + \row + \o checkType + \o A value of the \l{QStyleOptionMenuItem::}{CheckType} enum, + which is either NotCheckable, Exclusive, or + NonExclusive. + \row + \o checked + \o Boolean that is true if the menu item is checked. + \row + \o font + \o The QFont to use for the menu item's text. + \row + \o icon + \o the QIcon of the menu item. + \row + \o maxIconWidth + \o The maximum width allowed for the icon + \row + \o menuHasChecableItem + \o Boolean which is true if at least one item in the + menu is checkable. + \row + \o menuItemType + \o The type of the menu item. This a value of the + \l{QStyleOptionMenuItem::}{MenuItemType}. + \row + \o menuRect + \o The bounding rectangle for the QMenu that the menu + item lives in. + \row + \o tabWidth + \o This is the distance between the text of the menu + item and the shortcut. + \row + \o text + \o The text of the menu item. + \endtable + + The setup of the style option for CE_MenuTearOff and + CE_MenuScroller also uses QStyleOptionMenuItem; they only set the + \c menuRect variable in addition to the common settings with + QStyleOption's \l{QStyleOption::}{initFrom()}. + + \section3 Menu Bar + + QMenuBar uses the style to draw each menu bar item and the empty + area of the menu bar. The pull-down menus themselves are + \l{QMenu}s (see \l{Menus}). The style element tree for the menu + bar follows: + + \image javastyle/menubar.png + + The panel and empty area is drawn after the menu items. The + QPainter that the QMenuBar sends to the style has the bounding + rectangles of the items clipped out (i.e., clip region), so you + don't need to worry about drawing over the items. The pixel + metrics in QMenuBar is used when the bounding rectangles of the + menu bar items are calculated. + + \image javastyle/menubarimage.png + + QStyleOptionMenuItem is used for menu bar items. The members that + are used by QMenuBar is described in the following table: + + \table + \header + \o Member + \o Content + \row + \o menuRect + \o the bounding rectangle of the entire menu bar to + which the item belongs. + \row + \o text + \o the text of the item + \row + \o icon + \o the icon of the menu item (it is not common that + styles draw this icon) + \endtable + + QStyleOptionMenuItem is also used for drawing CE_EmptyMenuBarArea. + + QStyleOptionFrame is used for drawing the panel frame The + \l{QStyleOptionFrame::}{lineWidth} is set to PM_MenuBarPanelWidth. + The \l{QStyleOptionFrame::}{midLineWidth} is currently always set + to 0. + + \section3 Item View Headers + + It is the style that draws the headers of Qt's item views. The + item views keeps the dimensions on individual sections. Also + note that the delegates may use the style to paint decorations + and frames around items. QItemDelegate, for instance, draws + PE_FrameFocusRect and PE_IndicatorViewItemCheck. + + \image javastyle/header.png + + Here is a QTableWidget showing the bounding rects of a Java + header: + + \image javastyle/headerimage.png + + The QHeaderView uses CT_HeaderSection, PM_HeaderMargin and + PM_HeaderGripMargin for size and hit test calculations. The + PM_HeaderMarkSize is currently not used by Qt. QTableView draws + the button in the top-left corner (i.e., the area where the + vertical and horizontal headers intersect) as a CE_Header. + + The style option for header views is QStyleOptionHeader. The view + paints one header section at a time, so the data is for the + section being drawn. Its contents are: + + \table 90% + \header + \o Member + \o Content + \row + \o icon + \o the icon of the header (for section that is being + drawn). + \row + \o iconAlignment + \o the alignment (Qt::Alignment) of the icon in the header. + \row + \o orientation + \o a Qt::Orientation value deciding whether the header + is the horizontal header above the view or the + vertical header on the left. + \row + \o position + \o a QStyleOptionHeader::SectionPosition value + giving the header section's position relative to + the other sections. + \row + \o section + \o holds the section that is being drawn. + \row + \o selectedPosition + \o a QStyleOptionHeader::SelectedPosition value giving + the selected section's position relative to the + section that is being painted. + \row + \o sortIndicator + \o a QStyleOptionHeader::SortIndicator value that + describes the direction in which the section's sort + indicator should be drawn. + \row + \o text + \o the text of the currently drawn section. + \row + \o textAlignment + \o the Qt::Alignment of the text within the + headersection. + \endtable + + \section3 Tree Branch Indicators + + The branch indicators in a tree view is drawn by the style with + PE_IndicatorBranch. We think of indicators here as the indicators + that describe the relationship of the nodes in the tree. The + generic QStyleOption is sent to the style for drawing this + elements. The various branch types are described by states. Since + there are no specific style option, we simply present the states + table: + + \table 90% + \header + \o State + \o Set When + \row + \o State_Sibling + \o the node in the tree has a sibling (i.e., there is + another node in the same column). + \row + \o State_Item + \o this branch indicator has an item. + \row + \o State_Children + \o the branch has children (i.e., a new sub-tree can + be opened at the branch). + \row + \o State_Open + \o the branch indicator has an opened sub-tree. + \endtable + + The tree view (and tree widget) use the style to draw the branches + (or nodes if you will) of the tree. + + QStyleOption is used as the style for PE_IndicatorBranch has state + flags set depending on what type of branch it is. + + Since there is no tree structure for branch indicators, we only + present an image of a tree in the java style. Each state is marked + in the image with a rectangle in a specific color (i.e., these + rectangles are not bounding rectangles). All combinations of + states you must be aware of are represented in the image. + + \image javastyle/branchindicatorimage.png + + \section3 Tool Boxes + + PM_SmallIconSize for sizeHints. + + QToolBox is a container that keeps a collection of widgets. It has + one tab for each widget and display one of them at a time. The + tool box lays the components it displays (the tool box buttons + and selected widget) in a QVBoxLayout. The style tree for tool + boxes looks like this: + + \image javastyle/toolbox.png + + We show an image of a tool box in the Plastique style: + + \image javastyle/toolboximage.png + + All elements have the same bounding rectangles in the + Plastique as well as the other Qt built-in styles. + + The style option for tool boxes is QStyleOptionToolBox. It + contains the text and icon of the tool box contents. The only + state set by QToolBox is State_Sunken, which is set when the user + presses a tab down with the mouse. The rest of the + QStyleOptionToolBox members are: + + \table 90% + \header + \o Member + \o Content + \row + \o icon + \o the icon on the toolbox tab + \row + \o text + \o the text on the toolbox tab + \endtable + + \section3 Size Grip + + The size grip calculates its size hint with CT_SizeGrip. The pixel + metric PM_SizeGripSize is currently unused by Qt. The element tree + for and an image in the Plastique style of QSizeGrip follows: + + \image javastyle/sizegrip.png + + \image javastyle/sizegripimage.png + + We show the size grip in a \l{QMainWindow}'s bottom right + corner. + + The size grip style option, QStyleOptionSizeGrip, have one + member except the common members from QStyleOption: + + \table 90% + \header + \o Member + \o Content + \row + \o corner + \o a Qt::Corner value that describe which corner in a + window (or equivalent) the grip is located. + \endtable + + \section3 Rubber Band + + The \l{QRubberBand}'s style tree consists of two nodes. + + \image javastyle/rubberband.png + + We present an image of a Java style window being moved in a + QMdiArea with a rubber band: + + \image javastyle/rubberbandimage.png + + The style option for rubber bands is QStyleOptionRubberBand. + Its members are: + + \table + \header + \o Member + \o Content + \row + \o opaque + \o boolean that is true if the rubber band must be + drawn in an opaque style (i.e., color) + \row + \o shape + \o a QRubberBand::Shape enum value that holds the + shape of the band (which is either a rectangle or a + line) + \endtable + + \section3 Dock Widgets + + When the dock widget lays out its contents it asks the style for + these pixel metrics: PM_DockWidgetSeparatorExtent, + PM_DockWidgetTitleBarButtonMargin, PM_DockWidgetFrameWidth, and + PM_DockWidgetTitleMargin. It also calculates the bounding + rectangles of the float and close buttons with + SE_DockWidgetCloseButton and SE_DockWidgetFloatButton. + + \image javastyle/dockwidget.png + + The dotted lines indicate that the sender keeps instances of the + recipient of the arrow (i.e., it is not a style element to draw). + The dock widget only draws PE_frameDockWidget when it is detached + from its main window (i.e., it is a top level window). If it is + docked it draws the indicator dock widget resize handle. We show a + dock widget in both docked and floating state in the plastique + style: + + \image javastyle/dockwidgetimage.png + + The style option is QStyleOptionDockWidget: + + \table 90% + \header + \o Member + \o Content + \row + \o closeable + \o boolean that holds whether the dock window can be + closed + \row + \o floatable + \o boolean that holds whether the dock window can + float (i.e., detach from the main window in which + it lives) + \row + \o movable + \o boolean that holds whether the window is movable + (i.e., can move to other dock widget areas) + \row + \o title + \o the title text of the dock window + \endtable + + For the buttons, QStyleOptionButton is used (see \l{Tool Buttons} + for content description). The dock widget resize handle has a + plain QStyleOption. +*/ diff --git a/doc/src/widgets/widgets-and-layouts/stylesheet.qdoc b/doc/src/widgets/widgets-and-layouts/stylesheet.qdoc new file mode 100644 index 0000000000..80376b40a1 --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/stylesheet.qdoc @@ -0,0 +1,3963 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page stylesheet.html + \title Qt Style Sheets + \brief How to use style sheets to customize the appearance of widgets. + + \ingroup frameworks-technologies + \ingroup qt-basic-concepts + \ingroup qt-gui-concepts + + \previouspage {Styles and Style Aware Widgets}{Styles} + \contentspage Widgets and Layouts + \nextpage The Style Sheet Syntax + + \keyword style sheet + \keyword stylesheet + + Qt Style Sheets are a powerful mechanism that allows you to + customize the appearance of widgets, in addition to what is + already possible by subclassing QStyle. The concepts, + terminology, and syntax of Qt Style Sheets are heavily inspired + by HTML \l{http://www.w3.org/Style/CSS/}{Cascading Style Sheets + (CSS)} but adapted to the world of widgets. + + Topics: + + \list + \i \l{Overview} + \i \l{The Style Sheet Syntax} + \i \l{Qt Designer Integration} + \i \l{Customizing Qt Widgets Using Style Sheets} + \i \l{Qt Style Sheets Reference} + \i \l{Qt Style Sheets Examples} + \endlist + + \target overview + \section1 Overview + + Styles sheets are textual specifications that can be set on the + whole application using QApplication::setStyleSheet() or on a + specific widget (and its children) using + QWidget::setStyleSheet(). If several style sheets are set at + different levels, Qt derives the effective style sheet from all + of those that are set. This is called cascading. + + For example, the following style sheet specifies that all + \l{QLineEdit}s should use yellow as their background color, and + all \l{QCheckBox}es should use red as the text color: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 0 + + For this kind of customization, style sheets are much more + powerful than QPalette. For example, it might be tempting to set + the QPalette::Button role to red for a QPushButton to obtain a + red push button. However, this wasn't guaranteed to work for all + styles, because style authors are restricted by the different + platforms' guidelines and (on Windows XP and Mac OS X) by the + native theme engine. + + Style sheets let you perform all kinds of customizations that are + difficult or impossible to perform using QPalette alone. If you + want yellow backgrounds for mandatory fields, red text for + potentially destructive push buttons, or fancy check boxes, style + sheets are the answer. + + Style sheets are applied on top of the current \l{QStyle}{widget + style}, meaning that your applications will look as native as + possible, but any style sheet constraints will be taken into + consideration. Unlike palette fiddling, style sheets offer + guarantees: If you set the background color of a QPushButton to be + red, you can be assured that the button will have a red background + in all styles, on all platforms. In addition, \l{Qt Designer} + provides style sheet integration, making it easy to view the effects + of a style sheet in different \l{QStyle}{widget styles}. + + In addition, style sheets can be used to provide a distinctive + look and feel for your application, without having to subclass + QStyle. For example, you can specify arbitrary images for radio + buttons and check boxes to make them stand out. Using this + technique, you can also achieve minor customizations that would + normally require subclassing several style classes, such as + specifying a \l{QStyle::styleHint()}{style hint}. The + \l{widgets/stylesheet}{Style Sheet} example depicted below defines + two distinctive style sheets that you can try out and modify at + will. + + \table + \row \o \inlineimage stylesheet-coffee-xp.png + \o \inlineimage stylesheet-pagefold.png + \row \o Coffee theme running on Windows XP + \o Pagefold theme running on Windows XP + \endtable + + \table + \row \o \inlineimage stylesheet-coffee-cleanlooks.png + \o \inlineimage stylesheet-pagefold-mac.png + \row \o Coffee theme running on Ubuntu Linux + \o Pagefold theme running on Mac OS X + \endtable + + When a style sheet is active, the QStyle returned by QWidget::style() + is a wrapper "style sheet" style, \e not the platform-specific style. The + wrapper style ensures that any active style sheet is respected and + otherwise forwards the drawing operations to the underlying, + platform-specific style (e.g., QWindowsXPStyle on Windows XP). + + Since Qt 4.5, Qt style sheets fully supports Mac OS X. + + \warning Qt style sheets are currently not supported for custom QStyle + subclasses. We plan to address this in some future release. +*/ + +/*! + \page stylesheet-syntax.html + \contentspage {Qt Style Sheet}{Contents} + \previouspage Qt Style Sheet + \nextpage Qt Designer Integration + \title The Style Sheet Syntax + + Qt Style Sheet terminology and syntactic rules are almost + identical to those of HTML CSS. If you already know CSS, you can + probably skim quickly through this section. + + \tableofcontents + + \section1 Style Rules + + Style sheets consist of a sequence of style rules. A \e{style + rule} is made up of a selector and a declaration. The + \e{selector} specifies which widgets are affected by the rule; + the \e{declaration} specifies which properties should be set on + the widget. For example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 1 + + In the above style rule, \c QPushButton is the selector and \c{{ + color: red }} is the declaration. The rule specifies that + QPushButton and its subclasses (e.g., \c MyPushButton) should use + red as their foreground color. + + Qt Style Sheet is generally case insensitive (i.e., \c color, + \c Color, \c COLOR, and \c cOloR refer to the same property). + The only exceptions are class names, + \l{QObject::setObjectName()}{object names}, and Qt property + names, which are case sensitive. + + Several selectors can be specified for the same declaration, + using commas (\c{,}) to separate the selectors. For example, + the rule + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 2 + + is equivalent to this sequence of three rules: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 3 + + The declaration part of a style rule is a list of + \tt{\e{property}: \e{value}} pairs, enclosed in braces (\c{{}}) + and separated with semicolons. For example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 4 + + See the \l{List of Properties} section below for the list of + properties provided by Qt widgets. + + \section1 Selector Types + + All the examples so far used the simplest type of selector, the + Type Selector. Qt Style Sheets support all the + \l{http://www.w3.org/TR/REC-CSS2/selector.html#q1}{selectors + defined in CSS2}. The table below summarizes the most useful + types of selectors. + + \table 100% + \header + \o Selector + \o Example + \o Explanation + + \row + \o Universal Selector + \o \c * + \o Matches all widgets. + + \row + \o Type Selector + \o \c QPushButton + \o Matches instances of QPushButton and of its subclasses. + + \row + \o Property Selector + \o \c{QPushButton[flat="false"]} + \o Matches instances of QPushButton that are not + \l{QPushButton::}{flat}. You may use this selector to test + for any Qt \l{Qt's Property System}{property} that supports + QVariant::toString() (see the \l{QVariant::}{toString()} + function documentation for details). In addition, the + special \c class property is supported, for the name of the + class. + + This selector may also be used to test dynamic properties. + For more information on customization using dynamic properties, + refer to \l{Customizing Using Dynamic Properties}. + + Instead of \c =, you can also use \c ~= to test whether a + Qt property of type QStringList contains a given QString. + + \warning If the value of the Qt property changes after the + style sheet has been set, it might be necessary to force a + style sheet recomputation. One way to achieve this is to + unset the style sheet and set it again. + + \row + \o Class Selector + \o \c .QPushButton + \o Matches instances of QPushButton, but not of its subclasses. + + This is equivalent to \c{*[class~="QPushButton"]}. + + \row + \o ID \target ID Selector + Selector + \o \c{QPushButton#okButton} + \o Matches all QPushButton instances whose + \l{QObject::objectName}{object name} is \c okButton. + + \row + \o Descendant Selector + \o \c{QDialog QPushButton} + \o Matches all instances of QPushButton that are descendants + (children, grandchildren, etc.) of a QDialog. + + \row + \o Child Selector + \o \c{QDialog > QPushButton} + \o Matches all instances of QPushButton that are direct + children of a QDialog. + \endtable + + \section1 Sub-Controls + + For styling complex widgets, it is necessary to access subcontrols of the + widget, such as the drop-down button of a QComboBox or the up and down + arrows of a QSpinBox. Selectors may contain \e{subcontrols} that make it + possible to restrict the application of a rule to specific widget + subcontrols. For example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 5 + + The above rule styles the drop-down button of all \l{QComboBox}es. + Although the double-colon (\c{::}) syntax is reminiscent of CSS3 + Pseudo-Elements, Qt Sub-Controls differ conceptually from these and have + different cascading semantics. + + Sub-controls are always positioned with respect to another element - a + reference element. This reference element could be the widget or another + Sub-control. For example, the \l{Qt Style Sheets Reference#drop-down-sub} + {::drop-down} of a QComboBox is placed, by default, in the top right corner + of the Padding rectangle of the QComboBox. The + \l{Qt Style Sheets Reference#drop-down-sub}{::drop-down} is placed, + by default, in the Center of the Contents rectangle of the + \l{Qt Style Sheets Reference#drop-down-sub}{::drop-down} Sub-control. See + the \l{List of Stylable Widgets} below for the Sub-controls to use to + style a widget and their default positions. + + The origin rectangle to be used can be changed using the + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} + property. For example, if we want to place the drop-down in the margin + rectangle of the QComboBox instead of the default Padding rectangle, we + can specify: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 6 + + The alignment of the drop-down within the Margin rectangle is changed + using \l{Qt Style Sheets Reference#subcontrol-position-prop} + {subcontrol-position} property. + + The \l{Qt Style Sheets Reference#width-prop}{width} and + \l{Qt Style Sheets Reference#height-prop}{height} properties can be used + to control the size of the Sub-control. Note that setting a + \l{Qt Style Sheets Reference#image-prop}{image} implicitly sets the size + of a Sub-control. + + The relative positioning scheme + (\l{Qt Style Sheets Reference#position-prop}{position} : relative), + allows the position of the Sub-Control to be offset from its initial + position. For example, when the QComboBox's drop-down button is + pressed, we might like the arrow inside to be offset to give a + "pressed" effect. To achieve this, we can specify: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 7 + + The absolute positioning scheme + (\l{Qt Style Sheets Reference#position-prop}{position} : absolute), + allows the position and size of the Sub-control to be changed with + respect to the reference element. + + Once positioned, they are treated the same as widgets and can be styled + using the \l{box model}. + + See the \l{List of Sub-Controls} below for a list of supported + sub-controls, and \l{Customizing the QPushButton's Menu Indicator + Sub-Control} for a realistic example. + + \note With complex widgets such as QComboBox and QScrollBar, if one + property or sub-control is customized, \bold{all} the other properties or + sub-controls must be customized as well. + + \section1 Pseudo-States + + Selectors may contain \e{pseudo-states} that denote that restrict + the application of the rule based on the widget's state. + Pseudo-states appear at the end of the selector, with a colon + (\c{:}) in between. For example, the following rule applies when + the mouse hovers over a QPushButton: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 8 + + Pseudo-states can be negated using the exclamation operator. For + example, the following rule applies when the mouse does not hover + over a QRadioButton: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 9 + + Pseudo-states can be chained, in which case a logical AND is + implied. For example, the following rule applies to when the + mouse hovers over a checked QCheckBox: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 10 + + Negated Pseudo-states may appear in Pseudo-state chains. For example, + the following rule applies when the mouse hovers over a QPushButton + that is not pressed: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 11 + + If needed, logical OR can be expressed using the comma operator: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 12 + + Pseudo-states can appear in combination with subcontrols. For + example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 13 + + See the \l{List of Pseudo-States} section below for the list of + pseudo-states provided by Qt widgets. + + \section1 Conflict Resolution + + Conflicts arise when several style rules specify the same + properties with different values. Consider the following style + sheet: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 14 + + Both rules match QPushButton instances called \c okButton and + there is a conflict for the \c color property. To resolve this + conflict, we must take into account the \e specificity of the + selectors. In the above example, \c{QPushButton#okButton} is + considered more specific than \c QPushButton, because it + (usually) refers to a single object, not to all instances of a + class. + + Similarly, selectors with pseudo-states are more specific than + ones that do not specify pseudo-states. Thus, the following style + sheet specifies that a \l{QPushButton} should have white text + when the mouse is hovering over it, otherwise red text: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 15 + + Here's a tricky one: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 16 + + Here, both selectors have the same specificity, so if the mouse + hovers over the button while it is enabled, the second rule takes + precedence. If we want the text to be white in that case, we can + reorder the rules like this: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 17 + + Alternatively, we can make the first rule more specific: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 18 + + A similar issue arises in conjunction with Type Selectors. + Consider the following example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 19 + + Both rules apply to QPushButton instances (since QPushButton + inherits QAbstractButton) and there is a conflict for the + \l{Qt Style Sheets Reference#color-prop}{color} property. Because QPushButton + inherits QAbstractButton, it might be tempting to assume that + \c QPushButton is more specific than \c QAbstractButton. However, + for style sheet computations, all Type Selectors have the same + specificity, and the rule that appears last takes precedence. In + other words, \l{Qt Style Sheets Reference#color-prop}{color} is set to \c gray + for all \l{QAbstractButton}s, including \l{QPushButton}s. If we really + want \l{QPushButton}s to have red text, we can always reorder the + rules. + + For determining the specificity of a rule, Qt Style Sheets follow + the + \l{http://www.w3.org/TR/REC-CSS2/cascade.html#specificity}{CSS2 + Specification}: + + \quotation + \e{A selector's specificity is calculated as follows:} + + \list + \o \e{count the number of ID attributes in the selector (= a)} + \o \e{count the number of other attributes and pseudo-classes in the selector (= b)} + \o \e{count the number of element names in the selector (= c)} + \o \e{ignore pseudo-elements [i.e., \l{subcontrols}].} + \endlist + + \e{Concatenating the three numbers a-b-c (in a number system with a + large base) gives the specificity.} + + \e{Some examples:} + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 20 + \endquotation + + \section1 Cascading + + Style sheets can be set on the QApplication, on parent widgets, + and on child widgets. An arbitrary widget's effective style sheet + is obtained by merging the style sheets set on the widget's + ancestors (parent, grandparent, etc.), as well as any style sheet + set on the QApplication. + + When conflicts arise, the widget's own style sheet is always + preferred to any inherited style sheet, irrespective of the + specificity of the conflicting rules. Likewise, the parent + widget's style sheet is preferred to the grandparent's, etc. + + One consequence of this is that setting a style rule on a widget + automatically gives it precedence over other rules specified in + the ancestor widgets' style sheets or the QApplication style + sheet. Consider the following example. First, we set a style + sheet on the QApplication: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 21 + + Then we set a style sheet on a QPushButton object: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 22 + + The style sheet on the QPushButton forces the QPushButton (and + any child widget) to have blue text, in spite of the more + specific rule set provided by the application-wide style sheet. + + The result would have been the same if we had written + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 23 + + except that if the QPushButton had children (which is unlikely), + the style sheet would have no impact on them. + + Style sheet cascading is a complex topic. Refer to the + \l{http://www.w3.org/TR/CSS2/cascade.html#cascade}{CSS2 + Specification} for the gory details. Be aware that Qt currently + doesn't implement \c{!important}. + + \section1 Inheritance + + In classic CSS, when font and color of an item is not explicitly set, + it gets automatically inherited from the parent. When using Qt Style Sheets, + a widget does \bold{not} automatically inherit its font and color setting + from its parent widget. + + For example, consider a QPushButton inside a QGroupBox: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 24 + + The QPushButton does not have an explicit color set. Hence, instead + of inheriting color of its parent QGroupBox, it has the system color. + If we want to set the color on a QGroupBox and its children, + we can write: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 25 + + In contrast, setting a font and propagate using QWidget::setFont() and + QWidget::setPalette() propagates to child widgets. + + \section1 Widgets inside C++ namespaces + + The Type Selector can be used to style widgets of a particular type. For + example, + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 26 + + Qt Style Sheet uses QObject::className() of the widget to determine + when to apply the Type Selector. When custom widgets are inside namespaces, + the QObject::className() returns ::. This conflicts + with the syntax for \l{Sub-Controls}. To overcome this problem, + when using the Type Selector for widgets inside namespaces, we must + replace the "::" with "--". For example, + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 27 + + \section1 Setting QObject properties + + From 4.3 and above, any designable Q_PROPERTY + can be set using the qproperty- syntax. + + For example, + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 28 + + If the property references an enum declared with Q_ENUMS, you should + reference its constants by name, i.e., not their numeric value. + +*/ + +/*! + \page stylesheet-designer.html + \contentspage {Qt Style Sheet}{Contents} + \previouspage The Style Sheet Syntax + \nextpage Customizing Qt Widgets Using Style Sheets + \title Qt Designer Integration + + \l{Qt Designer}{Qt Designer} is an excellent tool + to preview style sheets. You can right-click on any widget in Designer + and select \gui{Change styleSheet...} to set the style sheet. + + \image designer-stylesheet-options.png + + In Qt 4.2 and later, \l{Qt Designer}{Qt Designer} also includes a + style sheet syntax highlighter and validator. The validator indicates + if the syntax is valid or invalid, at the bottom left of the \gui{Edit + Style Sheet} dialog. + + \image designer-validator-highlighter.png + + When you click \gui{OK} or \gui{Apply}, \QD will automatically display + the widget with its new stylesheet. + + \image designer-stylesheet-usage.png + */ + +/*! + \page stylesheet-customizing.html + \contentspage {Qt Style Sheet}{Contents} + \previouspage Qt Designer Integration + \nextpage Qt Style Sheets Reference + \title Customizing Qt Widgets Using Style Sheets + + When using style sheets, every widget is treated as a box with four + concentric rectangles: the margin rectangle, the border rectangle, the + padding rectangle, and the content rectangle. The box model describes + this in further detail. + + \tableofcontents + + \target box model + \section1 The Box Model + + The four concentric rectangles appear conceptually as below: + + \image stylesheet-boxmodel.png + + \list + \o The margin falls outside the border. + \o The border is drawn between the margin and the padding. + \o The padding falls inside the border, between the border and + the actual contents. + \o The content is what is left from the original widget or + subcontrol once we have removed the margin, the border, and + the padding. + \endlist + + The \l{Qt Style Sheets Reference#margin-prop}{margin}, + \l{Qt Style Sheets Reference#border-width-prop} + {border-width}, and + \l{Qt Style Sheets Reference#padding-prop}{padding} + properties all default to zero. In that case, all four rectangles + (\c margin, \c border, \c padding, and \c content) coincide exactly. + + You can specify a background for the widget using the + \l{Qt Style Sheets Reference#background-image-prop}{background-image} + property. By default, the background-image is drawn only for the area + inside the border. This can be changed using the + \l{Qt Style Sheets Reference#background-clip-prop}{background-clip} + property. You can use + \l{Qt Style Sheets Reference#background-repeat-prop}{background-repeat} + and + \l{Qt Style Sheets Reference#background-origin-prop}{background-origin} + to control the repetition and origin of the background image. + + A background-image does not scale with the size of the widget. To provide + a "skin" or background that scales along with the widget size, one must + use + \l{Qt Style Sheets Reference#border-image-prop}{border-image}. Since the + border-image property provides an alternate background, it is not required + to specify a background-image when border-image is specified. In the case, + when both of them are specified, the border-image draws over the + background-image. + + In addition, the \l{Qt Style Sheets Reference#image-prop}{image} property + may be used to draw an image over the border-image. The image specified does + not tile or stretch and when its size does not match the size of the widget, + its alignment is specified using the + \l{Qt Style Sheets Reference#image-position-prop}{image-position} + property. Unlike background-image and border-image, one may specify a + SVG in the image property, in which case the image is scaled automatically + according to the widget size. + + The steps to render a rule are as follows: + \list + \o Set clip for entire rendering operation (border-radius) + \o Draw the background (background-image) + \o Draw the border (border-image, border) + \o Draw overlay image (image) + \endlist + + \target sub controls + \section1 Sub-controls + + A widget is considered as a hierarchy (tree) of subcontrols drawn on top + of each other. For example, the QComboBox draws the drop-down sub-control + followed by the down-arrow sub-control. A QComboBox is thus rendered as + follows: + \list + \o Render the QComboBox { } rule + \o Render the QComboBox::drop-down { } rule + \o Render the QComboBox::down-arrow { } rule + \endlist + + Sub-controls share a parent-child relationship. In the case of QComboBox, + the parent of down-arrow is the drop-down and the parent of drop-down is + the widget itself. Sub-controls are positioned within their parent using + the \l{Qt Style Sheets Reference#subcontrol-position-prop} + {subcontrol-position} and + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} + properties. + + Once positioned, sub-controls can be styled using the \l{box model}. + + \note With complex widgets such as QComboBox and QScrollBar, if one + property or sub-control is customized, \bold{all} the other properties or + sub-controls must be customized as well. + +*/ + +/*! + \page stylesheet-reference.html + \contentspage {Qt Style Sheet}{Contents} + \previouspage Customizing Qt Widgets Using Style Sheets + \nextpage Qt Style Sheets Examples + \title Qt Style Sheets Reference + + Qt Style Sheets support various properties, pseudo-states, and + subcontrols that make it possible to customize the look of + widgets. + + \tableofcontents + + \section1 List of Stylable Widgets + + The following table lists the Qt widgets that can be customized + using style sheets: + + \table 100% + \header + \o Widget + \o How to Style + + \row + \o QAbstractScrollArea \target qabstractscrollarea-widget + \o Supports the \l{box model}. + + All derivatives of QAbstractScrollArea, including QTextEdit, + and QAbstractItemView (all item view classes), support + scrollable backgrounds using + \l{Qt Style Sheets Reference#background-attachment-prop} + {background-attachment}. Setting the background-attachment to + \c{fixed} provides a background-image that does not scroll with the + viewport. Setting the background-attachment to \c{scroll}, scrolls + the background-image when the scroll bars move. + + See \l{Qt Style Sheets Examples#Customizing QAbstractScrollArea} + {Customizing QAbstractScrollArea} for an example. + + \row + \o QCheckBox \target qcheckbox-widget + \o Supports the \l{box model}. The check indicator can be + styled using the \l{#indicator-sub}{::indicator} + subcontrol. By default, the indicator is placed in the Top + Left corner of the Contents rectangle of the widget. + + The \l{#spacing-prop}{spacing} property + specifies the spacing between the check indicator and + the text. + + See \l{Qt Style Sheets Examples#Customizing QCheckBox} + {Customizing QCheckBox} for an example. + + \row + \o QColumnView \target qcolumnview-widget + \o The grip can be styled be using the \l{image-prop}{image} property. + The arrow indicators can by styled using the + \l{left-arrow-sub}{::left-arrow} subcontrol and the + \l{right-arrow-sub}{::right-arrow} subcontrol. + + \row + \o QComboBox \target qcombobox-widget + \o The frame around the combobox can be styled using the + \l{box model}. The drop-down button can be styled using + the \l{#drop-down-sub}{::drop-down} subcontrol. By default, the + drop-down button is placed in the top right corner of the padding + rectangle of the widget. The arrow mark inside the drop-down button + can be styled using the \l{#down-arrow-sub}{::down-arrow} + subcontrol. By default, the arrow is placed in the center of the + contents rectangle of the drop-down subcontrol. + + See \l{Qt Style Sheets Examples#Customizing QComboBox}{Customizing QComboBox} + for an example. + + \row + \o QDateEdit \target qdateedit-widget + \o See \l{#qspinbox-widget}{QSpinBox}. + + \row + \o QDateTimeEdit \target qdatetimeedit-widget + \o See \l{#qspinbox-widget}{QSpinBox}. + + \row + \o QDialog \target qdialog-widget + \o Supports only the \l{Qt Style Sheets Reference#background-prop}{background}, + \l{#background-clip-prop}{background-clip} and + \l{#background-origin-prop}{background-origin} properties. + + \warning Make sure you define the Q_OBJECT macro for your custom + widget. + + \row + \o QDialogButtonBox \target qdialogbuttonbox-widget + \o The layout of buttons can be altered using the + \l{#button-layout-prop}{button-layout} property. + + \row + \o QDockWidget \target qdockwidget-widget + \o Supports styling of the title bar and the title bar buttons when docked. + + The dock widget border can be styled using the \l{#border-prop}{border} + property. The \l{#title-sub}{::title} subcontrol can be used to customize + the title bar. The close and float buttons are positioned with respect + to the \l{title-sub}{::title} subcontrol using the + \l{#close-button-sub}{::close-button} and + \l{#float-button-sub}{::float-button} respectively. + + When the title bar is vertical, the \l{#vertical-ps}{:vertical} pseudo + class is set. In addition, depending on QDockWidget::DockWidgetFeature, + the \l{#closable-ps}{:closable}, \l{#floatable-ps}{:floatable} and + \l{#movable-ps}{:movable} pseudo states are set. + + \note Use QMainWindow::separator to style the resize handle. + + \warning The style sheet has no effect when the QDockWidget is undocked + as Qt uses native top level windows when undocked. + + See \l{Qt Style Sheets Examples#Customizing QDockWidget} + {Customizing QDockWidget} for an example. + + \row + \o QDoubleSpinBox \target qdoublespinbox-widget + \o See \l{#qspinbox-widget}{QSpinBox}. + + \row + \o QFrame \target qframe-widget + \o Supports the \l{box model}. + + Since 4.3, setting a stylesheet on a QLabel automatically + sets the QFrame::frameStyle property to QFrame::StyledPanel. + + See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} + for an example. + + \row + \o QGroupBox \target qgroupbox-widget + \o Supports the \l{box model}. The title can be styled using the + \l{#title-sub}{::title} subcontrol. By default, the title is placed + depending on QGroupBox::textAlignment. + + In the case of a checkable QGroupBox, the title includes the + check indicator. The indicator is styled using the + the \l{#indicator-sub}{::indicator} subcontrol. The + \l{#spacing-prop}{spacing} property can be used to control + the spacing between the text and indicator. + + See \l{Qt Style Sheets Examples#Customizing QGroupBox}{Customizing QGroupBox} + for an example. + + \row + \o QHeaderView \target qheaderview-widget + \o Supports the \l{box model}. The sections of the header view are + styled using the \l{#section-sub}{::section} sub control. The + \c{section} Sub-control supports the \l{#middle-ps}{:middle}, + \l{#first-ps}{:first}, \l{#last-ps}{:last}, + \l{#only-one-ps}{:only-one}, \l{#next-selected-ps}{:next-selected}, + \l{#previous-selected-ps}{:previous-selected}, + \l{#selected-ps}{:selected}, + and \l{#checked-ps}{:checked} pseudo states. + + Sort indicator in can be styled using the + \l{#up-arrow-sub}{::up-arrow} and the + \l{#down-arrow-sub}{::down-arrow} Sub-control. + + See \l{Qt Style Sheets Examples#Customizing QHeaderView}{Customizing QHeaderView} + for an example. + + \row + \o QLabel \target qlabel-widget + \o Supports the \l{box model}. Does not support the + \l{#hover-ps}{:hover} pseudo-state. + + Since 4.3, setting a stylesheet on a QLabel automatically + sets the QFrame::frameStyle property to QFrame::StyledPanel. + + See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} for an + example (a QLabel derives from QFrame). + + \row + \o QLineEdit \target qlineedit-widget + \o Support the \l{box model}. + + The color and background of the selected item is styled using + \l{#selection-color-prop}{selection-color} and + \l{#selection-background-color-prop}{selection-background-color} + respectively. + + The password character can be styled using the + \l{#lineedit-password-character-prop}{lineedit-password-character} + property. + + See \l{Qt Style Sheets Examples#Customizing QLineEdit}{Customizing QLineEdit} + for an example. + + \row + \o QListView \target qlistview-widget + \o Supports the \l{box model}. When + \l{QAbstractItemView::alternatingRowColors}{alternating row colors} + is enabled, the alternating colors can be styled using the + \l{#alternate-background-color-prop}{alternate-background-color} + property. + + The color and background of the selected item is styled using + \l{#selection-color-prop}{selection-color} and + \l{#selection-background-color-prop}{selection-background-color} + respectively. + + The selection behavior is controlled by the + \l{#show-decoration-selected-prop}{show-decoration-selected} property. + + Use the \l{#item-sub}{::item} subcontrol for more fine grained + control over the items in the QListView. + + See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to + style scrollable backgrounds. + + See \l{Qt Style Sheets Examples#Customizing QListView} + {Customzing QListView} for an example. + + \row + \o QListWidget \target qlistwidget-widget + \o See \l{#qlistview-widget}{QListView}. + + \row + \o QMainWindow \target qmainwindow-widget + \o Supports styling of the separator + + The separator in a QMainWindow when using QDockWidget is styled + using the \l{#separator-sub}{::separator} subcontrol. + + See \l{Qt Style Sheets Examples#Customizing QMainWindow}{Customizing QMainWindow} + for an example. + + \row + \o QMenu \target qmenu-widget + \o Supports the \l{box model}. + + Individual items are styled using the \l{#item-sub}{::item} + subcontrol. In addition to the usually supported pseudo states, + \c{item} subcontrol supports the + \l{#selected-ps}{:selected}, \l{#default-ps}{:default}, + \l{#exclusive-ps}{:exclusive} and the + \l{#non-exclusive-ps}{non-exclusive} pseudo states. + + The indicator of checkable menu items is styled using the + \l{#indicator-sub}{::indicator} subcontrol. + + The separator is styled using the \l{#separator-sub}{::separator} + subcontrol. + + For items with a sub menu, the arrow marks are styled using the + \l{right-arrow-sub}{right-arrow} and + \l{left-arrow-sub}{left-arrow}. + + The scroller is styled using the \l{#scroller-sub}{::scroller}. + + The tear-off is styled using the \l{#tearoff-sub}{::tearoff}. + + See \l{Qt Style Sheets Examples#Customizing QMenu}{Customizing QMenu} + for an example. + + \row + \o QMenuBar \target qmenubar-widget + \o Supports the \l{box model}. The \l{#spacing-prop}{spacing} + property specifies the spacing between menu items. + Individual items are styled using the \l{#item-sub}{::item} + subcontrol. + + \warning When running on Qt/Mac, the menu bar is usually embedded into the + system-wide menu bar. In this case, the style sheet will have no effect. + + See \l{Qt Style Sheets Examples#Customizing QMenuBar}{Customizing QMenuBar} + for an example. + + \row + \o QMessageBox \target qmessagebox-widget + \o The \l{#messagebox-text-interaction-flags-prop} + {messagebox-text-interaction-flags} property can be used to alter + the interaction with text in the message box. + + \row + \o QProgressBar \target qprogressbar-widget + \o Supports the \l{box model}. The chunks of the progress bar + can be styled using the \l{#chunk-sub}{::chunk} subcontrol. + The chunk is displayed on the Contents rectangle of the widget. + + If the progress bar displays text, use the \l{text-align-prop}{text-align} + property to position the text. + + Indeterminate progress bars have the + \l{#indeterminate-ps}{:indeterminate} pseudo state set. + + See \l{Qt Style Sheets Examples#Customizing QProgressBar}{Customizing QProgressBar} + for an example. + + \row + \o QPushButton \target qpushbutton-widget + \o Supports the \l{box model}. Supports the \l{#default-ps}{:default}, + \l{#flat-ps}{:flat}, \l{#checked-ps}{:checked} pseudo states. + + For QPushButton with a menu, the menu indicator is styled + using the \l{#menu-indicator-sub}{::menu-indicator} + subcontrol. Appearance of checkable push buttons can be + customized using the \l{#open-ps}{:open} and + \l{#closed-ps}{:closed} pseudo-states. + + \warning If you only set a background-color on a QPushButton, the background + may not appear unless you set the border property to some value. This is + because, by default, the QPushButton draws a native border which completely + overlaps the background-color. For example, + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 30 + + See \l{Qt Style Sheets Examples#Customizing QPushButton}{Customizing QPushButton} + for an example. + + \row + \o QRadioButton \target qradiobutton-widget + \o Supports the \l{box model}. The check indicator can be + styled using the \l{#indicator-sub}{::indicator} + subcontrol. By default, the indicator is placed in the Top + Left corner of the Contents rectangle of the widget. + + The \l{#spacing-prop}{spacing} property + specifies the spacing between the check indicator and + the text. + + See \l{Qt Style Sheets Examples#Customizing QRadioButton} + {Customizing QRadioButton} for an example. + + \row + \o QScrollBar \target qscrollbar-widget + \o Supports the \l{box model}. The Contents rectangle of the widget + is considered to be the groove over which the slider moves. The extent + of the QScrollBar (i.e the width or the height depending on the orientation) + is set using the \l{#width-prop}{width} or \l{#height-prop}{height} property + respectively. To determine the orientation, use the + \l{#horizontal-ps}{:horizontal} and the \l{vertical-ps}{:vertical} + pseudo states. + + The slider can be styled using the \l{#handle-sub}{::handle} subcontrol. + Setting the \l{#min-width-prop}{min-width} or \l{#min-height-prop}{min-height} + provides size contraints for the slider depending on the orientation. + + The \l{add-line-sub}{::add-line} subcontrol can be used to style the + button to add a line. By default, the add-line subcontrol is placed in + top right corner of the Border rectangle of the widget. Depending on the + orientation the \l{#right-arrow-sub}{::right-arrow} or + \l{#down-arrow-sub}{::down-arrow}. By default, the arrows are placed in + the center of the Contents rectangle of the add-line subcontrol. + + The \l{sub-line-sub}{::sub-line} subcontrol can be used to style the + button to subtract a line. By default, the sub-line subcontrol is placed in + bottom right corner of the Border rectangle of the widget. Depending on the + orientation the \l{#left-arrow-sub}{::left-arrow} or + \l{#up-arrow-sub}{::up-arrow}. By default, the arrows are placed in + the center of the Contents rectangle of the sub-line subcontrol. + + The \l{sub-page-sub}{::sub-page} subcontrol can be used to style the + region of the slider that subtracts a page. The \l{add-page-sub}{::add-page} + subcontrol can be used to style the region of the slider that adds a page. + + See \l{Qt Style Sheets Examples#Customizing QScrollBar}{Customizing QScrollBar} + for an example. + + \row + \o QSizeGrip \target qsizegrip-widget + \o Supports the \l{#width-prop}{width}, + \l{#height-prop}{height}, and \l{#image-prop}{image} + properties. + + See \l{Qt Style Sheets Examples#Customizing QSizeGrip}{Customizing QSizeGrip} + for an example. + + \row + \o QSlider \target qslider-widget + \o Supports the \l{box model}. For horizontal slides, the + \l{min-width-prop}{min-width} and \l{height-prop}{height} + properties must be provided. For vertical sliders, the + \l{min-height-prop}{min-height} and \l{width-prop}{width} + properties must be provided. + + The groove of the slider is styled + using the \l{#groove-sub}{::groove}. The groove is + positioned by default in the Contents rectangle of the widget. + The thumb of the slider is styled using \l{#handle-sub}{::handle} + subcontrol. The subcontrol moves in the Contents rectangle of + the groove subcontrol. + + See \l{Qt Style Sheets Examples#Customizing QSlider}{Customizing QSlider} + for an example. + + \row + \o QSpinBox \target qspinbox-widget + \o The frame of the spin box can be styled using the \l{box + model}. + + The up button and arrow can be styled using the + \l{#up-button-sub}{::up-button} and + \l{#up-arrow-sub}{::up-arrow} subcontrols. By default, + the up-button is placed in the top right corner in the + Padding rectangle of the widget. Without an explicit size, + it occupies half the height of its reference rectangle. + The up-arrow is placed in the center of the Contents + rectangle of the up-button. + + The down button and arrow can be styled using the + \l{#down-button-sub}{::down-button} and + \l{#down-arrow-sub}{::down-arrow} subcontrols. By default, + the down-button is placed in the bottom right corner in the + Padding rectangle of the widget. Without an explicit size, + it occupies half the height of its reference rectangle. + The bottom-arrow is placed in the center of the Contents + rectangle of the bottom-button. + + See \l{Qt Style Sheets Examples#Customizing QSpinBox}{Customizing QSpinBox} + for an example. + + \row + \o QSplitter \target qsplitter-widget + \o Supports the \l{box model}. The handle of the splitter + is styled using the \l{#handle-sub}{::handle} subcontrol. + + See \l{Qt Style Sheets Examples#Customizing QSplitter}{Customizing QSplitter} + for an example. + + \row + \o QStatusBar \target qstatusbar-widget + \o Supports only the \l{Qt Style Sheets Reference#background-prop} + {background} property. + The frame for individual items can be style using the + \l{#item-sub}{::item} subcontrol. + + See \l{Qt Style Sheets Examples#Customizing QStatusBar}{Customizing QStatusBar} + for an example. + + \row + \o QTabBar \target qtabbar-widget + \o Individual tabs may be styled using the \l{#tab-sub}{::tab} subcontrol. + Close buttons using the \l{#close-button-sub}{::close-button} + The tabs support the + \l{#only-one-ps}{:only-one}, \l{#first-ps}{:first}, + \l{#last-ps}{:last}, \l{#middle-ps}{:middle}, + \l{#previous-selected-ps}{:previous--selected}, + \l{#next-selected-ps}{:next-selected}, + \l{#selected-ps}{:selected} pseudo states. + + The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right}, + \l{#bottom-ps}{:bottom} pseudo states depending on the orientation + of the tabs. + + Overlapping tabs for the selected state are created by using + negative margins or using the \c{absolute} position scheme. + + The tear indicator of the QTabBar is styled using the + \l{#tear-sub}{::tear} subcontrol. + + QTabBar used two QToolButtons for its scrollers that can be styled + using the \c{QTabBar QToolButton} selector. To specify the width + of the scroll button use the \l{#scroller-sub}{::scroller} + subcontrol. + + The alignment of the tabs within the QTabBar is styled + using the \l{#Alignment}{alignment} property. \warning + + To change the position of the QTabBar within a QTabWidget, use the + \l{#tab-bar-sub}{tab-bar} subcontrol (and set subcontrol-position). + + See \l{Qt Style Sheets Examples#Customizing QTabWidget and QTabBar}{Customizing QTabBar} + for an example. + + \row + \o QTabWidget \target qtabwidget-widget + \o The frame of the tab widget is styled using the + \l{#pane-sub}{::pane} subcontrol. The left and right + corners are styled using the \l{#left-corner-sub}{::left-corner} + and \l{#right-corner-sub}{::right-corner} respectively. + The position of the tab bar is controlled using the + \l{#tab-bar-sub}{::tab-bar} subcontrol. + + By default, the subcontrols have positions of a QTabWidget in + the QWindowsStyle. To place the QTabBar in the center, set the + subcontrol-position of the tab-bar subcontrol. + + The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right}, + \l{#bottom-ps}{:bottom} pseudo states depending on the orientation + of the tabs. + + See \l{Qt Style Sheets Examples#Customizing QTabWidget and QTabBar} + {Customizing QTabWidget} for an example. + + \row + \o QTableView \target qtableview-widget + \o Supports the \l{box model}. When + \l{QAbstractItemView::alternatingRowColors}{alternating row colors} + is enabled, the alternating colors can be styled using the + \l{#alternate-background-color-prop}{alternate-background-color} + property. + + The color and background of the selected item is styled using + \l{#selection-color-prop}{selection-color} and + \l{#selection-background-color-prop}{selection-background-color} + respectively. + + The corner widget in a QTableView is implemented as a QAbstractButton + and can be styled using the "QTableView QTableCornerButton::section" + selector. + + \warning If you only set a background-color on a QTableCornerButton, + the background may not appear unless you set the border property to + some value. This is because, by default, the QTableCornerButton draws a + native border which completely overlaps the background-color. + + The color of the grid can be specified using the + \l{#gridline-color-prop}{gridline-color} property. + + See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to + style scrollable backgrounds. + + See \l{Qt Style Sheets Examples#Customizing QTableView} + {Customzing QTableView} for an example. + + \row + \o QTableWidget \target qtablewidget-widget + \o See \l{#qtableview-widget}{QTableView}. + + \row + \o QTextEdit \target qtextedit-widget + \o Supports the \l{box model}. + + The color and background of selected text is styled using + \l{#selection-color-prop}{selection-color} and + \l{#selection-background-color-prop}{selection-background-color} + respectively. + + See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to + style scrollable backgrounds. + + \row + \o QTimeEdit \target qtimeedit-widget + \o See \l{#qspinbox-widget}{QSpinBox}. + + \row + \o QToolBar \target qtoolbar-widget + \o Supports the \l{box model}. + + The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right}, + \l{#bottom-ps}{:bottom} pseudo states depending on the area in + which the tool bar is grouped. + + The \l{#first-ps}{:first}, \l{#last-ps}{:last}, \l{#middle-ps}{:middle}, + \l{#only-one-ps}{:only-one} pseudo states indicator the position + of the tool bar within a line group (See + QStyleOptionToolBar::positionWithinLine). + + The separator of a QToolBar is styled using the + \l{#separator-sub}{::separator} subcontrol. + + The handle (to move the toolbar) is styled using the + \l{#handle-sub}{::handle} subcontrol. + + See \l{Qt Style Sheets Examples#Customizing QToolBar}{Customizing QToolBar} + for an example. + + \row + \o QToolButton \target qtoolbutton-widget + \o Supports the \l{box model}. + + If the QToolButton has a menu, is + \l{#menu-indicator-sub}{::menu-indicator} subcontrol can be used to + style the indicator. By default, the menu-indicator is positioned + at the bottom right of the Padding rectangle of the widget. + + If the QToolButton is in QToolButton::MenuButtonPopup mode, + the \l{#menu-button-sub}{::menu-button} subcontrol is used to draw the + menu button. \l{#menu-arrow-sub}{::menu-arrow} subcontrol is used to + draw the menu arrow inside the menu-button. By default, it is + positioned in the center of the Contents rectangle of the + menu-button subcontrol. + + When the QToolButton displays arrows, the \l{#up-arrow-sub}{::up-arrow}, + \l{#down-arrow-sub}{::down-arrow}, \l{#left-arrow-sub}{::left-arrow} + and \l{#right-arrow-sub}{::right-arrow} subcontrols are used. + + \warning If you only set a background-color on a QToolButton, the background + will not appear unless you set the border property to some value. This is + because, by default, the QToolButton draws a native border which completely + overlaps the background-color. For example, + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 31 + + See \l{Qt Style Sheets Examples#Customizing QToolButton}{Customizing QToolButton} + for an example. + + \row + \o QToolBox \target qtoolbox-widget + \o Supports the \l{box model}. + + The individual tabs can by styled using the + \l{#tab-sub}{::tab} subcontrol. The tabs support the + \l{#only-one-ps}{:only-one}, \l{#first-ps}{:first}, + \l{#last-ps}{:last}, \l{#middle-ps}{:middle}, + \l{#previous-selected-ps}{:previous-selected}, + \l{#next-selected-ps}{:next-selected}, + \l{#selected-ps}{:selected} pseudo states. + + \row + \o QToolTip \target qtooltip-widget + \o Supports the \l{box model}. The \l{#opacity-prop}{opacity} + property controls the opacity of the tooltip. + + See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} + for an example (a QToolTip is a QFrame). + + \row + \o QTreeView \target qtreeview-widget + \o Supports the \l{box model}. When + \l{QAbstractItemView::alternatingRowColors}{alternating row colors} + is enabled, the alternating colors can be styled using the + \l{#alternate-background-color-prop}{alternate-background-color} + property. + + The color and background of the selected item is styled using + \l{#selection-color-prop}{selection-color} and + \l{#selection-background-color-prop}{selection-background-color} + respectively. + + The selection behavior is controlled by the + \l{#show-decoration-selected-prop}{show-decoration-selected} property. + + The branches of the tree view can be styled using the + \l{#branch-sub}{::branch} subcontrol. The + ::branch Sub-control supports the \l{open-ps}{:open}, + \l{closed-ps}{:closed}, \l{has-siblings-ps}{:has-sibling} and + \l{has-children-ps}{:has-children} pseudo states. + + Use the \l{#item-sub}{::item} subcontrol for more fine grained + control over the items in the QTreeView. + + See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to + style scrollable backgrounds. + + See \l{Qt Style Sheets Examples#Customizing QTreeView}{Customizing QTreeView} + for an example to style the branches. + + \row + \o QTreeWidget \target qtreewidget-widget + \o See \l{#qtreeview-widget}{QTreeView}. + + \row + \o QWidget \target qwidget-widget + \o Supports only the \l{Qt Style Sheets Reference#background-prop}{background}, + \l{#background-clip-prop}{background-clip} and + \l{#background-origin-prop}{background-origin} properties. + + If you subclass from QWidget, you need to provide a paintEvent for your + custom QWidget as below: + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 32 + + The above code is a no-operation if there is no stylesheet set. + + \warning Make sure you define the Q_OBJECT macro for your custom + widget. + + \endtable + + \section1 List of Properties + + The table below lists all the properties supported by Qt Style + Sheets. Which values can be given to an property depend on the + \l{List of Property Types}{property's type}. Unless otherwise + specified, properties below apply to all widgets. Properties + marked with an asterisk * are specific to Qt and have no equivalent + in CSS2 or CSS3. + + \table 100% + \header + \o Property + \o Type + \o Description + + \row + \o \bold{\c alternate-background-color} \target alternate-background-color-prop + \o \l{#Brush}{Brush} \BR + \o The \l{QAbstractItemView::alternatingRowColors} + {alternate background color} used in QAbstractItemView subclasses. + + If this property is not set, the default value is + whatever is set for the palette's + \l{QPalette::}{AlternateBase} role. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 33 + + See also \l{Qt Style Sheets Reference#background-prop}{background} and + \l{#selection-background-color-prop}{selection-background-color}. + + \row + \o \bold{\c background} \target background-prop + \o \l{#Background}{Background} + \o Shorthand notation for setting the background. Equivalent + to specifying \c background-color, \c background-image, \c + background-repeat, and/or \c background-position. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QDialog, QFrame, QGroupBox, QLabel, QLineEdit, + QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, + QTextEdit, QToolTip, and plain \l{QWidget}s. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 34 + + + Often, it is required to set a fill pattern similar to the styles + in Qt::BrushStyle. You can use the background-color property for + Qt::SolidPattern, Qt::RadialGradientPattern, Qt::LinearGradientPattern + and Qt::ConicalGradientPattern. The other patterns are easily achieved + by creating a background image that contains the pattern. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 35 + + See also \l{#background-origin-prop}{background-origin}, + \l{#selection-background-color-prop}{selection-background-color}, + \l{#background-clip-prop}{background-clip}, + \l{#background-attachment-prop}{background-attachment} + and \l{#alternate-background-color-prop}{alternate-background-color}. + + \row + \o \c background-color \target background-color-prop + \o \l{#Brush}{Brush} \BR + \o The background color used for the widget. + + Examples: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 36 + + \row + \o \c background-image \target background-image-prop + \o \l{#Url}{Url} + \o The background image used for the widget. Semi-transparent + parts of the image let the \c background-color shine + through. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 37 + + \row + \o \c background-repeat \target background-repeat-prop + \o \l{#Repeat}{Repeat} + \o Whether and how the background image is repeated to fill + the \c background-origin rectangle. + + If this property is not specified, the background image + is repeated in both directions (\c repeat). + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 38 + + \row + \o \c background-position + \o \l{#Alignment}{Alignment} + \o The alignment of the background image within the \c + background-origin rectangle. + + If this property is not specified, the alignment is \c + top \c left. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 39 + + \row + \o \bold{\c background-attachment} \target background-attachment-prop + \o \l{#Attachment}{Attachment} + \o Determines whether the background-image in a QAbstractScrollArea + is scrolled or fixed with respect to the viewport. + By default, the background-image scrolls with the viewport. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 40 + + See also \l{Qt Style Sheets Reference#background-prop}{background} + + \row + \o \bold{\c background-clip} \target background-clip-prop + \o \l{#Origin}{Origin} + \o The widget's rectangle, in which the \c background is drawn. + + This property specifies the rectangle to which the \c background-color + and \c background-image are clipped. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QDialog, QFrame, QGroupBox, QLabel, + QPushButton, QRadioButton, QSplitter, QTextEdit, QToolTip, + and plain \l{QWidget}s. + + If this property is not specified, the default is \c + border. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 41 + + See also \l{Qt Style Sheets Reference#background-prop}{background}, + \l{#background-origin-prop}{background-origin} and \l{The Box Model}. + + \row + \o \bold{\c background-origin} \target background-origin-prop + \o \l{#Origin}{Origin} + \o The widget's background rectangle, to use in conjunction + with \c background-position and \c background-image. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QDialog, QFrame, QGroupBox, QLabel, + QPushButton, QRadioButton, QSplitter, QTextEdit, QToolTip, + and plain \l{QWidget}s. + + If this property is not specified, the default is \c + padding. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 42 + + See also \l{Qt Style Sheets Reference#background-prop}{background} and + \l{The Box Model}. + + \row + \o \bold{\c border} \target border-prop + \o \l{#Border}{Border} + \o Shorthand notation for setting the widget's border. Equivalent + to specifying \c border-color, \c border-style, and/or + \c border-width. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, + QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, + QTextEdit, QToolTip, and plain \l{QWidget}s. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 43 + + \row + \o \c border-top + \o \l{#Border}{Border} + \o Shorthand notation for setting the widget's top border. + Equivalent to specifying \c border-top-color, \c + border-top-style, and/or \c border-top-width. + + \row + \o \c border-right + \o \l{#Border}{Border} + \o Shorthand notation for setting the widget's right border. + Equivalent to specifying \c border-right-color, \c + border-right-style, and/or \c border-right-width. + + \row + \o \c border-bottom + \o \l{#Border}{Border} + \o Shorthand notation for setting the widget's bottom border. + Equivalent to specifying \c border-bottom-color, \c + border-bottom-style, and/or \c border-bottom-width. + + \row + \o \c border-left + \o \l{#Border}{Border} + \o Shorthand notation for setting the widget's left border. + Equivalent to specifying \c border-left-color, \c + border-left-style, and/or \c border-left-width. + + \row + \o \bold{\c border-color} \target border-attrs + \target border-color-prop + \o \l{#Box Colors}{Box Colors} + \o The color of all the border's edges. Equivalent to + specifying \c border-top-color, \c border-right-color, \c + border-bottom-color, and \c border-left-color. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, + QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, + QTextEdit, QToolTip, and plain \l{QWidget}s. + + If this property is not specified, it defaults to + \l{#color-prop}{color} (i.e., the widget's foreground + color). + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 44 + + See also \l{Qt Style Sheets Reference#border-style-prop}{border-style}, + \l{Qt Style Sheets Reference#border-width-prop}{border-width}, + \l{#border-image-prop}{border-image}, and \l{The Box Model}. + + \row + \o \c border-top-color + \o \l{#Brush}{Brush} \BR + \o The color of the border's top edge. + + \row + \o \c border-right-color + \o \l{#Brush}{Brush} \BR + \o The color of the border's right edge. + + \row + \o \c border-bottom-color + \o \l{#Brush}{Brush} \BR + \o The color of the border's bottom edge. + + \row + \o \c border-left-color + \o \l{#Brush}{Brush} \BR + \o The color of the border's left edge. + + \row + \o \bold{\c border-image} \target border-image-prop + \o \l{#Border Image}{Border Image} + \o The image used to fill the border. The image is cut into + nine parts and stretched appropriately if necessary. See + \l{#Border Image}{Border Image} for details. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, + QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, + QTextEdit and QToolTip. + + See also \l{#border-color-prop}{border-color}, + \l{Qt Style Sheets Reference#border-style-prop}{border-style}, + \l{Qt Style Sheets Reference#border-width-prop}{border-width}, and + \l{The Box Model}. + + \row + \o \bold{\c border-radius} \target border-radius-prop + \o \l{#Radius}{Radius} + \o The radius of the border's corners. Equivalent to + specifying \c border-top-left-radius, \c + border-top-right-radius, \c border-bottom-right-radius, + and \c border-bottom-left-radius. + + The border-radius clips the element's + \l{Qt Style Sheets Reference#background-prop}{background}. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, + and QToolTip. + + If this property is not specified, it defaults to 0. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 45 + + See also \l{Qt Style Sheets Reference#border-width-prop}{border-width} and + \l{The Box Model}. + + \row + \o \c border-top-left-radius + \o \l{#Radius}{Radius} + \o The radius of the border's top-left corner. + + \row + \o \c border-top-right-radius + \o \l{#Radius}{Radius} + \o The radius of the border's top-right corner. + + \row + \o \c border-bottom-right-radius + \o \l{#Radius}{Radius} + \o The radius of the border's bottom-right corner. Setting + this property to a positive value results in a rounded + corner. + + \row + \o \c border-bottom-left-radius + \o \l{#Radius}{Radius} + \o The radius of the border's bottom-left corner. Setting this + property to a positive value results in a rounded corner. + + \row + \o \bold{\c border-style} \target border-style-prop + \o \l {Border Style} + \o The style of all the border's edges. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, + and QToolTip. + + If this property is not specified, it defaults to \c none. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 46 + + See also \l{#border-color-prop}{border-color}, + \l{Qt Style Sheets Reference#border-style-prop}{border-style}, + \l{#border-image-prop}{border-image}, and \l{The Box Model}. + + \row + \o \c border-top-style + \o \l{#Border Style}{Border Style} + \o The style of the border's top edge. + + \row + \o \c border-right-style + \o \l{#Border Style}{Border Style} + \o The style of the border's right edge/ + + \row + \o \c border-bottom-style + \o \l{#Border Style}{Border Style} + \o The style of the border's bottom edge. + + \row + \o \c border-left-style + \o \l{#Border Style}{Border Style} + \o The style of the border's left edge. + + \row + \o \bold{\c border-width} \target border-width-prop + \o \l{#Box Lengths}{Box Lengths} + \o The width of the border. Equivalent to setting \c + border-top-width, \c border-right-width, \c + border-bottom-width, and \c border-left-width. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, + and QToolTip. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 47 + + See also \l{#border-color-prop}{border-color}, + \l{#border-radius-prop}{border-radius}, + \l{Qt Style Sheets Reference#border-style-prop}{border-style}, + \l{#border-image-prop}{border-image}, and + \l{The Box Model}. + + \row + \o \c border-top-width + \o \l{#Length}{Length} + \o The width of the border's top edge. + + \row + \o \c border-right-width + \o \l{#Length}{Length} + \o The width of the border's right edge. + + \row + \o \c border-bottom-width + \o \l{#Length}{Length} + \o The width of the border's bottom edge. + + \row + \o \c border-left-width + \o \l{#Length}{Length} + \o The width of the border's left edge. + + \row + \o \bold{\c bottom} \target bottom-prop + \o \l{#Length}{Length} + \o If \l{#position-prop}{position} is \c relative (the + default), moves a \l{subcontrol} by a certain offset up; + specifying \tt{bottom: \e{y}} is then equivalent to + specifying \tt{\l{Qt Style Sheets Reference#top-prop}{top}: -\e{y}}. + + If \l{#position-prop}{position} is \c absolute, the \c + bottom property specifies the subcontrol's bottom edge + in relation to the parent's bottom edge (see also + \l{Qt Style Sheets Reference#subcontrol-origin-prop} + {subcontrol-origin}). + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 48 + + See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{#right-prop}{right}, and + \l{Qt Style Sheets Reference#top-prop}{top}. + + \row + \o \bold{\c button-layout} \target button-layout-prop + \o \l{#Number}{Number} + \o The layout of buttons in a QDialogButtonBox or + a QMessageBox. The possible values are 0 + (\l{QDialogButtonBox::}{WinLayout}), 1 + (\l{QDialogButtonBox::}{MacLayout}), 2 + (\l{QDialogButtonBox::}{KdeLayout}), and 3 + (\l{QDialogButtonBox::}{GnomeLayout}). + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_DialogButtonLayout} style hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 49 + + \row + \o \bold{\c color} \target color-prop + \o \l{#Brush}{Brush} \BR + \o The color used to render text. + + This property is supported by all widgets that respect + the \l QWidget::palette. + + If this property is not set, the default is whatever is + set for in the widget's palette for the + QWidget::foregroundRole (typically black). + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 50 + + See also \l{Qt Style Sheets Reference#background-prop}{background} and + \l{#selection-color-prop}{selection-color}. + + \row + \o \bold{\c dialogbuttonbox-buttons-have-icons} + \o \l{#Boolean}{Boolean} + \o Whether the buttons in a QDialogButtonBox show icons + + If this property is set to 1, the buttons of a QDialogButtonBox + show icons; if it is set to 0, the icons are not shown. + + See the \l{Qt Style Sheets Reference#list of icons}{List of Icons} + section for information on how to set icons. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 51 + + \note Styles defining this property must be applied before the + QDialogButtonBox is created; this means that you must apply the + style to the parent widget or to the application itself. + + \omit + \row + \o \bold{\c etch-disabled-text}* + \o \l{#Boolean}{Boolean} + \o Whether disabled text is drawn etched. + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_EtchDisabledText} style hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 52 + \endomit + + \row + \o \bold{\c font} \target font-prop + \o \l{#Font}{Font} + \o Shorthand notation for setting the text's font. Equivalent + to specifying \c font-family, \c font-size, \c font-style, + and/or \c font-weight. + + This property is supported by all widgets that respect + the \l QWidget::font. + + If this property is not set, the default is the + QWidget::font. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 53 + + \row + \o \c font-family + \o String + \o The font family. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 54 + + \row + \o \c font-size + \o \l{#Font Size}{Font Size} + \o The font size. In this version of Qt, only pt and px metrics are + supported. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 55 + + \row + \o \c font-style + \o \l {Font Style} + \o The font style. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 56 + + \row + \o \c font-weight + \o \l{#Font Weight}{Font Weight} + \o The weight of the font. + + \row + \o \bold{\c gridline-color}* \target gridline-color-prop + \o \l{#Color}{Color} \BR + \o The color of the grid line in a QTableView. + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_Table_GridLineColor} style hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 57 + + \row + \o \bold{\c height} \target height-prop + \o \l{#Length}{Length} + \o The height of a \l{subcontrol} (or in some case, a widget). + + If this property is not specified, it defaults to a value + that depends on the subcontrol/widget and on the current style. + + \warning Unless otherwise specified, this property has no effect + when set on widgets. If you want a widget with a fixed height, set + the \l{#min-width-prop}{min-height} and + \l{#max-width-prop}{max-height} to the same value. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 58 + + See also \l{#width-prop}{width}. + + \row + \o \bold{\c icon-size} \target icon-size-prop + \o \l{#Length}{Length} + \o The width and height of the icon in a widget. + + The icon size of the following widgets can be set using this + property. + \list + \i QCheckBox + \i QListView + \i QPushButton + \i QRadioButton + \i QTabBar + \i QToolBar + \i QToolBox + \i QTreeView + \endlist + + \row + \o \bold{\c image}* \target image-prop + \o \l{#Url}{Url}+ + \o The image that is drawn in the contents rectangle of a + \l{subcontrol}. + + The image property accepts a list of \l{#Url}{Url}s or + an \c{svg}. The actual image that is drawn is determined + using the same algorithm as QIcon (i.e) the image is never scaled + up but always scaled down if necessary. If a \c{svg} is specified, + the image is scaled to the size of the contents rectangle. + + Setting the image property on sub controls implicitly sets the + width and height of the sub-control (unless the image in a SVG). + + In Qt 4.3 and later, the alignment of the + image within the rectangle can be specified using + \l{image-position-prop}{image-position}. + + This property is for \l{subcontrol}s only--we don't support it for + other elements. + + \warning The QIcon SVG plugin is needed to render SVG images. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 59 + + \row + \o \bold{\c image-position} \target image-position-prop + \o \l{#Alignment}{alignment} + \o In Qt 4.3 and later, the alignment of the image image's position can be specified + using relative or absolute position. + + \row + \o \bold{\c left} \target left-prop + \o \l{#Length}{Length} + \o If \l{#position-prop}{position} is \c relative (the + default), moves a \l{subcontrol} by a certain offset to + the right. + + If \l{#position-prop}{position} is \c absolute, the \c + left property specifies the subcontrol's left edge in + relation to the parent's left edge (see also + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}). + + If this property is not specified, it defaults to \c 0. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 60 + + See also \l{#right-prop}{right}, \l{Qt Style Sheets Reference#top-prop}{top}, and + \l{#bottom-prop}{bottom}. + + \row + \o \bold{\c lineedit-password-character*} \target lineedit-password-character-prop + \o \l{#Number}{Number} + \o The QLineEdit password character as a Unicode number. + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_LineEdit_PasswordCharacter} style hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 61 + + \row + \o \bold{\c margin} \target margin-prop + \o \l {Box Lengths} + \o The widget's margins. Equivalent to specifying \c + margin-top, \c margin-right, \c margin-bottom, and \c + margin-left. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, + and QToolTip. + + If this property is not specified, it defaults to \c 0. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 62 + + See also \l{Qt Style Sheets Reference#padding-prop}{padding}, + \l{#spacing-prop}{spacing}, and \l{The Box Model}. + + \row + \o \c margin-top + \o \l{#Length}{Length} + \o The widget's top margin. + + \row + \o \c margin-right + \o \l{#Length}{Length} + \o The widget's right margin. + + \row + \o \c margin-bottom + \o \l{#Length}{Length} + \o The widget's bottom margin. + + \row + \o \c margin-left + \o \l{#Length}{Length} + \o The widget's left margin. + + \row + \o \bold{\c max-height} \target max-height-prop + \o \l{#Length}{Length} + \o The widget's or a subcontrol's maximum height. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, + QSplitter, QStatusBar, QTextEdit, and QToolTip. + + The value is relative to the contents rect in the \l{The + Box Model}{box model}. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 63 + + See also \l{#max-width-prop}{max-width}. + + \row + \o \bold{\c max-width} \target max-width-prop + \o \l{#Length}{Length} + \o The widget's or a subcontrol's maximum width. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, + QSplitter, QStatusBar, QTextEdit, and QToolTip. + + The value is relative to the contents rect in the \l{The + Box Model}{box model}. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 64 + + See also \l{#max-height-prop}{max-height}. + + + \row + \o \bold{\c messagebox-text-interaction-flags*} \target messagebox-text-interaction-flags-prop + \o \l{#Number}{Number} + \o The interaction behavior for text in a message box. + Possible values are based on Qt::TextInteractionFlags. + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_MessageBox_TextInteractionFlags} style + hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 65 + + \row + \o \bold{\c min-height} \target min-height-prop + \o \l{#Length}{Length} + \o The widget's or a subcontrol's minimum height. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, + QSplitter, QStatusBar, QTextEdit, and QToolTip. + + If this property is not specified, the minimum height is + derived based on the widget's contents and the style. + + The value is relative to the contents rect in the \l{The + Box Model}{box model}. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 66 + + See also \l{#min-width-prop}{min-width}. + + \row + \o \bold{\c min-width} \target min-width-prop + \o \l{#Length}{Length} + \o The widget's or a subcontrol's minimum width. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox, + QSplitter, QStatusBar, QTextEdit, and QToolTip. + + If this property is not specified, the minimum width is + derived based on the widget's contents and the style. + + The value is relative to the contents rect in the \l{The + Box Model}{box model}. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 67 + + See also \l{#min-height-prop}{min-height}. + + \row + \o \bold{\c opacity*} \target opacity-prop + \o \l{#Number}{Number} + \o The opacity for a widget. Possible values are from 0 + (transparent) to 255 (opaque). For the moment, this is + only supported for \l{QToolTip}{tooltips}. + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_ToolTipLabel_Opacity} style hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 68 + + \row + \o \bold{\c padding} \target padding-prop + \o \l{#Box Lengths}{Box Lengths} + \o The widget's padding. Equivalent to specifying \c + padding-top, \c padding-right, \c padding-bottom, and \c + padding-left. + + This property is supported by QAbstractItemView + subclasses, QAbstractSpinBox subclasses, QCheckBox, + QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, + QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, + and QToolTip. + + If this property is not specified, it defaults to \c 0. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 69 + + See also \l{#margin-prop}{margin}, + \l{#spacing-prop}{spacing}, and \l{The Box Model}. + + \row + \o \c padding-top + \o \l{#Length}{Length} + \o The widget's top padding. + + \row + \o \c padding-right + \o \l{#Length}{Length} + \o The widget's right padding. + + \row + \o \c padding-bottom + \o \l{#Length}{Length} + \o The widget's bottom padding. + + \row + \o \c padding-left + \o \l{#Length}{Length} + \o The widget's left padding. + + \row + \o \bold{\c paint-alternating-row-colors-for-empty-area} + \target paint-alternating-row-colors-for-empty-area-prop + \o \c bool + \o Whether the QTreeView paints alternating row colors for the empty + area (i.e the area where there are no items) + + \row + \o \bold{\c position} \target position-prop + \o \c relative \BR + | \c absolute + \o Whether offsets specified using \l{Qt Style Sheets Reference#left-prop}{left}, + \l{#right-prop}{right}, \l{Qt Style Sheets Reference#top-prop}{top}, and + \l{#bottom-prop}{bottom} are relative or absolute + coordinates. + + If this property is not specified, it defaults to \c + relative. + + \row + \o \bold{\c right} \target right-prop + \o \l{#Length}{Length} + \o If \l{#position-prop}{position} is \c relative (the + default), moves a \l{subcontrol} by a certain offset to + the left; specifying \tt{right: \e{x}} is then equivalent + to specifying \tt{\l{Qt Style Sheets Reference#left-prop}{left}: -\e{x}}. + + If \l{#position-prop}{position} is \c absolute, the \c + right property specifies the subcontrol's right edge in + relation to the parent's right edge (see also + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}). + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 70 + + See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{Qt Style Sheets Reference#top-prop}{top}, and + \l{#bottom-prop}{bottom}. + + \row + \o \bold{\c selection-background-color*} \target selection-background-color-prop + \o \l{#Brush}{Brush} \BR + \o The background of selected text or items. + + This property is supported by all widgets that respect + the \l QWidget::palette and that show selection text. + + If this property is not set, the default value is + whatever is set for the palette's + \l{QPalette::}{Highlight} role. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 71 + + See also \l{#selection-color-prop}{selection-color} and + \l{Qt Style Sheets Reference#background-prop}{background}. + + \row + \o \bold{\c selection-color*} \target selection-color-prop + \o \l{#Brush}{Brush} \BR + \o The foreground of selected text or items. + + This property is supported by all widgets that respect + the \l QWidget::palette and that show selection text. + + If this property is not set, the default value is + whatever is set for the palette's + \l{QPalette::}{HighlightedText} role. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 72 + + See also + \l{#selection-background-color-prop}{selection-background-color} + and \l{#color-prop}{color}. + + \row + \o \bold{\c show-decoration-selected*} \target show-decoration-selected-prop + \o \l{#Boolean}{Boolean} + \o Controls whether selections in a QListView cover the + entire row or just the extent of the text. + + If this property is not specified, it defaults to the + value specified by the current style for the + \l{QStyle::}{SH_ItemView_ShowDecorationSelected} style + hint. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 73 + + \row + \o \bold{\c spacing*} \target spacing-prop + \o \l{#Length}{Length} + \o Internal spacing in the widget. + + This property is supported by QCheckBox, checkable + \l{QGroupBox}es, QMenuBar, and QRadioButton. + + If this property is not specified, the default value + depends on the widget and on the current style. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 74 + + See also \l{Qt Style Sheets Reference#padding-prop}{padding} and + \l{#margin-prop}{margin}. + + \row + \o \bold{\c subcontrol-origin*} \target subcontrol-origin-prop + \o \l{#Origin}{Origin} + \o The origin rectangle of the \l subcontrol within the + parent element. + + If this property is not specified, the default is \c + padding. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 75 + + See also + \l{Qt Style Sheets Reference#subcontrol-position-prop}{subcontrol-position}. + + \row + \o \bold{\c subcontrol-position*} \target subcontrol-position-prop + \o \l{#Alignment}{Alignment} + \o The alignment of the \l subcontrol within the origin + rectangle specified by \l{Qt Style Sheets Reference#subcontrol-origin-prop} + {subcontrol-origin}. + + If this property is not specified, it defaults to a value + that depends on the subcontrol. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 76 + + See also + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}. + + \row + \o \bold{\c text-align} \target text-align-prop + \o \l{#Alignment}{Alignment} + \o The alignment of text and icon within the contents of the widget. + + If this value is not specified, it defaults to the value + that depends on the native style. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 77 + + This property is currently supported only by QPushButton + and QProgressBar. + + \row + \o \bold{\c text-decoration} + \o \c none \BR + \c underline \BR + \c overline \BR + \c line-through + \o Additional text effects + + \row + \o \bold{\c top} \target top-prop + \o \l{#Length}{Length} + \o If \l{#position-prop}{position} is \c relative (the + default), moves a \l{subcontrol} by a certain offset + down. + + If \l{#position-prop}{position} is \c absolute, the \c top + property specifies the subcontrol's top edge in relation + to the parent's top edge (see also + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}). + + If this property is not specified, it defaults to \c 0. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 78 + + See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{#right-prop}{right}, and + \l{#bottom-prop}{bottom}. + + \row + \o \bold{\c width} \target width-prop + \o \l{#Length}{Length} + \o The width of a \l{subcontrol} (or a widget in some cases). + + If this property is not specified, it defaults to a value + that depends on the subcontrol/widget and on the current style. + + \warning Unless otherwise specified, this property has no effect + when set on widgets. If you want a widget with a fixed width, set + the \l{#min-width-prop}{min-width} and + \l{#max-width-prop}{max-width} to the same value. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 79 + + See also \l{#height-prop}{height}. + + \endtable + + \target list of icons + \section1 List of Icons + + Icons used in Qt can be customized using the following properties. Each of + the properties listed in this section have the type \l{#Icon}{Icon}. + + Note that for icons to appear in buttons in a QDialogButtonBox, you need to + set the dialogbuttonbox-buttons-have-icons property to true. Also, to + customize the size of the icons, use the icon-size property. + + \table 100% + \header + \o Name + \o QStyle::StandardPixmap + + \row + \o backward-icon + \o QStyle::SP_ArrowBack + + \row + \o cd-icon + \o QStyle::SP_DriveCDIcon + + \row + \o computer-icon + \o QStyle::SP_ComputerIcon + + \row + \o desktop-icon + \o QStyle::SP_DesktopIcon + + \row + \o dialog-apply-icon + \o QStyle::SP_DialogApplyButton + + \row + \o dialog-cancel-icon + \o QStyle::SP_DialogCancelButton + + \row + \o dialog-close-icon + \o QStyle::SP_DialogCloseButton + + \row + \o dialog-discard-icon + \o QStyle::SP_DialogDiscardButton + + \row + \o dialog-help-icon + \o QStyle::SP_DialogHelpButton + + \row + \o dialog-no-icon + \o QStyle::SP_DialogNoButton + + \row + \o dialog-ok-icon + \o QStyle::SP_DialogOkButton + + \row + \o dialog-open-icon + \o QStyle::SP_DialogOpenButton + + \row + \o dialog-reset-icon + \o QStyle::SP_DialogResetButton + + \row + \o dialog-save-icon + \o QStyle::SP_DialogSaveButton + + \row + \o dialog-yes-icon + \o QStyle::SP_DialogYesButton + + \row + \o directory-closed-icon + \o QStyle::SP_DirClosedIcon + + \row + \o directory-icon + \o QStyle::SP_DirIcon + + \row + \o directory-link-icon + \o QStyle::SP_DirLinkIcon + + \row + \o directory-open-icon + \o QStyle::SP_DirOpenIcon + + \row + \o dockwidget-close-icon + \o QStyle::SP_DockWidgetCloseButton + + \row + \o downarrow-icon + \o QStyle::SP_ArrowDown + + \row + \o dvd-icon + \o QStyle::SP_DriveDVDIcon + + \row + \o file-icon + \o QStyle::SP_FileIcon + + \row + \o file-link-icon + \o QStyle::SP_FileLinkIcon + + \omit + \row + \o filedialog-backward-icon + \o QStyle::SP_FileDialogBack + \endomit + + \row + \o filedialog-contentsview-icon + \o QStyle::SP_FileDialogContentsView + + \row + \o filedialog-detailedview-icon + \o QStyle::SP_FileDialogDetailedView + + \row + \o filedialog-end-icon + \o QStyle::SP_FileDialogEnd + + \row + \o filedialog-infoview-icon + \o QStyle::SP_FileDialogInfoView + + \row + \o filedialog-listview-icon + \o QStyle::SP_FileDialogListView + + \row + \o filedialog-new-directory-icon + \o QStyle::SP_FileDialogNewFolder + + \row + \o filedialog-parent-directory-icon + \o QStyle::SP_FileDialogToParent + + \row + \o filedialog-start-icon + \o QStyle::SP_FileDialogStart + + \row + \o floppy-icon + \o QStyle::SP_DriveFDIcon + + \row + \o forward-icon + \o QStyle::SP_ArrowForward + + \row + \o harddisk-icon + \o QStyle::SP_DriveHDIcon + + \row + \o home-icon + \o QStyle::SP_DirHomeIcon + + \row + \o leftarrow-icon + \o QStyle::SP_ArrowLeft + + \row + \o messagebox-critical-icon + \o QStyle::SP_MessageBoxCritical + + \row + \o messagebox-information-icon + \o QStyle::SP_MessageBoxInformation + + \row + \o messagebox-question-icon + \o QStyle::SP_MessageBoxQuestion + + \row + \o messagebox-warning-icon + \o QStyle::SP_MessageBoxWarning + + \row + \o network-icon + \o QStyle::SP_DriveNetIcon + + \row + \o rightarrow-icon + \o QStyle::SP_ArrowRight + + \row + \o titlebar-contexthelp-icon + \o QStyle::SP_TitleBarContextHelpButton + + \row + \o titlebar-maximize-icon + \o QStyle::SP_TitleBarMaxButton + + \row + \o titlebar-menu-icon + \o QStyle::SP_TitleBarMenuButton + + \row + \o titlebar-minimize-icon + \o QStyle::SP_TitleBarMinButton + + \row + \o titlebar-normal-icon + \o QStyle::SP_TitleBarNormalButton + + \row + \o titlebar-shade-icon + \o QStyle::SP_TitleBarShadeButton + + \row + \o titlebar-unshade-icon + \o QStyle::SP_TitleBarUnshadeButton + + \row + \o trash-icon + \o QStyle::SP_TrashIcon + + \row + \o uparrow-icon + \o QStyle::SP_ArrowUp + + \endtable + + \section1 List of Property Types + + The following table summarizes the syntax and meaning of the + different property types. + + \table 100% + \header + \o Type + \o Syntax + \o Description + + \row + \o \bold Alignment \target Alignment + \o \{ \c top \BR + | \c bottom \BR + | \c left \BR + | \c right \BR + | \c center \}* + \o Horizontal and/or vertical alignment. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 80 + + \row + \o \bold Attachment \target Attachment + \o \{ \c scroll \BR + | \c fixed \}* + \o Scroll or fixed attachment. + + \row + \o \bold Background \target Background + \o \{ \l{#Brush}{Brush} \BR + | \l{#Url}{Url} \BR + | \l{#Repeat}{Repeat} \BR + | \l{#Alignment}{Alignment} \}* + \o A sequence of \l{#Brush}{Brush}, \l{#Url}{Url}, + \l{#Repeat}{Repeat}, and \l{#Alignment}{Alignment}. + + \row + \o \bold Boolean \target Boolean + \o 0 | 1 + \o True (\c 1) or false (\c 0). + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 81 + + \row + \o \bold Border \target Border + \o \{ \l{#Border Style}{Border Style} \BR + | \l{#Length}{Length} \BR + | \l{#Brush}{Brush} \}* + \o Shorthand border property. + + \row + \o \bold{Border Image} \target Border Image + \o \c none \BR + | \l{Url} \l{Number}\{4\} \BR (\c stretch | \c repeat){0,2} + \o A border image is an image that is composed of nine parts + (top left, top center, top right, center left, center, + center right, bottom left, bottom center, and bottom + right). When a border of a certain size is required, the + corner parts are used as is, and the top, right, bottom, + and left parts are stretched or repeated to produce a + border with the desired size. + + See the + \l{http://www.w3.org/TR/css3-background/#the-border-image} + {CSS3 Draft Specification} for details. + + \row + \o \bold{Border Style} \target Border Style + \o \c dashed \BR + | \c dot-dash \BR + | \c dot-dot-dash \BR + | \c dotted \BR + | \c double \BR + | \c groove \BR + | \c inset \BR + | \c outset \BR + | \c ridge \BR + | \c solid \BR + | \c none + \o Specifies the pattern used to draw a border. + See the \l{http://www.w3.org/TR/css3-background/#border-style} + {CSS3 Draft Specification} for details. + + \row + \o \bold{Box Colors} \target Box Colors + \o \l{#Brush}{Brush}\{1,4\} + \o One to four occurrences of \l{#Brush}{Brush}, specifying the top, + right, bottom, and left edges of a box, respectively. If + the left color is not specified, it is taken to be the + same as the right color. If the bottom color is not + specified, it is taken to be the same as the top color. If + the right color is not specified, it is taken to be the + same as the top color. + + Example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 82 + + \row + \o \bold{Box Lengths} \target Box Lengths + \o \l{#Length}{Length}\{1,4\} + \o One to four occurrences of \l{#Length}{Length}, specifying the + top, right, bottom, and left edges of a box, + respectively. If the left length is not specified, it is + taken to be the same as the right length. If the bottom + length is not specified, is it taken to be the same as the + top length. If the right length is not specified, it is + taken to be the same as the top length. + + Examples: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 83 + + \row + \o \bold{Brush} \target Brush + \o \l{#Color}{Color} \BR + | \l{Gradient} \BR + | \l{PaletteRole} + \o Specifies a Color or a Gradient or an entry in the Palette. + + \row + \o \bold{Color} \target Color + \o \tt{rgb(\e{r}, \e{g}, \e{b})} \BR + | \tt{rgba(\e{r}, \e{g}, \e{b}, \e{a})} \BR + | \tt{hsv(\e{h}, \e{s}, \e{v})} \BR + | \tt{hsva(\e{h}, \e{s}, \e{v}, \e{a})} \BR + | \tt{#\e{rrggbb}} \BR + | \l{QColor::setNamedColor()}{Color Name} \BR + \o Specifies a color as RGB (red, green, blue) or RGBA + (red, green, blue, alpha) or HSV (hue, saturation, value) or HSVA + (hue, saturation, value, alpha) or a named color. The \c rgb() or \c rgba() + syntax can be used with integer values between 0 and 255, or with + percentages. The value of s, v, and a in \c hsv() or \c hsva() must all + be in the range 0-255; the value of h must be in the range 0-359. + + Examples: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 84 + + \note The RGB colors allowed are the same as those allowed with + CSS 2.1, as listed + \l{http://www.w3.org/TR/CSS21/syndata.html#color-units}{here}. + + \row + \o \bold{Font} \target Font + \o (\l{#Font Style}{Font Style} | \l{#Font Weight}{Font Weight}){0,2} \l{#Font Size}{Font Size} String + \o Shorthand font property. + + \row + \o \bold{Font Size} \target Font Size + \o \l{Length} + \o The size of a font. + + \row + \o \bold{Font Style} \target Font Style + \o \c normal \BR + | \c italic \BR + | \c oblique + \o The style of a font. + + \row + \o \bold{Font Weight} \target Font Weight + \o \c normal \BR + | \c bold \BR + | \c 100 \BR + | \c 200 \BR + ... \BR + | \c 900 + \o The weight of a font. + + \row + \o \bold{Gradient} \target Gradient + \o \c qlineargradient \BR + | \c qradialgradient \BR + | \c qconicalgradient + \o Specifies gradient fills. There are three types of gradient fills: + + \list + \o \e{Linear} gradients interpolate colors between start and + end points. + \o \e{Radial} gradients interpolate colors between a focal + point and end points on a circle surrounding it. + \o \e{Conical} gradients interpolate colors around a center + point. + \endlist + + Gradients are specified in Object Bounding Mode. Imagine the box + in which the gradient is rendered, to have its top left corner at (0, 0) + and its bottom right corner at (1, 1). Gradient parameters are + then specified as percentages from 0 to 1. These values are + extrapolated to actual box coordinates at runtime. It is possible + specify values that lie outside the bounding box (-0.6 or 1.8, for + instance). + + \warning The stops have to appear sorted in ascending order. + + Examples: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 85 + + \row + \o \bold{Icon} \target Icon + \o (\l{#Url}{Url} (\c disabled | \c active | \c normal | \c selected)? + (\c on | \c off)? )* + \o A list of url, QIcon::Mode and QIcon::State. + + Example: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 86 + + \row + \o \bold{Length} \target Length + \o \l{#Number}{Number} (\c px | \c pt | \c em | \c ex)? + \o A number followed by a measurement unit. The CSS standard recommends + that user agents must + \l{http://www.w3.org/TR/CSS21/syndata.html#illegalvalues}{ignore} + a declaration with an illegal value. In Qt, it is mandatory to + specify measurement units. For compatibility with earlier versions + of Qt, numbers without measurement units are treated as pixels + in most contexts. The supported units are: + + \list + \o \c px: pixels + \o \c pt: the size of one point (i.e., 1/72 of an inch) + \o \c em: the em width of the font (i.e., the width of 'M') + \o \c ex: the ex width of the font (i.e., the height of 'x') + \endlist + + \row + \o \bold{Number} \target Number + \o A decimal integer or a real number + \o Examples: \c 0, \c 18, \c +127, \c -255, \c 12.34, \c -.5, + \c 0009. + + \row + \o \bold{Origin} \target Origin + \o \c margin \BR + | \c border \BR + | \c padding \BR + | \c content + \o Indicates which of four rectangles to use. + + \list + \o \c margin: The margin rectangle. The margin falls outside the border. + \o \c border: The border rectangle. This is where any border is drawn. + \o \c padding: The padding rectangle. Unlike the margins, + padding is located inside the border. + \o \c content: The content rectangle. This specifies where + the actual contents go, excluding any + padding, border, or margin. + \endlist + + See also \l{The Box Model}. + + \row + \o \bold{PaletteRole} \target PaletteRole + \o \c alternate-base \BR + | \c base \BR + | \c bright-text \BR + | \c button \BR + | \c button-text \BR + | \c dark \BR + | \c highlight \BR + | \c highlighted-text \BR + | \c light \BR + | \c link \BR + | \c link-visited \BR + | \c mid \BR + | \c midlight \BR + | \c shadow \BR + | \c text \BR + | \c window \BR + | \c window-text \BR + \o These values correspond the \l{QPalette::ColorRole}{Color roles} + in the widget's QPalette. + + For example, + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 87 + + \row + \o \bold{Radius} \target Radius + \o \l{#Length}{Length}\{1, 2\} + \o One or two occurrences of \l{#Length}{Length}. If only one length is + specified, it is used as the radius of the quarter circle + defining the corner. If two lengths are specified, the + first length is the horizontal radius of a quarter + ellipse, whereas the second length is the vertical radius. + + \row + \o \bold{Repeat} \target Repeat + \o \c repeat-x \BR + | \c repeat-y \BR + | \c repeat \BR + | \c no-repeat + \o A value indicating the nature of repetition. + + \list + \o \c repeat-x: Repeat horizontally. + \o \c repeat-y: Repeat vertically. + \o \c repeat: Repeat horizontally and vertically. + \o \c no-repeat: Don't repeat. + \endlist + + \row + \o \bold{Url} \target Url + \o \tt{url(\e{filename})} + \o \tt{\e{filename}} is the name of a file on the local disk + or stored using \l{the Qt Resource System}. Setting an + image implicitly sets the width and height of the element. + + \endtable + + \section1 List of Pseudo-States + + The following pseudo-states are supported: + + \table 100% + \header + \o Pseudo-State + \o Description + + \row \o \c :active \target active + \o This state is set when the widget resides in an active window. + + \row + \o \c :adjoins-item \target adjoins-item-ps + \o This state is set when the \l{#branch-sub}{::branch} of a QTreeView + is adjacent to an item. + + \row + \o \c :alternate \target alternate-ps + \o This state is set for every alternate row whe painting the row of + a QAbstractItemView when QAbstractItemView::alternatingRowColors() + is set to true. + + \row + \o \c :bottom \target bottom-ps + \o The item is positioned at the bottom. For example, a QTabBar + that has its tabs positioned at the bottom. + + \row + \o \c :checked \target checked-ps + \o The item is checked. For example, the + \l{QAbstractButton::checked}{checked} state of QAbstractButton. + + \row + \o \c :closable \target closable-ps + \o The items can be closed. For example, the QDockWidget has the + QDockWidget::DockWidgetClosable feature turned on. + + \row + \o \c :closed \target closed-ps + \o The item is in the closed state. For example, an non-expanded + item in a QTreeView + + \row + \o \c :default \target default-ps + \o The item is the default. For example, a + \l{QPushButton::default}{default} QPushButton or a default action + in a QMenu. + + \row + \o \c :disabled \target disabled-ps + \o The item is \l{QWidget::enabled}{disabled}. + + \row + \o \c :editable \target editable-ps + \o The QComboBox is editable. + + \row + \o \c :edit-focus \target edit-focus-ps + \o The item has edit focus (See QStyle::State_HasEditFocus). This state + is available only for Qt Extended applications. + + \row + \o \c :enabled \target enabled-ps + \o The item is \l{QWidget::enabled}{enabled}. + + \row + \o \c :exclusive \target exclusive-ps + \o The item is part of an exclusive item group. For example, a menu + item in a exclusive QActionGroup. + + \row + \o \c :first \target first-ps + \o The item is the first (in a list). For example, the first + tab in a QTabBar. + + \row + \o \c :flat \target flat-ps + \o The item is flat. For example, a + \l{QPushButton::flat}{flat} QPushButton. + + \row + \o \c :floatable \target floatable-ps + \o The items can be floated. For example, the QDockWidget has the + QDockWidget::DockWidgetFloatable feature turned on. + + \row + \o \c :focus \target focus-ps + \o The item has \l{QWidget::hasFocus()}{input focus}. + + \row + \o \c :has-children \target has-children-ps + \o The item has children. For example, an item in a + QTreeView that has child items. + + \row + \o \c :has-siblings \target has-siblings-ps + \o The item has siblings. For example, an item in a + QTreeView that siblings. + + \row + \o \c :horizontal \target horizontal-ps + \o The item has horizontal orientation + + \row + \o \c :hover \target hover-ps + \o The mouse is hovering over the item. + + \row + \o \c :indeterminate \target indeterminate-ps + \o The item has indeterminate state. For example, a QCheckBox + or QRadioButton is \l{Qt::PartiallyChecked}{partially checked}. + + \row + \o \c :last \target last-ps + \o The item is the last (in a list). For example, the last + tab in a QTabBar. + + \row + \o \c :left \target left-ps + \o The item is positioned at the left. For example, a QTabBar + that has its tabs positioned at the left. + + \row + \o \c :maximized \target maximized-ps + \o The item is maximized. For example, a maximized QMdiSubWindow. + + \row + \o \c :middle \target middle-ps + \o The item is in the middle (in a list). For example, a tab + that is not in the beginning or the end in a QTabBar. + + \row + \o \c :minimized \target minimized-ps + \o The item is minimized. For example, a minimized QMdiSubWindow. + + \row + \o \c :movable \target movable-ps + \o The item can be moved around. For example, the QDockWidget has the + QDockWidget::DockWidgetMovable feature turned on. + + \row + \o \c :no-frame \target no-frame-ps + \o The item has no frame. For example, a frameless QSpinBox + or QLineEdit. + + \row + \o \c :non-exclusive \target non-exclusive-ps + \o The item is part of a non-exclusive item group. For example, a menu + item in a non-exclusive QActionGroup. + + \row + \o \c :off \target off-ps + \o For items that can be toggled, this applies to items + in the "off" state. + + \row + \o \c :on \target on-ps + \o For items that can be toggled, this applies to widgets + in the "on" state. + + \row + \o \c :only-one \target only-one-ps + \o The item is the only one (in a list). For example, a lone tab + in a QTabBar. + + \row + \o \c :open \target open-ps + \o The item is in the open state. For example, an expanded + item in a QTreeView, or a QComboBox or QPushButton with + an open menu. + + \row + \o \c :next-selected \target next-selected-ps + \o The next item (in a list) is selected. For example, the + selected tab of a QTabBar is next to this item. + + \row + \o \c :pressed \target pressed-ps + \o The item is being pressed using the mouse. + + \row + \o \c :previous-selected \target previous-selected-ps + \o The previous item (in a list) is selected. For example, a + tab in a QTabBar that is next to the selected tab. + + \row + \o \c :read-only \target read-only-ps + \o The item is marked read only or non-editable. For example, + a read only QLineEdit or a non-editable QComboBox. + + \row + \o \c :right \target right-ps + \o The item is positioned at the right. For example, a QTabBar + that has its tabs positioned at the right. + + \row + \o \c :selected \target selected-ps + \o The item is selected. For example, the selected tab in + a QTabBar or the selected item in a QMenu. + + \row + \o \c :top \target top-ps + \o The item is positioned at the top. For example, a QTabBar + that has its tabs positioned at the top. + + \row + \o \c :unchecked \target unchecked-ps + \o The item is + \l{QAbstractButton::checked}{unchecked}. + + \row + \o \c :vertical \target vertical-ps + \o The item has vertical orientation. + + \row + \o \c :window \target window-ps + \o The widget is a window (i.e top level widget) + + \endtable + + \target subcontrols + \section1 List of Sub-Controls + + The following subcontrols are available: + + \table 100% + \header + \o Sub-Control + \o Description + + \row + \o \c ::add-line \target add-line-sub + \o The button to add a line of a QScrollBar. + + \row + \o \c ::add-page \target add-page-sub + \o The region between the handle (slider) and the \l{#add-line-sub}{add-line} + of a QScrollBar. + + \row + \o \c ::branch \target branch-sub + \o The branch indicator of a QTreeView. + + \row + \o \c ::chunk \target chunk-sub + \o The progress chunk of a QProgressBar. + + \row + \o \c ::close-button \target close-button-sub + \o The close button of a QDockWidget or tabs of QTabBar + + \row + \o \c ::corner \target corner-sub + \o The corner between two scrollbars in a QAbstractScrollArea + + \row + \o \c ::down-arrow \target down-arrow-sub + \o The down arrow of a QComboBox, QHeaderView (sort indicator), + QScrollBar or QSpinBox. + + \row + \o \c ::down-button \target down-button-sub + \o The down button of a QScrollBar or a QSpinBox. + + \row + \o \c ::drop-down \target drop-down-sub + \o The drop-down button of a QComboBox. + + \row + \o \c ::float-button \target float-button-sub + \o The float button of a QDockWidget + + \row + \o \c ::groove \target groove-sub + \o The groove of a QSlider. + + \row + \o \c ::indicator \target indicator-sub + \o The indicator of a QAbstractItemView, a QCheckBox, a QRadioButton, + a checkable QMenu item or a checkable QGroupBox. + + \row + \o \c ::handle \target handle-sub + \o The handle (slider) of a QScrollBar, a QSplitter, or a QSlider. + + \row + \o \c ::icon \target icon-sub + \o The icon of a QAbstractItemView or a QMenu. + + \row + \o \c ::item \target item-sub + \o An item of a QAbstractItemView, a QMenuBar, a QMenu, or + a QStatusBar. + + \row + \o \c ::left-arrow \target left-arrow-sub + \o The left arrow of a QScrollBar. + + \row + \o \c ::left-corner \target left-corner-sub + \o The left corner of a QTabWidget. For example, this control can be + used to control position the left corner widget in a QTabWidget. + + \row + \o \c ::menu-arrow \target menu-arrow-sub + \o The arrow of a QToolButton with a menu. + + \row + \o \c ::menu-button \target menu-button-sub + \o The menu button of a QToolButton. + + \row + \o \c ::menu-indicator \target menu-indicator-sub + \o The menu indicator of a QPushButton. + + \row + \o \c ::right-arrow \target right-arrow-sub + \o The right arrow of a QMenu or a QScrollBar. + + \row + \o \c ::pane \target pane-sub + \o The pane (frame) of a QTabWidget. + + \row + \o \c ::right-corner \target right-corner-sub + \o The right corner of a QTabWidget. For example, this control can be + used to control the position the right corner widget in a QTabWidget. + + \row + \o \c ::scroller \target scroller-sub + \o The scroller of a QMenu or QTabBar. + + \row + \o \c ::section \target section-sub + \o The section of a QHeaderView. + + \row + \o \c ::separator \target separator-sub + \o The separator of a QMenu or in a QMainWindow. + + \row + \o \c ::sub-line \target sub-line-sub + \o The button to subtract a line of a QScrollBar. + + \row + \o \c ::sub-page \target sub-page-sub + \o The region between the handle (slider) and the \l{#sub-line-sub}{sub-line} + of a QScrollBar. + + \row + \o \c ::tab \target tab-sub + \o The tab of a QTabBar or QToolBox. + + \row + \o \c ::tab-bar \target tab-bar-sub + \o The tab bar of a QTabWidget. This subcontrol exists only to + control the position of the QTabBar inside the QTabWidget. To + style the tabs using the \l{#tab-sub}{::tab} subcontrol. + + \row + \o \c ::tear \target tear-sub + \o The tear indicator of a QTabBar. + + \row + \o \c ::tearoff \target tearoff-sub + \o The tear-off indicator of a QMenu. + + \row + \o \c ::text \target text-ps + \o The text of a QAbstractItemView. + + \row + \o \c ::title \target title-sub + \o The title of a QGroupBox or a QDockWidget. + + \row + \o \c ::up-arrow \target up-arrow-sub + \o The up arrow of a QHeaderView (sort indicator), QScrollBar + or a QSpinBox. + + \row + \o \c ::up-button \target up-button-sub + \o The up button of a QSpinBox. + + \endtable + + See \l{Customizing the QPushButton's Menu Indicator Sub-Control} + for an example of how to customize a subcontrol. + */ + +/*! + \page stylesheet-examples.html + \contentspage {Qt Style Sheet}{Contents} + \previouspage Qt Style Sheets Reference + \title Qt Style Sheets Examples + + We will now see a few examples to get started with using Qt Style Sheets. + + \tableofcontents + \section1 Style Sheet Usage + + \section2 Customizing the Foreground and Background Colors + + Let's start by setting yellow as the background color of all + \l{QLineEdit}s in an application. This could be achieved like + this: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 88 + + If we want the property to apply only to the \l{QLineEdit}s that are + children (or grandchildren or grand-grandchildren) of a specific dialog, + we would rather do this: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 89 + + If we want the property to apply only to one specific QLineEdit, + we can give it a name using QObject::setObjectName() and use an + ID Selector to refer to it: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 90 + + Alternatively, we can set the + \l{Qt Style Sheets Reference#background-prop}{background-color} property directly on the + QLineEdit, omitting the selector: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 91 + + To ensure a good contrast, we should also specify a suitable + color for the text: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 92 + + It might be a good idea to change the colors used for selected + text as well: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 93 + + + \section2 Customizing Using Dynamic Properties + + There are many situations where we need to present a form that + has mandatory fields. To indicate to the user that the field is + mandatory, one effective (albeit esthetically dubious) solution + is to use yellow as the background color for those fields. It + turns out this is very easy to implement using Qt Style Sheets. + First, we would use the following application-wide style sheet: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 94 + + This means that every widget whose \c mandatoryField Qt property + is set to true would have a yellow background. + + Then, for each mandatory field widget, we would simply create a + \c mandatoryField property on the fly and set it to true. For + example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.cpp 95 + + \section2 Customizing a QPushButton Using the Box Model + + This time, we will show how to create a red QPushButton. This + QPushButton would presumably be connected to a very destructive + piece of code. + + First, we are tempted to use this style sheet: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 96 + + However, the result is a boring, flat button with no borders: + + \image stylesheet-redbutton1.png A flat red button + + What happened is this: + + \list + \o We have made a request that cannot be satisfied using the + native styles alone (e.g., the Windows XP theme engine doesn't + let us specify the background color of a button). + \o Therefore, the button is rendered using style sheets. + \o We haven't specified any values for + \l{Qt Style Sheets Reference#border-width-prop}{border-width} and + \l{Qt Style Sheets Reference#border-style-prop}{border-style}, so by default we obtain + a 0-pixel wide border of style \c none. + \endlist + + Let's improve the situation by specifying a border: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 97 + + \image stylesheet-redbutton2.png A red button with a beige border + + Things look already a lot better. But the button looks a bit + cramped. Let's specify some spacing between the border and the + text using the \l{Qt Style Sheets Reference#padding-prop}{padding}. Additionally, we will + enforce a minimum width, round the corners, and specify a larger + font to make the button look nicer: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 98 + + \image stylesheet-redbutton3.png A red button with a round beige border and big, bold text + + The only issue remaining is that the button doesn't react when we + press it. We can fix this by specifying a slightly different + background color and use a different border style. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 99 + + \section2 Customizing the QPushButton's Menu Indicator Sub-Control + + Subcontrols give access to the sub-elements of a widget. For + example, a QPushButton associated with a menu (using + QPushButton::setMenu()) has a menu indicator. Let's customize + the menu indicator for the red push button: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 100 + + By default, the menu indicator is located at the bottom-right + corner of the padding rectangle. We can change this by specifying + \l{Qt Style Sheets Reference#subcontrol-position-prop}{subcontrol-position} and + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} to anchor the + indicator differently. We can also use \l{Qt Style Sheets Reference#top-prop}{top} and + \l{Qt Style Sheets Reference#left-prop}{left} to move the indicator by a few pixels. For + example: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 101 + + This positions the \c myindicator.png to the center right of the + QPushButton's \l{Qt Style Sheets Reference#padding-prop}{padding} rectangle (see + \l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin} for more + information). + + \section2 Complex Selector Example + + Since red seems to be our favorite color, let's make the text in + QLineEdit red by setting the following application-wide + stylesheet: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 102 + + However, we would like to give a visual indication that a + QLineEdit is read-only by making it appear gray: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 103 + + At some point, our design team comes with the requirement that + all \l{QLineEdit}s in the registration form (with the + \l{QObject::objectName}{object name} \c registrationDialog) to be + brown: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 104 + + A few UI design meetings later, we decide that all our + \l{QDialog}s should have brown colored \l{QLineEdit}s: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 105 + + Quiz: What happens if we have a read-only QLineEdit in a QDialog? + [Hint: The \l{The Style Sheet Syntax#Conflict Resolution}{Conflict Resolution} section above explains + what happens in cases like this.] + + \section1 Customizing specific widgets + + This section provides examples to customize specific widgets using Style Sheets. + + \section2 Customizing QAbstractScrollArea + + The background of any QAbstractScrollArea (Item views, QTextEdit + and QTextBrowser) can be set using the background properties. For example, + to set a background-image that scrolls with the scroll bar: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 106 + + If the background-image is to be fixed with the viewport: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 107 + + \section2 Customizing QCheckBox + + Styling of a QCheckBox is almost indentical to styling a QRadioButton. The + main difference is that a tristate QCheckBox has an indeterminate state. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 108 + + \section2 Customizing QComboBox + + We will look at an example where the drop down button of a QComboBox + appears "merged" with the combo box frame. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 109 + + The pop-up of the QComboBox is a QAbstractItemView and is styled using + the descendant selector: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 110 + + \section2 Customizing QDockWidget + + The title bar and the buttons of a QDockWidget can be customized as + follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 111 + + If one desires to move the dock widget buttons to the left, the following + style sheet can be used: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 112 + + \note To customize the separator (resize handle) of a QDockWidget, + use QMainWindow::separator. + + \section2 Customizing QFrame + + A QFrame is styled using the \l{The Box Model}. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 113 + + \section2 Customizing QGroupBox + + Let us look at an example that moves the QGroupBox's title to + the center. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 114 + + For a checkable QGroupBox, use the \{#indicator-sub}{::indicator} subcontrol + and style it exactly like a QCheckBox (i.e) + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 115 + + \section2 Customizing QHeaderView + + QHeaderView is customized as follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 116 + + \section2 Customizing QLineEdit + + The frame of a QLineEdit is styled using the \l{The Box Model}. To + create a line edit with rounded corners, we can set: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 117 + + The password character of line edits that have QLineEdit::Password + echo mode can be set using: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 118 + + The background of a read only QLineEdit can be modified as below: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 119 + + \section2 Customizing QListView + + The background color of alternating rows can be customized using the following + style sheet: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 120 + + To provide a special background when you hover over items, we can use the + \l{item-sub}{::item} subcontrol. For example, + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 121 + + \section2 Customizing QMainWindow + + The separator of a QMainWindow can be styled as follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 122 + + \section2 Customizing QMenu + + Individual items of a QMenu are styled using the 'item' subcontrol as + follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 123 + + For a more advanced customization, use a style sheet as follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 124 + + \section2 Customizing QMenuBar + + QMenuBar is styled as follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 125 + + \section2 Customizing QProgressBar + + The QProgressBar's \l{stylesheet-reference.html#border-prop}{border}, + \l{stylesheet-reference.html#chunk-sub}{chunk}, and + \l{stylesheet-reference.html#text-align-prop}{text-align} can be customized using + style sheets. However, if one property or sub-control is customized, + all the other properties or sub-controls must be customized as well. + + \image progressBar-stylesheet.png + + For example, we change the \l{stylesheet-reference.html#border-prop} + {border} to grey and the \l{stylesheet-reference.html#chunk-sub}{chunk} + to cerulean. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 126 + + This leaves the \l{stylesheet-reference.html#text-align-prop} + {text-align}, which we customize by positioning the text in the center of + the progress bar. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 127 + + A \l{stylesheet-reference.html#margin-prop}{margin} can be included to + obtain more visible chunks. + + \image progressBar2-stylesheet.png + + In the screenshot above, we use a + \l{stylesheet-reference.html#margin-prop}{margin} of 0.5 pixels. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 128 + + \section2 Customizing QPushButton + + A QPushButton is styled as follows: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 129 + + For a QPushButton with a menu, use the + \l{Qt Style Sheets Reference#menu-indicator-sub}{::menu-indicator} + subcontrol. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 130 + + Checkable QPushButton have the \l{Qt Style Sheets Reference#checked-ps} + {:checked} pseudo state set. + + \section2 Customizing QRadioButton + + The indicator of a QRadioButton can be changed using: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 131 + + \section2 Customizing QScrollBar + + The QScrollBar can be styled using its subcontrols like + \l{stylesheet-reference.html#handle-sub}{handle}, + \l{stylesheet-reference.html#add-line-sub}{add-line}, + \l{stylesheet-reference.html#sub-line-sub}{sub-line}, and so on. Note that + if one property or sub-control is customized, all the other properties or + sub-controls must be customized as well. + + \image stylesheet-scrollbar1.png + + The scroll bar above has been styled in aquamarine with a solid grey + border. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 132 + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 133 + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 134 + + The \l{stylesheet-reference.html#left-arrow-sub}{left-arrow} and + \l{stylesheet-reference.html#right-arrow-sub}{right-arrow} have a solid grey + border with a white background. As an alternative, you could also embed the + image of an arrow. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 135 + + If you want the scroll buttons of the scroll bar to be placed together + (instead of the edges) like on Mac OS X, you can use the following + stylesheet: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 136 + + The scroll bar using the above stylesheet looks like this: + \image stylesheet-scrollbar2.png + + + To customize a vertical scroll bar use a style sheet similar to the following: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 137 + + \section2 Customizing QSizeGrip + + QSizeGrip is usually styled by just setting an image. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 138 + + \section2 Customizing QSlider + + You can style horizontal slider as below: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 139 + + If you want to change the color of the slider parts before and after the handle, you can use the add-page + and sub-page subcontrols. For example, for a vertical slider: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 140 + + \section2 Customizing QSpinBox + + QSpinBox can be completely customized as below (the style sheet has commentary inline): + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 141 + + + \section2 Customizing QSplitter + + A QSplitter derives from a QFrame and hence can be styled like a QFrame. + The grip or the handle is customized using the + \l{Qt Style Sheets Reference#handle-sub}{::handle} subcontrol. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 142 + + \section2 Customizing QStatusBar + + We can provide a background for the status bar and a border for items + inside the status bar as follows: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 143 + + Note that widgets that have been added to the QStatusBar can be styled + using the descendant declaration (i.e) + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 144 + + \section2 Customizing QTabWidget and QTabBar + + \image tabWidget-stylesheet1.png + + For the screenshot above, we need a stylesheet as follows: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 145 + + Often we require the tabs to overlap to look like below: + \image tabWidget-stylesheet2.png + + For a tab widget that looks like above, we make use of + \l{http://www.communitymx.com/content/article.cfm?cid=B0029} + {negative margins}. The resulting stylesheet looks like this: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 146 + + To move the tab bar to the center (as below), we require the following stylesheet: + \image tabWidget-stylesheet3.png + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 147 + + The tear indicator and the scroll buttons can be further customized as follows: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 148 + + Since Qt 4.6 the close button can be customized as follow: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 159 + + \section2 Customizing QTableView + + Suppose we'd like our selected item in QTableView to have bubblegum pink + fade to white as its background. + + \image tableWidget-stylesheet.png + + This is possible with the + \l{stylesheet-reference.html#selection-background-color-prop} + {selection-background-color} property and the syntax required is: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 149 + + The corner widget can be customized using the following style sheet + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 150 + + \section2 Customizing QToolBar + + The background and the handle of a QToolBar is customized as below: + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 151 + + \section2 Customizing QToolBox + + The tabs of the QToolBox are customized using the 'tab' subcontrol. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 152 + + \section2 Customizing QToolButton + + There are three types of QToolButtons. + \list + \i The QToolButton has no menu. In this case, the QToolButton is styled + exactly like QPushButton. See + \l{#Customizing QPushButton}{Customizing QPushButton} for an + example. + + \i The QToolButton has a menu and has the QToolButton::popupMode set to + QToolButton::DelayedPopup or QToolButton::InstantPopup. In this case, + the QToolButton is styled exactly like a QPushButton with a menu. + See \l{#Customizing QPushButton}{Customizing QPushButton} for an + example of the usage of the menu-indicator pseudo state. + + \i The QToolButton has its QToolButton::popupMode set to + QToolButton::MenuButtonPopup. In this case, we style it as follows: + \endlist + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 153 + + + \section2 Customizing QToolTip + + QToolTip is customized exactly like a QLabel. In addition, for platforms + that support it, the opacity property may be set to adjust the opacity. + + For example, + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 154 + + \section2 Customizing QTreeView + + The background color of alternating rows can be customized using the following + style sheet: + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 155 + + To provide a special background when you hover over items, we can use the + \l{item-sub}{::item} subcontrol. For example, + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 156 + + The branches of a QTreeView are styled using the + \l{Qt Style Sheets Reference#branch-sub}{::branch} subcontrol. The + following stylesheet color codes the various states when drawing + a branch. + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 157 + + Colorful, though it is, a more useful example can be made using the + following images: + + \table + \row + \o \inlineimage stylesheet-vline.png + \o \inlineimage stylesheet-branch-more.png + \o \inlineimage stylesheet-branch-end.png + \o \inlineimage stylesheet-branch-closed.png + \o \inlineimage stylesheet-branch-open.png + \row + \o vline.png + \o branch-more.png + \o branch-end.png + \o branch-closed.png + \o branch-open.png + \endtable + + \snippet doc/src/snippets/code/doc_src_stylesheet.qdoc 158 + + The resulting tree view looks like this: + + \image stylesheet-treeview.png + + \sa {Style Sheet Example}, {Supported HTML Subset}, QStyle + + + \section1 Common mistakes + + This section lists some common mistakes when using stylesheets. + + \section2 QPushButton and images + + When styling a QPushButton, it is often desirable to use an image as the + button graphic. It is common to try the + \l{Qt Style Sheets Reference#background-image-prop}{background-image} + property, + but this has a number of drawbacks: For instance, the background will + often appear hidden behind the button decoration, because it is not + considered a background. In addition, if the button is resized, the + entire background will be stretched or tiled, which does not + always look good. + + It is better to use the + \l{Qt Style Sheets Reference#border-image-prop}{border-image} + property, as it will always display the image, + regardless of the background (you can combine it with a background if it + has alpha values in it), and it has special settings to deal with button + resizing. + + Consider the following snippet: + + \snippet doc/src/snippets/stylesheet/common-mistakes.cpp 1 + + This will produce a button looking like this: + + \image stylesheet-border-image-normal.png + + The numbers after the url gives the top, right, bottom and left number of + pixels, respectively. These numbers correspond to the border and should not + stretch when the size changes. + Whenever you resize the button, the middle part of the image will stretch + in both directions, while the pixels specified in the stylesheet + will not. This makes the borders of the button look more natural, like + this: + + \table + \row + \o \inlineimage stylesheet-border-image-stretched.png + \row + \o With borders + \endtable + + \table + \row + \o \inlineimage stylesheet-border-image-wrong.png + \row + \o Without borders + \endtable + + */ diff --git a/doc/src/widgets/widgets-and-layouts/widgets.qdoc b/doc/src/widgets/widgets-and-layouts/widgets.qdoc new file mode 100644 index 0000000000..f3f65b67eb --- /dev/null +++ b/doc/src/widgets/widgets-and-layouts/widgets.qdoc @@ -0,0 +1,162 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page widgets-and-layouts.html + \title Widgets and Layouts + \ingroup qt-gui-concepts + \brief The primary elements for designing user interfaces in Qt. + + \section1 Widgets + + Widgets are the primary elements for creating user interfaces in Qt. + \l{The Widget Classes}{Widgets} can display data and status information, + receive user input, and provide a container for other widgets that + should be grouped together. A widget that is not embedded in a + parent widget is called a \l{Window and Dialog Widgets} {window}. + + \image parent-child-widgets.png A parent widget containing various child widgets. + + The QWidget class provides the basic capability to render to the + screen, and to handle user input events. All UI elements that Qt + provides are either subclasses of QWidget, or are used in connection + with a QWidget subclass. Creating custom widgets is done by + subclassing QWidget or a suitable subclass and reimplementing the + virtual event handlers. + + \section1 Layouts + + \l{Layout Management}{Layouts} are an elegant and flexible way to + automatically arrange child widgets within their container. Each + widget reports its size requirements to the layout through the + \l{QWidget::}{sizeHint} and \l{QWidget::}{sizePolicy} properties, + and the layout distributes the available space accordingly. + + \table + \row + \o \image qgridlayout-with-5-children.png + \o \image qformlayout-with-6-children.png + \endtable + + \l{Qt Designer Manual}{\QD} is a powerful tool for interactively creating and + arranging widgets in layouts. + + \section1 Widget Styles + + \l{Styles and Style Aware Widgets}{Styles} draw on behalf of + widgets and encapsulate the look and feel of a GUI. Qt's built-in + widgets use the QStyle class to perform nearly all of their drawing, + ensuring that they look exactly like the equivalent native widgets. + + \table + \row + \o \image windowsxp-tabwidget.png + \o \image plastique-tabwidget.png + \o \image macintosh-tabwidget.png + \endtable + + \l{Qt Style Sheets} are a powerful mechanism that allows you to customize the + appearance of widgets, in addition to what is already possible by subclassing QStyle. + + \section1 The Widget Classes + + The following sections list the widget classes. See the \l{Qt Widget + Gallery} for some examples. + + \section2 Basic Widgets + + These basic widgets (controls), e.g. buttons, comboboxes and + scroll bars, are designed for direct use. + + \table + \row + \o \image windows-label.png + \o \image windowsvista-pushbutton.png + \o \image gtk-progressbar.png + \row + \o \image plastique-combobox.png + \o \image macintosh-radiobutton.png + \o \image cde-lineedit.png + \endtable + + \annotatedlist basicwidgets + + \section2 Advanced Widgets + + Advanced GUI widgets, e.g. tab widgets and progress bars, provide + more complex user interface controls. + + \table + \row + \o \image windowsxp-treeview.png + \o \image gtk-calendarwidget.png + \o \image qundoview.png + \endtable + + \annotatedlist advanced + + \table + \row + \o \image windowsvista-tabwidget.png + \o \image macintosh-groupbox.png + \endtable + + \section2 Organizer Widgets + + Classes like splitters, tab bars, button groups, etc are used for + organizing and grouping GUI primitives into more complex + applications and dialogs. + + \annotatedlist organizers + + \section2 Abstract Widget Classes + + The abstract widget classes are base classes. They are not usable as + standalone classes but provide functionality when they are subclassed. + + \annotatedlist abstractwidgets +*/ + +/*! + \group advanced + \title Advanced Widgets +*/ + +/*! + \group abstractwidgets + \title Abstract Widget Classes +*/ + +/*! + \group basicwidgets + \title Basic Widgets +*/ + +/*! + \group organizers + \title Organizers +*/ diff --git a/doc/src/widgets/widgets-tutorial.qdoc b/doc/src/widgets/widgets-tutorial.qdoc new file mode 100644 index 0000000000..a90c01447a --- /dev/null +++ b/doc/src/widgets/widgets-tutorial.qdoc @@ -0,0 +1,249 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page widgets-tutorial.html + \ingroup tutorials + \title Widgets Tutorial + \brief This tutorial covers basic usage of widgets and layouts, showing how + they are used to build GUI applications. + + \section1 Introduction + + Widgets are the basic building blocks for graphical user interface + (GUI) applications built with Qt. Each GUI component (e.g. + buttons, labels, text editor) is a \l{QWidget}{widget} that is + placed somewhere within a user interface window, or is displayed + as an independent window. Each type of widge is provided by a + subclass of QWidget, which is itself a subclass of QObject. + + QWidget is not an abstract class. It can be used as a container + for other widgets, and it can be subclassed with minimal effort to + create new, custom widgets. QWidget is often used to create a + window inside which other \l{QWidget}s are placed. + + As with \l{QObject}s, \l{QWidget}s can be created with parent + objects to indicate ownership, ensuring that objects are deleted + when they are no longer used. With widgets, these parent-child + relationships have an additional meaning: Each child widget is + displayed within the screen area occupied by its parent widget. + This means that when you delete a window widget, all the child + widgets it contains are also deleted. + + \section1 Writing a main Function + + Many of the GUI examples provided with Qt follow the pattern of + having a \c{main.cpp} file, which contains the standard code to + initialize the application, plus any number of other source/header + files that contain the application logic and custom GUI components. + + A typical \c main() function in \c{main.cpp} looks like this: + + \snippet doc/src/snippets/widgets-tutorial/template.cpp main.cpp body + + First, a QApplication object is constructed, which can be + configured with arguments passed in from the command line. After + the widgets have been created and shown, QApplication::exec() is + called to start Qt's event loop. Control passes to Qt until this + function returns. Finally, \c{main()} returns the value returned + by QApplication::exec(). + + \section1 Simple widget examples + + Each of theses simple widget examples is written entirely within + the \c main() function. + + \list + \o \l {tutorials/widgets/toplevel} {Creating a window} + + \o \l {tutorials/widgets/childwidget} {Creating child widgets} + + \o \l {tutorials/widgets/windowlayout} {Using layouts} + + \o \l {tutorials/widgets/nestedlayouts} {Nested layouts} + \endlist + + \section1 Real world widget examples + + In these \l{Widget examples} {more advanced examples}, the code + that creates the widgets and layouts is stored in other files. For + example, the GUI for a main window may be created in the + constructor of a QMainWindow subclass. + + \section1 Building The Examples + + If you installed a binary package to get Qt, or if you compiled Qt + yourself, the examples described in this tutorial should already + be built and ready to run. If you wish to modify and recompile + them, follow these steps: + + \list 1 + + \o From a command prompt, enter the directory containing the + example you have modified. + + \o Type \c qmake and press \key{Return}. If this doesn't work, + make sure that the executable is on your path, or enter its + full location. + + \o On Linux/Unix and Mac OS X, type \c make and press + \key{Return}; on Windows with Visual Studio, type \c nmake and + press \key{Return}. + + \endlist + + An executable file is created in the current directory. On + Windows, this file may be located in a \c debug or \c release + subdirectory. You can run this executable to see the example code + at work. +*/ + +/*! + \example tutorials/widgets/toplevel + \title Widgets Tutorial - Creating a Window + + If a widget is created without a parent, it is treated as a window, or + \e{top-level widget}, when it is shown. Since it has no parent object to + ensure that it is deleted when no longer needed, it is up to the + developer to keep track of the top-level widgets in an application. + + In the following example, we use QWidget to create and show a window with + a default size: + + \div {class="qt-code"} + \table + \row + \o \snippet tutorials/widgets/toplevel/main.cpp main program + \o \inlineimage widgets-tutorial-toplevel.png + \endtable + \enddiv + + To create a real GUI, we need to place widgets inside the window. To do + this, we pass a QWidget instance to a widget's constructor, as we will + demonstrate in the next part of this tutorial. + +*/ + +/*! + \example tutorials/widgets/childwidget + \title Widgets Tutorial - Child Widgets + + We can add a child widget to the window created in the previous example by + passing \c window as the parent to its constructor. In this case, we add a + button to the window and place it in a specific location: + + \div {class="qt-code"} + \table + \row + \o \snippet tutorials/widgets/childwidget/main.cpp main program + \o \inlineimage widgets-tutorial-childwidget.png + \endtable + \enddiv + + The button is now a child of the window and will be deleted when the + window is destroyed. Note that hiding or closing the window does not + automatically destroy it. It will be destroyed when the example exits. +*/ + +/*! + \example tutorials/widgets/windowlayout + \title Widgets Tutorial - Using Layouts + + Usually, child widgets are arranged inside a window using layout objects + rather than by specifying positions and sizes explicitly. Here, we + construct a label and line edit widget that we would like to arrange + side-by-side. + + \div {class="qt-code"} + \table + \row + \o \snippet tutorials/widgets/windowlayout/main.cpp main program + \o \inlineimage widgets-tutorial-windowlayout.png + \endtable + \enddiv + + The \c layout object we construct manages the positions and sizes of + widgets supplied to it with the \l{QHBoxLayout::}{addWidget()} function. + The layout itself is supplied to the window itself in the call to + \l{QWidget::}{setLayout()}. Layouts are only visible through the effects + they have on the widgets (and other layouts) they are responsible for + managing. + + In the example above, the ownership of each widget is not immediately + clear. Since we construct the widgets and the layout without parent + objects, we would expect to see an empty window and two separate windows + containing a label and a line edit. However, when we tell the layout to + manage the label and line edit and set the layout on the window, both the + widgets and the layout itself are ''reparented'' to become children of + the window. +*/ + +/*! + \example tutorials/widgets/nestedlayouts + \title Widgets Tutorial - Nested Layouts + + Just as widgets can contain other widgets, layouts can be used to provide + different levels of grouping for widgets. Here, we want to display a + label alongside a line edit at the top of a window, above a table view + showing the results of a query. + + We achieve this by creating two layouts: \c{queryLayout} is a QHBoxLayout + that contains QLabel and QLineEdit widgets placed side-by-side; + \c{mainLayout} is a QVBoxLayout that contains \c{queryLayout} and a + QTableView arranged vertically. + + \div {class="qt-code"} + \table + \row + \o \snippet tutorials/widgets/nestedlayouts/main.cpp first part + \snippet tutorials/widgets/nestedlayouts/main.cpp last part + \o \inlineimage widgets-tutorial-nestedlayouts.png + \endtable + \enddiv + + Note that we call the \c{mainLayout}'s \l{QBoxLayout::}{addLayout()} + function to insert the \c{queryLayout} above the \c{resultView} table. + + We have omitted the code that sets up the model containing the data shown + by the QTableView widget, \c resultView. For completeness, we show this below. + + As well as QHBoxLayout and QVBoxLayout, Qt also provides QGridLayout + and QFormLayout classes to help with more complex user interfaces. + These can be seen if you run \l{Qt Designer}. + + \section1 Setting up the Model + + In the code above, we did not show where the table's data came from + because we wanted to concentrate on the use of layouts. Here, we see + that the model holds a number of items corresponding to rows, each of + which is set up to contain data for two columns. + + \snippet tutorials/widgets/nestedlayouts/main.cpp set up the model + + The use of models and views is covered in the + \l{Item Views Examples} and in the \l{Model/View Programming} overview. +*/ diff --git a/doc/src/widgets/windows-and-dialogs/dialogs.qdoc b/doc/src/widgets/windows-and-dialogs/dialogs.qdoc new file mode 100644 index 0000000000..54f8c05e39 --- /dev/null +++ b/doc/src/widgets/windows-and-dialogs/dialogs.qdoc @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group standard-dialogs + \ingroup qt-gui-concepts + \title Standard Dialogs + \brief A list of Qt classes for implementing standard dialogs. +*/ + +/*! + \page dialogs.html + \title Dialog Windows + \ingroup qt-gui-concepts + \brief An overview over dialog windows. + + \previouspage Application Main Window + \contentspage Application Windows and Dialogs + \nextpage Desktop Integration + + Dialogs can be \e{modal}, in which case the user is required to provide + necessary information before work in the main window + can continue, or \e{modeless}. Modeless dialogs do not prevent the user from + interacting with any of the other windows in the application. + + Qt provides a set of ready-made dialogs for file, font, color-selection + and more. + + \annotatedlist standard-dialogs + + Custom dialogs can be easily created by composing regular widgets into + a QDialog. These classes are specifically designed for building custom + dialogs: + + \annotatedlist dialog-classes +*/ diff --git a/doc/src/widgets/windows-and-dialogs/mainwindow.qdoc b/doc/src/widgets/windows-and-dialogs/mainwindow.qdoc new file mode 100644 index 0000000000..f2b29c9d5b --- /dev/null +++ b/doc/src/widgets/windows-and-dialogs/mainwindow.qdoc @@ -0,0 +1,261 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group mainwindow-classes + \title Main Window and Related Classes +*/ + +/*! + \page application-windows.html + \title Window and Dialog Widgets + \brief Windows and Dialogs in Qt. + \ingroup qt-gui-concepts + + A \l{Widgets Tutorial}{widget} that is not embedded in a parent widget is called a window. + (Usually, windows have a frame and a title bar, although it is also possible to create + windows without such decoration using suitable window flags). In Qt, QMainWindow + and the various subclasses of QDialog are the most common window types. + + In applications, windows provide the screen space upon which the user + interface is built. Windows separate applications visually from each other + and usually provide a window decoration that allows the user to resize and + position the applications according to his preferences. Windows are typically + integrated into the desktop environment and to some degree managed by the + window management system that the desktop environment provides. For instance, + selected windows of an application are represented in the task bar. + + \section1 Primary and Secondary Windows + + Any QWidget that has no parent will become a window, and will on most platforms + be listed in the desktop's task bar. This is usually only wanted for one + window in the application, the \e{primary window}. + + In addition, a QWidget that has a parent can become a window by setting the + \l{Qt::WindowType}{Qt::WA_Window} flag. Depending on the window management system + such \e{secondary windows} are usually stacked on top of their respective parent + window, and not have a task bar entry of their own. + + The QMainWindow and the QDialog classes set the Qt::WA_Window flag in their + constructor, as they are designed to be used as windows and provide facilities + that are not wanted for child widgets. + + \section1 Main Windows and Dialogs + + The \l{Application Main Window} provides the framework for building the + application's main user interface, and are created by subclassing QMainWindow. + QMainWindow has its own layout to which you can add a \l{QMenuBar}{menu bar}, + \l{QToolBar}{tool bars}, \l{QDockWidget}{dockable widgets} and a + \l{QStatusBar}{status bar}. The center area can be occupied by any kind of + QWidget. + + \l{Dialog Windows} are used as secondary windows that present the user with + options and choices. Dialogs are created by subclassing QDialog and using + \l{Widgets and Layouts}{widgets and layouts} to implement the user interface. + In addition, Qt provides a number of ready-made standard dialogs that can be + used for standard tasks like file or font selection. + + Both main windows and dialogs can be created with \QD, Qt's visual design tool. + Using \QD is a lot faster than hand-coding, and makes it easy to test different + design ideas. Creating designs visually and reading the code generated by + \l{uic} is a great way to learn Qt! + + \keyword window geometry + \section1 Window Geometry + + QWidget provides several functions that deal with a widget's + geometry. Some of these functions operate on the pure client area + (i.e. the window excluding the window frame), others include the + window frame. The differentiation is done in a way that covers the + most common usage transparently. + + \list + \o \bold{Including the window frame:} + \l{QWidget::x()}{x()}, + \l{QWidget::y()}{y()}, + \l{QWidget::frameGeometry()}{frameGeometry()}, + \l{QWidget::pos()}{pos()}, and + \l{QWidget::move()}{move()}. + \o \bold{Excluding the window frame:} + \l{QWidget::geometry()}{geometry()}, + \l{QWidget::width()}{width()}, + \l{QWidget::height()}{height()}, + \l{QWidget::rect()}{rect()}, and + \l{QWidget::size()}{size()}. + \endlist + + Note that the distinction only matters for decorated top-level + widgets. For all child widgets, the frame geometry is equal to the + widget's client geometry. + + This diagram shows most of the functions in use: + \img geometry.png Geometry diagram + + \section2 X11 Peculiarities + + On X11, a window does not have a frame until the window manager + decorates it. This happens asynchronously at some point in time + after calling QWidget::show() and the first paint event the + window receives, or it does not happen at all. Bear in mind that + X11 is policy-free (others call it flexible). Thus you cannot + make any safe assumption about the decoration frame your window + will get. Basic rule: There's always one user who uses a window + manager that breaks your assumption, and who will complain to + you. + + Furthermore, a toolkit cannot simply place windows on the screen. All + Qt can do is to send certain hints to the window manager. The window + manager, a separate process, may either obey, ignore or misunderstand + them. Due to the partially unclear Inter-Client Communication + Conventions Manual (ICCCM), window placement is handled quite + differently in existing window managers. + + X11 provides no standard or easy way to get the frame geometry + once the window is decorated. Qt solves this problem with nifty + heuristics and clever code that works on a wide range of window + managers that exist today. Don't be surprised if you find one + where QWidget::frameGeometry() returns wrong results though. + + Nor does X11 provide a way to maximize a window. + QWidget::showMaximized() has to emulate the feature. Its result + depends on the result of QWidget::frameGeometry() and the + capability of the window manager to do proper window placement, + neither of which can be guaranteed. +*/ + +/*! + \page mainwindow.html + \title Application Main Window + \ingroup qt-gui-concepts + \brief Creating the application window. + + \tableofcontents + + \section1 Overview of the Main Window Classes + + These classes provide everything you need for a typical modern main + application window, like the main window itself, menu and tool bars, + a status bar, etc. + + \annotatedlist mainwindow-classes + + \section1 The Main Window Classes + + Qt 4 provides the following classes for managing main windows and + associated user interface components: + + \list + \o QMainWindow remains the central class around which applications + can be built. The interface to this class has been simplified, and + much of the functionality previously included in this class is now + present in the companion QDockWidget and QToolBar classes. + + \o QDockWidget provides a widget that can be used to create + detachable tool palettes or helper windows. Dock widgets keep track + of their own properties, and they can be moved, closed, and floated + as external windows. + + \o QToolBar provides a generic toolbar widget that can hold a + number of different action-related widgets, such as buttons, + drop-down menus, comboboxes, and spin boxes. The emphasis on a + unified action model in Qt 4 means that toolbars cooperate well + with menus and keyboard shortcuts. + \endlist + + \section1 Example Code + + Using QMainWindow is straightforward. Generally, we subclass + QMainWindow and set up menus, toolbars, and dock widgets inside + the QMainWindow constructor. + + To add a menu bar to the main window, we simply create the menus, and + add them to the main window's menu bar. Note that the + QMainWindow::menuBar() function will automatically create the menu bar + the first time it is called. You can also call + QMainWindow::setMenuBar() to use a custom menu bar in the main window. + + \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 0 + \dots + \snippet examples/mainwindows/menus/mainwindow.cpp 5 + \dots + + Once actions have been created, we can add them to the main window + components. To begin with, we add them to the pop-up menus: + + \snippet examples/mainwindows/menus/mainwindow.cpp 10 + \dots + \snippet examples/mainwindows/menus/mainwindow.cpp 11 + \dots + + The QToolBar and QMenu classes use Qt's action system to provide a + consistent API. In the above code, some existing actions were added to + the file menu with the QMenu::addAction() function. QToolBar also + provides this function, making it easy to reuse actions in different + parts of the main window. This avoids unnecessary duplication of work. + + We create a toolbar as a child of the main window, and add the desired + actions to it: + + \snippet examples/mainwindows/sdi/mainwindow.cpp 0 + \dots + \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 1 + + In this example, the toolbar is restricted to the top and bottom + toolbar areas of the main window, and is initially placed in the + top tool bar area. We can see that the actions specified by \c + newAct and \c openAct will be displayed both on the toolbar and in + the file menu. + + QDockWidget is used in a similar way to QToolBar. We create a + dock widget as a child of the main window, and add widgets as children + of the dock widget: + + \snippet doc/src/snippets/dockwidgets/mainwindow.cpp 0 + + In this example, the dock widget can only be placed in the left and + right dock areas, and it is initially placed in the left dock area. + + The QMainWindow API allows the programmer to customize which dock + widget areas occupy the four corners of the dock widget area. If + required, the default can be changed with the + QMainWindow::setCorner() function: + + \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 2 + + The following diagram shows the configuration produced by the above code. + Note that the left and right dock widgets will occupy the top and bottom + corners of the main window in this layout. + + \image mainwindow-docks-example.png + + Once all of the main window components have been set up, the central widget + is created and installed by using code similar to the following: + + \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 3 + + The central widget can be any subclass of QWidget. +*/ diff --git a/doc/src/windows-and-dialogs/dialogs.qdoc b/doc/src/windows-and-dialogs/dialogs.qdoc deleted file mode 100644 index 54f8c05e39..0000000000 --- a/doc/src/windows-and-dialogs/dialogs.qdoc +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group standard-dialogs - \ingroup qt-gui-concepts - \title Standard Dialogs - \brief A list of Qt classes for implementing standard dialogs. -*/ - -/*! - \page dialogs.html - \title Dialog Windows - \ingroup qt-gui-concepts - \brief An overview over dialog windows. - - \previouspage Application Main Window - \contentspage Application Windows and Dialogs - \nextpage Desktop Integration - - Dialogs can be \e{modal}, in which case the user is required to provide - necessary information before work in the main window - can continue, or \e{modeless}. Modeless dialogs do not prevent the user from - interacting with any of the other windows in the application. - - Qt provides a set of ready-made dialogs for file, font, color-selection - and more. - - \annotatedlist standard-dialogs - - Custom dialogs can be easily created by composing regular widgets into - a QDialog. These classes are specifically designed for building custom - dialogs: - - \annotatedlist dialog-classes -*/ diff --git a/doc/src/windows-and-dialogs/mainwindow.qdoc b/doc/src/windows-and-dialogs/mainwindow.qdoc deleted file mode 100644 index f2b29c9d5b..0000000000 --- a/doc/src/windows-and-dialogs/mainwindow.qdoc +++ /dev/null @@ -1,261 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \group mainwindow-classes - \title Main Window and Related Classes -*/ - -/*! - \page application-windows.html - \title Window and Dialog Widgets - \brief Windows and Dialogs in Qt. - \ingroup qt-gui-concepts - - A \l{Widgets Tutorial}{widget} that is not embedded in a parent widget is called a window. - (Usually, windows have a frame and a title bar, although it is also possible to create - windows without such decoration using suitable window flags). In Qt, QMainWindow - and the various subclasses of QDialog are the most common window types. - - In applications, windows provide the screen space upon which the user - interface is built. Windows separate applications visually from each other - and usually provide a window decoration that allows the user to resize and - position the applications according to his preferences. Windows are typically - integrated into the desktop environment and to some degree managed by the - window management system that the desktop environment provides. For instance, - selected windows of an application are represented in the task bar. - - \section1 Primary and Secondary Windows - - Any QWidget that has no parent will become a window, and will on most platforms - be listed in the desktop's task bar. This is usually only wanted for one - window in the application, the \e{primary window}. - - In addition, a QWidget that has a parent can become a window by setting the - \l{Qt::WindowType}{Qt::WA_Window} flag. Depending on the window management system - such \e{secondary windows} are usually stacked on top of their respective parent - window, and not have a task bar entry of their own. - - The QMainWindow and the QDialog classes set the Qt::WA_Window flag in their - constructor, as they are designed to be used as windows and provide facilities - that are not wanted for child widgets. - - \section1 Main Windows and Dialogs - - The \l{Application Main Window} provides the framework for building the - application's main user interface, and are created by subclassing QMainWindow. - QMainWindow has its own layout to which you can add a \l{QMenuBar}{menu bar}, - \l{QToolBar}{tool bars}, \l{QDockWidget}{dockable widgets} and a - \l{QStatusBar}{status bar}. The center area can be occupied by any kind of - QWidget. - - \l{Dialog Windows} are used as secondary windows that present the user with - options and choices. Dialogs are created by subclassing QDialog and using - \l{Widgets and Layouts}{widgets and layouts} to implement the user interface. - In addition, Qt provides a number of ready-made standard dialogs that can be - used for standard tasks like file or font selection. - - Both main windows and dialogs can be created with \QD, Qt's visual design tool. - Using \QD is a lot faster than hand-coding, and makes it easy to test different - design ideas. Creating designs visually and reading the code generated by - \l{uic} is a great way to learn Qt! - - \keyword window geometry - \section1 Window Geometry - - QWidget provides several functions that deal with a widget's - geometry. Some of these functions operate on the pure client area - (i.e. the window excluding the window frame), others include the - window frame. The differentiation is done in a way that covers the - most common usage transparently. - - \list - \o \bold{Including the window frame:} - \l{QWidget::x()}{x()}, - \l{QWidget::y()}{y()}, - \l{QWidget::frameGeometry()}{frameGeometry()}, - \l{QWidget::pos()}{pos()}, and - \l{QWidget::move()}{move()}. - \o \bold{Excluding the window frame:} - \l{QWidget::geometry()}{geometry()}, - \l{QWidget::width()}{width()}, - \l{QWidget::height()}{height()}, - \l{QWidget::rect()}{rect()}, and - \l{QWidget::size()}{size()}. - \endlist - - Note that the distinction only matters for decorated top-level - widgets. For all child widgets, the frame geometry is equal to the - widget's client geometry. - - This diagram shows most of the functions in use: - \img geometry.png Geometry diagram - - \section2 X11 Peculiarities - - On X11, a window does not have a frame until the window manager - decorates it. This happens asynchronously at some point in time - after calling QWidget::show() and the first paint event the - window receives, or it does not happen at all. Bear in mind that - X11 is policy-free (others call it flexible). Thus you cannot - make any safe assumption about the decoration frame your window - will get. Basic rule: There's always one user who uses a window - manager that breaks your assumption, and who will complain to - you. - - Furthermore, a toolkit cannot simply place windows on the screen. All - Qt can do is to send certain hints to the window manager. The window - manager, a separate process, may either obey, ignore or misunderstand - them. Due to the partially unclear Inter-Client Communication - Conventions Manual (ICCCM), window placement is handled quite - differently in existing window managers. - - X11 provides no standard or easy way to get the frame geometry - once the window is decorated. Qt solves this problem with nifty - heuristics and clever code that works on a wide range of window - managers that exist today. Don't be surprised if you find one - where QWidget::frameGeometry() returns wrong results though. - - Nor does X11 provide a way to maximize a window. - QWidget::showMaximized() has to emulate the feature. Its result - depends on the result of QWidget::frameGeometry() and the - capability of the window manager to do proper window placement, - neither of which can be guaranteed. -*/ - -/*! - \page mainwindow.html - \title Application Main Window - \ingroup qt-gui-concepts - \brief Creating the application window. - - \tableofcontents - - \section1 Overview of the Main Window Classes - - These classes provide everything you need for a typical modern main - application window, like the main window itself, menu and tool bars, - a status bar, etc. - - \annotatedlist mainwindow-classes - - \section1 The Main Window Classes - - Qt 4 provides the following classes for managing main windows and - associated user interface components: - - \list - \o QMainWindow remains the central class around which applications - can be built. The interface to this class has been simplified, and - much of the functionality previously included in this class is now - present in the companion QDockWidget and QToolBar classes. - - \o QDockWidget provides a widget that can be used to create - detachable tool palettes or helper windows. Dock widgets keep track - of their own properties, and they can be moved, closed, and floated - as external windows. - - \o QToolBar provides a generic toolbar widget that can hold a - number of different action-related widgets, such as buttons, - drop-down menus, comboboxes, and spin boxes. The emphasis on a - unified action model in Qt 4 means that toolbars cooperate well - with menus and keyboard shortcuts. - \endlist - - \section1 Example Code - - Using QMainWindow is straightforward. Generally, we subclass - QMainWindow and set up menus, toolbars, and dock widgets inside - the QMainWindow constructor. - - To add a menu bar to the main window, we simply create the menus, and - add them to the main window's menu bar. Note that the - QMainWindow::menuBar() function will automatically create the menu bar - the first time it is called. You can also call - QMainWindow::setMenuBar() to use a custom menu bar in the main window. - - \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 0 - \dots - \snippet examples/mainwindows/menus/mainwindow.cpp 5 - \dots - - Once actions have been created, we can add them to the main window - components. To begin with, we add them to the pop-up menus: - - \snippet examples/mainwindows/menus/mainwindow.cpp 10 - \dots - \snippet examples/mainwindows/menus/mainwindow.cpp 11 - \dots - - The QToolBar and QMenu classes use Qt's action system to provide a - consistent API. In the above code, some existing actions were added to - the file menu with the QMenu::addAction() function. QToolBar also - provides this function, making it easy to reuse actions in different - parts of the main window. This avoids unnecessary duplication of work. - - We create a toolbar as a child of the main window, and add the desired - actions to it: - - \snippet examples/mainwindows/sdi/mainwindow.cpp 0 - \dots - \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 1 - - In this example, the toolbar is restricted to the top and bottom - toolbar areas of the main window, and is initially placed in the - top tool bar area. We can see that the actions specified by \c - newAct and \c openAct will be displayed both on the toolbar and in - the file menu. - - QDockWidget is used in a similar way to QToolBar. We create a - dock widget as a child of the main window, and add widgets as children - of the dock widget: - - \snippet doc/src/snippets/dockwidgets/mainwindow.cpp 0 - - In this example, the dock widget can only be placed in the left and - right dock areas, and it is initially placed in the left dock area. - - The QMainWindow API allows the programmer to customize which dock - widget areas occupy the four corners of the dock widget area. If - required, the default can be changed with the - QMainWindow::setCorner() function: - - \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 2 - - The following diagram shows the configuration produced by the above code. - Note that the left and right dock widgets will occupy the top and bottom - corners of the main window in this layout. - - \image mainwindow-docks-example.png - - Once all of the main window components have been set up, the central widget - is created and installed by using code similar to the following: - - \snippet doc/src/snippets/code/doc_src_qt4-mainwindow.cpp 3 - - The central widget can be any subclass of QWidget. -*/ diff --git a/doc/src/xml/qtxml.qdoc b/doc/src/xml/qtxml.qdoc new file mode 100644 index 0000000000..20d7600935 --- /dev/null +++ b/doc/src/xml/qtxml.qdoc @@ -0,0 +1,23 @@ +/*! + \module QtXml + \title QtXml Module + \ingroup modules + \ingroup technology-apis + + \brief The QtXml module provides a stream reader and writer for + XML documents, and C++ implementations of SAX and DOM. + + To include the definitions of the module's classes, use the + following directive: + + \snippet doc/src/snippets/code/doc_src_qtxml.cpp 0 + + To link against the module, add this line to your \l qmake \c + .pro file: + + \snippet doc/src/snippets/code/doc_src_qtxml.pro 1 + + Further XML support is provided by the \l{Qt Solutions} group who + provide, for example, classes that support SOAP and MML with the + Qt XML classes. +*/ -- cgit v1.2.3