Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Creating Custom Qt Types

Overview

When creating user interfaces with Qt, particularly those with specialized controls and features, developers sometimes need to create new data types that can be used alongside or in place of Qt's existing set of value types.

Standard types such as QSize, QColor and QString can all be stored in QVariant objects, used as the types of properties in QObject-based classes, and emitted in signal-slot communication.

In this document, we take a custom type and describe how to integrate it into Qt's object model so that it can be stored in the same way as standard Qt types. We then show how to register the custom type to allow it to be used in signals and slots connections.

Creating a Custom Type

Before we begin, we need to ensure that the custom type we are creating meets all the requirements imposed by QMetaType. In other words, it must provide:

  • a public default constructor,
  • a public copy constructor, and
  • a public destructor.

The following Message class definition includes these members:

 class Message
 {
 public:
     Message();
     Message(const Message &other);
     ~Message();

     Message(const QString &body, const QStringList &headers);

     QString body() const;
     QStringList headers() const;

 private:
     QString m_body;
     QStringList m_headers;
 };

The class also provides a constructor for normal use and two public member functions that are used to obtain the private data.

Declaring the Type with QMetaType

The Message class only needs a suitable implementation in order to be usable. However, Qt's type system will not be able to understand how to store, retrieve and serialize instances of this class without some assistance. For example, we will be unable to store Message values in QVariant.

The class in Qt responsible for custom types is QMetaType. To make the type known to this class, we invoke the Q_DECLARE_METATYPE() macro on the class in the header file where it is defined:

 Q_DECLARE_METATYPE(Message);

This now makes it possible for Message values to be stored in QVariant objects and retrieved later. See the Custom Type Example for code that demonstrates this.

The Q_DECLARE_METATYPE() macro also makes it possible for these values to be used as arguments to signals, but only in direct signal-slot connections. To make the custom type generally usable with the signals and slots mechanism, we need to perform some extra work.

Creating and Destroying Custom Objects

Although the declaration in the previous section makes the type available for use in direct signal-slot connections, it cannot be used for queued signal-slot connections, such as those that are made between objects in different threads. This is because the meta-object system does not know how to handle creation and destruction of objects of the custom type at run-time.

To enable creation of objects at run-time, call the qRegisterMetaType() template function to register it with the meta-object system. This also makes the type available for queued signal-slot communication as long as you call it before you make the first connection that uses the type.

The Queued Custom Type Example declares a Block class which is registered in the main.cpp file:

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     ...
     qRegisterMetaType<Block>();
     ...
     return app.exec();
 }

This type is later used in a signal-slot connection in the window.cpp file:

 Window::Window()
 {
     thread = new RenderThread();
     ...
     connect(thread, SIGNAL(sendBlock(Block)), this, SLOT(addBlock(Block)));
     ...
     setWindowTitle(tr("Queued Custom Type"));
 }

If a type is used in a queued connection without being registered, a warning will be printed at the console; for example:

 QObject::connect: Cannot queue arguments of type 'Block'
 (Make sure 'Block' is registered using qRegisterMetaType().)

Making the Type Printable

It is often quite useful to make a custom type printable for debugging purposes, as in the following code:

     Message message(body, headers);
     qDebug() << "Original:" << message;

This is achieved by creating a streaming operator for the type, which is often defined in the header file for that type:

 QDebug operator<<(QDebug dbg, const Message &message);

The implementation for the Message type in the Custom Type Example goes to some effort to make the printable representation as readable as possible:

 QDebug operator<<(QDebug dbg, const Message &message)
 {
     QStringList pieces = message.body().split("\r\n", QString::SkipEmptyParts);
     if (pieces.isEmpty())
         dbg.nospace() << "Message()";
     else if (pieces.size() == 1)
         dbg.nospace() << "Message(" << pieces.first() << ")";
     else
         dbg.nospace() << "Message(" << pieces.first() << " ...)";
     return dbg.maybeSpace();
 }

The output sent to the debug stream can, of course, be made as simple or as complicated as you like. Note that the value returned by this function is the QDebug object itself, though this is often obtained by calling the maybeSpace() member function of QDebug that pads out the stream with space characters to make it more readable.

Further Reading

The Q_DECLARE_METATYPE() macro and qRegisterMetaType() function documentation contain more detailed information about their uses and limitations.

The Custom Type, Custom Type Sending and Queued Custom Type examples show how to implement a custom type with the features outlined in this document.

The Debugging Techniques document provides an overview of the debugging mechanisms discussed above.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  2. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  3. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  4. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 12
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
Page suivante

Le Qt Developer Network au hasard

Logo

Compiler l'add-in Qt de Visual Studio

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.7
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web