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  ·  Tous les espaces de nom  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

Shaped Clock Example

Files:

The Shaped Clock example shows how to apply a widget mask to a top-level widget to produce a shaped window.

Widget masks are used to customize the shapes of top-level widgets by restricting the available area for painting. On some window systems, setting certain window flags will cause the window decoration (title bar, window frame, buttons) to be disabled, allowing specially-shaped windows to be created. In this example, we use this feature to create a circular window containing an analog clock.

Since this example's window does not provide a File menu or a close button, we provide a context menu with an Exit entry so that the example can be closed. Click the right mouse button over the window to open this menu.

ShapedClock Class Definition

The ShapedClock class is based on the AnalogClock class defined in the Analog Clock example. The whole class definition is presented below:

 class ShapedClock : public QWidget
 {
     Q_OBJECT

 public:
     ShapedClock(QWidget *parent = 0);
     QSize sizeHint() const;

 protected:
     void mouseMoveEvent(QMouseEvent *event);
     void mousePressEvent(QMouseEvent *event);
     void paintEvent(QPaintEvent *event);
     void resizeEvent(QResizeEvent *event);

 private:
     QPoint dragPosition;
 };

The paintEvent() implementation is the same as that found in the AnalogClock class. We implement sizeHint() so that we don't have to resize the widget explicitly. We also provide an event handler for resize events. This allows us to update the mask if the clock is resized.

Since the window containing the clock widget will have no title bar, we provide implementations for mouseMoveEvent() and mousePressEvent() to allow the clock to be dragged around the screen. The dragPosition variable lets us keep track of where the user last clicked on the widget.

ShapedClock Class Implementation

The ShapedClock constructor performs many of the same tasks as the AnalogClock constructor. We set up a timer and connect it to the widget's update() slot:

 ShapedClock::ShapedClock(QWidget *parent)
     : QWidget(parent, Qt::FramelessWindowHint)
 {
     QTimer *timer = new QTimer(this);
     connect(timer, SIGNAL(timeout()), this, SLOT(update()));
     timer->start(1000);

     QAction *quitAction = new QAction(tr("E&xit"), this);
     quitAction->setShortcut(tr("Ctrl+Q"));
     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
     addAction(quitAction);

     setContextMenuPolicy(Qt::ActionsContextMenu);
     setToolTip(tr("Drag the clock with the left mouse button.\n"
                   "Use the right mouse button to open a context menu."));
     setWindowTitle(tr("Shaped Analog Clock"));
 }

We inform the window manager that the widget is not to be decorated with a window frame by setting the Qt::FramelessWindowHint flag on the widget. As a result, we need to provide a way for the user to move the clock around the screen.

Mouse button events are delivered to the mousePressEvent() handler:

 void ShapedClock::mousePressEvent(QMouseEvent *event)
 {
     if (event->button() == Qt::LeftButton) {
         dragPosition = event->globalPos() - frameGeometry().topLeft();
         event->accept();
     }
 }

If the left mouse button is pressed over the widget, we record the displacement in global (screen) coordinates between the top-left position of the widget's frame (even when hidden) and the point where the mouse click occurred. This displacement will be used if the user moves the mouse while holding down the left button. Since we acted on the event, we accept it by calling its accept() function.

The mouseMoveEvent() handler is called if the mouse is moved over the widget.

 void ShapedClock::mouseMoveEvent(QMouseEvent *event)
 {
     if (event->buttons() & Qt::LeftButton) {
         move(event->globalPos() - dragPosition);
         event->accept();
     }
 }

If the left button is held down while the mouse is moved, the top-left corner of the widget is moved to the point given by subtracting the dragPosition from the current cursor position in global coordinates. If we drag the widget, we also accept the event.

The paintEvent() function is given for completeness. See the Analog Clock example for a description of the process used to render the clock.

 void ShapedClock::paintEvent(QPaintEvent *)
 {
     static const QPoint hourHand[3] = {
         QPoint(7, 8),
         QPoint(-7, 8),
         QPoint(0, -40)
     };
     static const QPoint minuteHand[3] = {
         QPoint(7, 8),
         QPoint(-7, 8),
         QPoint(0, -70)
     };

     QColor hourColor(127, 0, 127);
     QColor minuteColor(0, 127, 127, 191);

     int side = qMin(width(), height());
     QTime time = QTime::currentTime();

     QPainter painter(this);
     painter.setRenderHint(QPainter::Antialiasing);
     painter.translate(width() / 2, height() / 2);
     painter.scale(side / 200.0, side / 200.0);

     painter.setPen(Qt::NoPen);
     painter.setBrush(hourColor);

     painter.save();
     painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
     painter.drawConvexPolygon(hourHand, 3);
     painter.restore();

     painter.setPen(hourColor);

     for (int i = 0; i < 12; ++i) {
         painter.drawLine(88, 0, 96, 0);
         painter.rotate(30.0);
     }

     painter.setPen(Qt::NoPen);
     painter.setBrush(minuteColor);

     painter.save();
     painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
     painter.drawConvexPolygon(minuteHand, 3);
     painter.restore();

     painter.setPen(minuteColor);

     for (int j = 0; j < 60; ++j) {
         if ((j % 5) != 0)
             painter.drawLine(92, 0, 96, 0);
         painter.rotate(6.0);
     }
 }

In the resizeEvent() handler, we re-use some of the code from the paintEvent() to determine the region of the widget that is visible to the user:

 void ShapedClock::resizeEvent(QResizeEvent * /* event */)
 {
     int side = qMin(width(), height());
     QRegion maskedRegion(width() / 2 - side / 2, height() / 2 - side / 2, side,
                          side, QRegion::Ellipse);
     setMask(maskedRegion);
 }

Since the clock face is a circle drawn in the center of the widget, this is the region we use as the mask.

Although the lack of a window frame may make it difficult for the user to resize the widget on some platforms, it will not necessarily be impossible. The resizeEvent() function ensures that the widget mask will always be updated if the widget's dimensions change, and additionally ensures that it will be set up correctly when the widget is first displayed.

Finally, we implement the sizeHint() for the widget so that it is given a reasonable default size when it is first shown:

 QSize ShapedClock::sizeHint() const
 {
     return QSize(100, 100);
 }

Notes on Widget Masks

Since QRegion allows arbitrarily complex regions to be created, widget masks can be made to suit the most unconventionally-shaped windows, and even allow widgets to be displayed with holes in them.

Widget masks can also be constructed by using the contents of pixmap to define the opaque part of the widget. For a pixmap with an alpha channel, a suitable mask can be obtained with QPixmap::mask().

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 78
  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 blog Digia au hasard

Logo

Créer des applications avec un style Metro avec Qt, exemples en QML et C++, un article de Digia Qt traduit par Thibaut Cuvelier

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. 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.4
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