Visning af rotwidget.cpp

#include <kdebug.h>
#include <kdialogbase.h>
#include <kpixmapeffect.h>

#include <qlabel.h>
#include <qpainter.h>
#include <qwidget.h>

#include "rotwidget.h"
#include "rotwidget.moc"

RotWidget::RotWidget( QWidget *parent, const QColor& c1, const QColor& c2, int sp )
    :QWidget(parent), m_color1(c1), m_color2(c2), m_step(0), m_speed(sp)
{
  if( (m_speed <= 0) || (m_speed > 20) )
    m_speed = 1;
  setFixedHeight( 6 );

  for( int i = 0; i <= width(); i++ )
    preparePixmap( i );

  m_stepTimer = new QTimer( this );
  connect(m_stepTimer, SIGNAL(timeout()), this, SLOT(stepEvent()));
  m_stepTimer->start( 50 );
}

RotWidget::~RotWidget()
{
}

void RotWidget::stepEvent()
{
  // This is inefficient as we create too many pixmaps, optimize later.
  m_step += m_speed;
  if( m_step > width() )
    m_step = 0;
  repaint( true );
}

// Todo: Optimize drawing.
void RotWidget::paintEvent( QPaintEvent *pe )
{
  QPainter p;
  p.begin( this );

  QRect r = pe->rect();

  if( m_stepPixmap.at( m_step ) )
    bitBlt( this, r.x(), r.y(), m_stepPixmap.at( m_step ), r.x(), r.y(), r.width(), r.height() );
  else
    p.fillRect( rect(), Qt::black );
  p.end();
}

void RotWidget::resizeEvent( QResizeEvent *re )
{
  m_stepPixmap.clear();
  for( int i = 0; i <= re->size().width(); i++ )
    preparePixmap( i );
}

void RotWidget::preparePixmap( int step )
{
  if( step < 0 )
    return;

  // Explicitly draw our first pixmap. The rest we will bitBlt() from here.
  if( step == 0 )
  {
    KPixmap tmp; tmp.resize( size().width() / 2, size().height() );
    KPixmap tmp2(tmp);
    KPixmapEffect::gradient( tmp, m_color1, m_color2, KPixmapEffect::HorizontalGradient );
    KPixmapEffect::gradient( tmp2, m_color2, m_color1, KPixmapEffect::HorizontalGradient );
    KPixmap *px = new KPixmap( size() );
    QPainter p;
    p.begin( px );
    p.drawPixmap( 0, 0, tmp );
    p.drawPixmap( size().width()/2, 0, tmp2 );
    p.end();
    m_stepPixmap.append( px );
  }
  else if( m_stepPixmap.at( step-1 ) )
  {
    QPixmap *prev = m_stepPixmap.at( step-1 );
    QPixmap next; next.resize( size() );
    // convert
    // prev = "[------------]"
    // to
    // next = "------------]["
    bitBlt( &next, 0, 0, prev, 1, 0, prev->width()-1, prev->height() );
    bitBlt( &next, width()-1, 0, prev, 0, 0, 1, prev->height() );
    KPixmap *n = new KPixmap( next );
    m_stepPixmap.append( n );
  }
}