PDA

View Full Version : Alpha mask on QScrollArea



JonnyJP
10th February 2012, 14:16
Hi,
I've got a vertical QScrollArea which I add custom widgets to which sits on a semi transparent QFrame and the user can scroll this up and down. If there are lots of widgets in the scroll area they obviously don't get rendered outside the scroll area's region but this causes a 'hard' cut-off and I'd like the widgets to fade in as the use scrolls up and down.

Is there any way to do this using an alpha mask? I've tried using stylesheets but that just paints the background of the QScrollArea and not the widgets themselves.

Any ideas?

I suppose this is similar to the end credits of a film where instead of the credits disappearing off the top of the screen they fade out with ever decreasing opacity.

Spitfire
14th February 2012, 10:41
I don't know about alpha mask, but it can be easily done using simple widget with reimplemented paintEvent.

Something like that:

// gradient widget
MyGradient::MyGradient( QWidget* parent )
:
QWidget( parent )
{
parent->installEventFilter( this );
this->setAttribute( Qt::WA_TransparentForMouseEvents, true ); // important
}

bool MyGradient::eventFilter( QObject* o, QEvent* e )
{
if( o == this->parentWidget() && e->type() == QEvent::Resize )
{
this->setGeometry( this->parentWidget()->rect() );
}

return false;
}

void MyGradient::paintEvent( QPaintEvent* e )
{
int fade_out_length = 100;
QColor startColor( 0, 0, 0, 0 );
QColor endColor( 0, 0, 0, 255 );
QRect r = this->rect();

QLinearGradient gradient_top( r.width()/2, fade_out_length, r.width()/2, 0 );
gradient_top.setColorAt( 0.0, startColor );
gradient_top.setColorAt( 1.0, endColor );

QLinearGradient gradient_bottom( r.width()/2, r.height() - fade_out_length, r.width()/2, r.bottom() );
gradient_bottom.setColorAt( 0.0, startColor );
gradient_bottom.setColorAt( 1.0, endColor );

QPainter p( this );
p.setBrush( gradient_top );
p.drawRect( this->rect() );

p.setBrush( gradient_bottom );
p.drawRect( this->rect() );
}

// how to use it
MainWindow::MainWindow( QWidget* parent )
: QMainWindow( parent )
{
QLabel* label = new QLabel();
label->setPixmap( QPixmap( "C:\\Users\\rob\\Documents\\startrek.jpg" ) );

QScrollArea* scrollArea = new QScrollArea();
scrollArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
scrollArea->setWidget( label );

new MyGradient( scrollArea->viewport() ); // the interesting part

this->setCentralWidget( scrollArea );
}
I hope this helps.

JonnyJP
16th February 2012, 16:12
Thanks.

I'll try it out and see how I get on...