// // Qt Sample Application: connect.cpp // // Draws lines that connect points. // #include <qwidget.h> #include <qpainter.h> #include <qapp.h> #include <stdlib.h> const int MAXPOINTS = 2000; // maximum number of points const int MAXCOLORS = 400; // // ConnectWidget - draws connected lines // class ConnectWidget : public QWidget { public: ConnectWidget( QWidget *parent=0, const char *name=0 ); ~ConnectWidget(); protected: void paintEvent( QPaintEvent * ); void mousePressEvent( QMouseEvent *); void mouseReleaseEvent( QMouseEvent *); void mouseMoveEvent( QMouseEvent *); private: QPoint *points; // point array QColor *colors; // color array int count; // count = number of points bool down; // TRUE if mouse down }; // // Initialize ConnectWidget. // ConnectWidget::ConnectWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { setBackgroundColor( white ); // white background count = 0; down = FALSE; points = new QPoint[MAXPOINTS]; colors = new QColor[MAXCOLORS]; for ( int i=0; i<MAXCOLORS; i++ ) // init color array colors[i] = QColor( rand()&255, rand()&255, rand()&255 ); } ConnectWidget::~ConnectWidget() { delete[] points; // cleanup delete[] colors; } // // Paint/refresh widget // void ConnectWidget::paintEvent( QPaintEvent * ) { QPainter paint; paint.begin( this ); // start painting for ( int i=0; i<count-1; i++ ) { // connect all points for ( int j=i+1; j<count; j++ ) { paint.setPen( colors[rand()%MAXCOLORS] ); // set random pen color paint.drawLine( points[i], points[j] ); // draw line } } paint.end(); // painting done } // // mousePressEvent receives all mouse presses // void ConnectWidget::mousePressEvent( QMouseEvent * ) { down = TRUE; count = 0; // start recording points erase(); // erase widget contents } // // mouseReleaseEvent receives all mouse releases // void ConnectWidget::mouseReleaseEvent( QMouseEvent * ) { down = FALSE; // done recording points update(); // draw the lines } // // mouseMoveEvent receives all mouse move/drag events // void ConnectWidget::mouseMoveEvent( QMouseEvent *e ) { if ( down && count < MAXPOINTS ) { QPainter paint; paint.begin( this ); points[count++] = e->pos(); // add point paint.drawPoint( e->pos() ); // plot point paint.end(); } } // // Create and display a ConnectWidget // int main( int argc, char **argv ) { QApplication a( argc, argv ); ConnectWidget connect; connect.show(); return a.exec( &connect ); }