C++: Display Color Bars

Bjarne-stroustrup
 

The task is to display a series of vertical color bars across the width of the display. The color bars should either use the system palette, or the sequence of colors: Black, Red, Green, Blue, Magenta, Cyan, Yellow, White.

file colorbars.h:

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>

class QPaintEvent ;

class MyWidget : public QWidget {
	public :
	MyWidget( ) ;

	protected :
	void paintEvent( QPaintEvent * ) ;
	private :
	int width ;
	int height ;
	const int colornumber ;
} ;
#endif

file colorbars.cpp:

#include <QtGui>
#include "colorbars.h"

MyWidget::MyWidget( ) :
width( 640 ) ,
height( 240 ) ,
colornumber( 8 ) {
	setGeometry( 0, 0 , width , height ) ;
}

void MyWidget::paintEvent ( QPaintEvent * ) {
	int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 , 
		0 , 0 , 255 , 255 , 0 , 255 , 0 , 255 , 255 , 255 , 255 , 0 ,
		255 , 255 , 255 } ; 
	QPainter myPaint( this ) ;
	int rectwidth = width / colornumber ; //width of one rectangle
	int xstart = 1 ; //x coordinate of the first rectangle
	int offset = -1  ; //to allow for ++offset to define the red value even in the first run of the loop below
	for ( int i = 0 ; i < colornumber ; i++ ) {
		QColor rectColor ;
		rectColor.setRed( rgbtriplets[ ++offset ] ) ;
		rectColor.setGreen( rgbtriplets[ ++offset ] ) ;
		rectColor.setBlue( rgbtriplets[ ++offset ] ) ;
		myPaint.fillRect( xstart , 0 , rectwidth , height - 1 , rectColor ) ;
		xstart += rectwidth + 1 ;
	}
}

file main.cpp:

#include <QApplication>
#include "colorbars.h"

int main( int argc, char * argv[ ] ) {
	QApplication app( argc , argv ) ;
	MyWidget window ;
	window.setWindowTitle( QApplication::translate( "colorslides" , "color slides demonstration" ) ) ;
	window.show( ) ;
	return app.exec( ) ;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.