summaryrefslogtreecommitdiffstats
path: root/examples/forever/forever.cpp
blob: 4ee6016a0a1d55919a202bbe8527a0dfec83e7eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/****************************************************************************
**
** Copyright (C) 1992-2008 Trolltech ASA.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qtimer.h>
#include <qpainter.h>
#include <qapplication.h>
#include <stdlib.h>				// defines rand() function

#include "forever.h"


//
// Forever - a widget that draws rectangles forever.
//

//
// Constructs a Forever widget.
//

Forever::Forever( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    for (int a=0; a<numColors; a++) {
	colors[a] = QColor( rand()&255,
			    rand()&255,
			    rand()&255 );
    }
    rectangles = 0;
    startTimer( 0 );				// run continuous timer
    QTimer * counter = new QTimer( this );
    connect( counter, SIGNAL(timeout()),
	     this, SLOT(updateCaption()) );
    counter->start( 1000 );
}


void Forever::updateCaption()
{
    QString s;
    s.sprintf( "Qt Example - Forever - %d rectangles/second", rectangles );
    rectangles = 0;
    setCaption( s );
}


//
// Handles paint events for the Forever widget.
//

void Forever::paintEvent( QPaintEvent * )
{
    QPainter paint( this );			// painter object
    int w = width();
    int h = height();
    if(w <= 0 || h <= 0) 
	return;
    paint.setPen( NoPen );			// do not draw outline
    paint.setBrush( colors[rand() % numColors]);// set random brush color
    
    QPoint p1( rand()%w, rand()%h );	// p1 = top left
    QPoint p2( rand()%w, rand()%h );	// p2 = bottom right
    
    QRect r( p1, p2 );
    paint.drawRect( r );			// draw filled rectangle
}

//
// Handles timer events for the Forever widget.
//

void Forever::timerEvent( QTimerEvent * )
{
    for ( int i=0; i<100; i++ ) {
	repaint( FALSE );			// repaint, don't erase
	rectangles++;
    }
}


//
// Create and display Forever widget.
//

int main( int argc, char **argv )
{
    QApplication a( argc, argv );		// create application object
    Forever always;				// create widget
    always.resize( 400, 250 );			// start up with size 400x250
    a.setMainWidget( &always );			// set as main widget
    always.setCaption("Qt Example - Forever");
    always.show();				// show widget
    return a.exec();				// run event loop
}