Home · Examples 


Wiggly Example

Code:

The Wiggly example shows how to animate a widget using QBasicTimer and timerEvent(). In addition, the example demonstrates how to use QFontMetrics to determine the size of text on screen.

QBasicTimer is a low-level class for timers. Unlike QTimer, QBasicTimer doesn't inherit from QObject; instead of emitting a timeout() signal when a certain amount of time has passed, it sends a QTimerEvent to a QObject of our choice. This makes QBasicTimer a more lightweight alternative to QTimer. Qt's built-in widgets use it internally, and it is provided in Qt's API for highly-optimized applications (e.g., Qtopia Core applications).

The example consists of two classes:

We will first take a quick look at the Wiggly class, then we will review the WigglyWidget class.

Wiggly Class Implementation

public class Wiggly extends QDialog {
The Wiggly class provides a dialog widget that allows the user to enter a text. The text is then rendered by WigglyWidget.
    public Wiggly(QWidget parent) {
        super(parent);

        WigglyWidget wigglyWidget = new WigglyWidget(null);
        QLineEdit lineEdit = new QLineEdit();

        QVBoxLayout layout = new QVBoxLayout();
        layout.addWidget(wigglyWidget);
        layout.addWidget(lineEdit);
        setLayout(layout);

        lineEdit.textChanged.connect(wigglyWidget, "setText(String)");

        lineEdit.setText("Hello world!");

        setWindowTitle("Wiggly");
        setWindowIcon(new QIcon("classpath:com/trolltech/images/qt-logo.png"));
        resize(360, 145);
    }
In the constructor we create a wiggly widget along with a
line edit, and we put the two widgets in a vertical layout. We connect the line edit's textChanged() signal to the wiggly widget's setText() slot to obtain the real time interaction with the wiggly widget. The widget's default text is "Hello world!".
    public static void main(String args[]) {
        QApplication.initialize(args);

        Wiggly d = new Wiggly(null);
        d.show();

        QApplication.exec();
    }

}
We also provide a main() method to create and show the dialog widget when the example is run.

WigglyWidget Class Implementation

class WigglyWidget extends QWidget {
    static final int sineTable[] = { 0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38 };

    private QBasicTimer timer;
    private String text;
    private int step;
The WigglyWidget class provides the wiggly line displaying the text. We subclass
QWidget and reimplement some standard event handling methods (shown later) to draw and update the widget.

The sineTable represents y-values of the sine curve, multiplied by 100. It is used to make the wiggly widget move along the sine curve.

    WigglyWidget(QWidget parent) {
        super(parent);
        setBackgroundRole(QPalette.ColorRole.Midlight);

        QFont newFont = font();
        newFont.setPointSize(newFont.pointSize() + 20);
        setFont(newFont);
The timer variable, of type QBasicTimer, is used to update the widget at regular intervals, making the widget move. The text variable is used to store the currently displayed text, and step to calculate position and color for each character on the wiggly line.

In the constructor, we make the widget's background slightly lighter than the usual background using the QPalette::Midlight color role. The background role defines the brush from the widget's palette that Qt uses to paint the background. Then we enlarge the widget's font with 20 points.

        step = 0;

        timer = new QBasicTimer();
        timer.start(60, this);
    }
Finally we start the timer; the call to QBasicTimer::start() makes sure that this particular wiggly widget will receive the timer events generated when the timer times out (every 60 milliseconds).

We implement a public setText() slot that sets the widget's text.

    public void setText(String s) {
        text = s;
    }
The paintEvent() method is called whenever a QPaintEvent is sent to the widget. Paint events are sent to widgets that need to update themselves, for instance when part of a widget is exposed because a covering widget was moved. For the wiggly widget, a paint event will also be generated every 60 milliseconds from the timerEvent() slot.
    protected void paintEvent(QPaintEvent e) {
        QFontMetrics metrics = new QFontMetrics(font());
        int x = (width() - metrics.width(text)) / 2;
        int y = (height() + metrics.ascent() - metrics.descent()) / 2;
        QColor color = new QColor();
The QFontMetrics object provides information about the widget's font. The x variable is the horizontal position where we start drawing the text. The y variable is the vertical position of the text's base line. Both variables are computed so that the text is horizontally and vertically centered. To compute the base line, we take into account the font's ascent (the height of the font above the base line) and font's descent (the height of the font below the base line). If the descent equals the ascent, they cancel out each other and the base line is at height() / 2.
        QPainter painter = new QPainter();
        painter.begin(this);
        for (int i = 0; i < text.length(); ++i) {
            int index = (step + i) % 16;
            color.setHsv((15 - index) * 16, 255, 191);
            painter.setPen(color);
            painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), text.substring(i, i + 1));
            x += metrics.width(text.substring(i, i + 1));
        }
        painter.end();

    }
Each time the paintEvent() method is called, we create a QPainter object painter to draw the contents of the widget. For each character in text, we determine the color and the position on the wiggly line based on step. In addition, x is incremented by the character's width.

For simplicity, we assume that QFontMetrics::width(text) returns the sum of the individual character widths (QFontMetrics::width(text[i])). In practice, this is not always the case because QFontMetrics::width(text) also takes into account the kerning between certain letters (e.g., 'A' and 'V'). The result is that the text isn't perfectly centered. You can verify this by typing "AVAVAVAVAVAV" in the line edit.

    protected void timerEvent(QTimerEvent event) {
        if (event.timerId() == timer.timerId()) {
            ++step;
            update();
        } else {
            super.timerEvent(event);

        }

    }

}
The timerEvent() method receives all the timer events that are generated for this widget. If a timer event is sent from the widget's QBasicTimer, we increment step to make the text move, and call QWidget::update() to refresh the display. Any other timer event is passed on to the base class's implementation of the timerEvent() method.

The QWidget::update() slot does not cause an immediate repaint; instead the slot schedules a paint event for processing when Qt returns to the main event loop. The paint events are then handled by WigglyWidget's paintEvent() method.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Jambi 4.5.2_01