The example program on this page may be used, distributed and modified
without limitation.
C0664 510077 qtdoc-1.2-a4-2.ps
Show Picture
This example loads a picture file and displays it in a window.
//
// Qt Example Program: showpic
//
// This program demonstrates how to load and display a picture.
//
// We create a simple widget that displays (plays) the picture
// whenever the widget needs to be repainted.
//
#include <qwidget.h>
#include <qpicture.h>
#include <qpainter.h>
#include <qapp.h>
#include <ctype.h>
class PictureDisplay : public QWidget // picture display widget
{
public:
PictureDisplay( const char *fileName );
~PictureDisplay();
protected:
void paintEvent( QPaintEvent * );
void keyPressEvent( QKeyEvent * );
private:
QPicture *pict;
QString name;
};
PictureDisplay::PictureDisplay( const char *fileName )
{
pict = new QPicture;
name = fileName;
if ( !pict->load(fileName) ) { // cannot load picture
delete pict;
pict = 0;
name.sprintf( "Not able to load picture: %s", fileName );
}
}
PictureDisplay::~PictureDisplay()
{
delete pict;
}
void PictureDisplay::paintEvent( QPaintEvent * )
{
QPainter paint;
paint.begin( this ); // paint widget
if ( pict )
paint.drawPicture( *pict ); // draw picture
else
paint.drawText( rect(), AlignCenter, name );
paint.end();
}
void PictureDisplay::keyPressEvent( QKeyEvent *k )
{
switch ( tolower(k->ascii()) ) {
case 'r': // reload
pict->load( name );
update();
break;
case 'q': // quit
QApplication::exit();
break;
}
}
int main( int argc, char **argv )
{
QApplication a( argc, argv ); // QApplication required!
char *fileName = "car.pic"; // default picture file name
if ( argc == 2 ) // use argument as file name
fileName = argv[1];
PictureDisplay test( fileName ); // create picture display
a.setMainWidget( &test); // set main widget
test.show(); // show it
return a.exec(); // start event loop
}
Generated at 17:29, 1997/04/07 for Qt version 1.2 by the webmaster at Troll Tech