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  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

Style overview

A style in Qt implements the look and feel found in a GUI for a particular platform. For example, Windows platforms may use the Windows or Windows-XP style, Unix platforms may use the Motif style, and so on.

This is a short guide that describes the steps that are necessary to get started creating and using custom styles with the Qt 3.x style API. First, we go through the steps necessary to create a style:

  1. Pick a base style to inherit from.
  2. Re-implement the necessary functions in the derived class.
Then we explain how to use the new style from within your own applications, or as a plugin that can be used by existing Qt applications.

Creating a custom style

1. Pick a base style to inherit from.

The first step is to pick one of the base styles provided with Qt to build your custom style from. The choice will depend on what look and feel you are trying to achieve. We recommend that you choose from the QWindowsStyle derived classes or the QMotifStyle derived classes. These are the two base look and feel classes in the Qt style engine. Inheriting directly from QCommonStyle is also an option if you want to start almost from scratch when implementing your style. In this simple example we will inherit from QWindowsStyle.

2. Re-implement the necessary functions in your derived class.

Depending on which parts of the base style you want to change, you must re-implement the functions that are used to draw those parts of the interface. If you take a look at the QStyle documentation, you will find a list of the different primitives, controls and complex controls. In this example we will first change the look of the standard arrows that are used in the QWindowsStyle. The arrows are PrimitiveElements that are drawn by the drawPrimitive() function, so we need to re-implement that function. We need the following class declaration:

#include <qwindowsstyle.h>

class CustomStyle : public QWindowsStyle {
    Q_OBJECT
public:
    CustomStyle();
    ~CustomStyle();

    void drawPrimitive( PrimitiveElement pe,
                        QPainter *p,
                        const QRect & r,
                        const QColorGroup & cg,
                        SFlags flags = Style_Default,
                        const QStyleOption & = QStyleOption::Default ) const;

private:
    // Disabled copy constructor and operator=
    CustomStyle( const CustomStyle & );
    CustomStyle& operator=( const CustomStyle & );
};

Note that we disable the copy constructor and the '=' operator for our style. QObject is the base class for all style classes in Qt, and a QObject inherently cannot be copied since there are some aspects of it that are not copyable.

From the QStyle docs we see that PE_ArrowUp, PE_ArrowDown, PE_ArrowLeft and PE_ArrowRight are the primitives we need to do something with. We get the following in our drawPrimitive() function:

CustomStyle::CustomStyle()
{
}

CustomStyle::~CustomStyle()
{
}

void CustomStyle::drawPrimitive( PrimitiveElement pe,
                                 QPainter * p,
                                 const QRect & r,
                                 const QColorGroup & cg,
                                 SFlags flags,
                                 const QStyleOption & opt ) const
{
    // we are only interested in the arrows
    if (pe >= PE_ArrowUp && pe <= PE_ArrowLeft) {
        QPointArray pa( 3 );
        // make the arrow cover half the area it is supposed to be 
        // painted on
        int x = r.x();
        int y = r.y();
        int w = r.width() / 2;
        int h = r.height() / 2;
        x += (r.width() - w) / 2;
        y += (r.height() - h) /2;

        switch( pe ) {
        case PE_ArrowDown:
            pa.setPoint( 0, x, y );
            pa.setPoint( 1, x + w, y );
            pa.setPoint( 2, x + w / 2, y + h );
            break;
        case PE_ArrowUp:
            pa.setPoint( 0, x, y + h );
            pa.setPoint( 1, x + w, y + h );
            pa.setPoint( 2, x + w / 2, y );
            break;
        case PE_ArrowLeft:
            pa.setPoint( 0, x + w, y );
            pa.setPoint( 1, x + w, y + h );
            pa.setPoint( 2, x, y + h / 2 );
            break;
        case PE_ArrowRight:
            pa.setPoint( 0, x, y );
            pa.setPoint( 1, x, y + h );
            pa.setPoint( 2, x + w, y + h / 2 );
            break;
        default: break;
            
        }

        // use different colors to indicate that the arrow is 
        // enabled/disabled
        if ( flags & Style_Enabled ) {
            p->setPen( cg.mid() );
            p->setBrush( cg.brush( QColorGroup::ButtonText ) );
        } else {
            p->setPen( cg.buttonText() );
            p->setBrush( cg.brush( QColorGroup::Mid ) );
        }
        p->drawPolygon( pa );
    } else {
        // let the base style handle the other primitives
        QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, data );
    }
}

Using a custom style

There are several ways of using a custom style in a Qt application. The simplest way is to include the following lines of code in the application's main() function:

#include "customstyle.h"

int main( int argc, char ** argv )
{
    QApplication::setStyle( new CustomStyle() );
    // do the usual routine on creating your QApplication object etc.
}

Note that you must also include the customstyle.h and customstyle.cpp files in your project.

2. Creating and using a pluggable style

You may want to make your style available for use in other applications, some of which may not be yours and are not available for you to recompile. The Qt Plugin system makes it possible to create styles as plugins. Styles created as plugins are loaded as shared objects at runtime by Qt itself. Please refer to the Qt Plugin documentation for more information on how to go about creating a style plugin.

Compile your plugin and put it into $QTDIR/plugins/styles. We now have a pluggable style that Qt can load automatically. To use your new style with existing applications, simply start the application with the following argument:

./application -style custom

The application will use the look and feel from the custom style you implemented.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 80
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. 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
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 6
Page suivante

Le Qt Developer Network au hasard

Logo

QML et les styles

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 3.2
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