PDA

View Full Version : Auto-scrolling QTextBrowser



MTK358
19th January 2012, 15:09
It it possible to make a subclass of QTextBrowser that automatically scrolls to the bottom whenever it was scrolled to the bottom when text was added?

Also, is it possible to make it stay scrolled to the same place in the text when resized?

Spitfire
20th January 2012, 14:15
1 - This QTextBrowser does it by default when text is appended. When text is inserted it doesn't but it requires very little work:

MyBrowser::MyBrowser( QWidget* parent ) :
QTextBrowser( parent ),
atBottom( false )
{
connect( this, SIGNAL( textChanged() ), this, SLOT( scrollToBottom() ) );
connect( this->verticalScrollBar(), SIGNAL( valueChanged( int ) ), this, SLOT( scrolledTo( int ) ) );
}

void MyBrowser::scrollToBottom( void )
{
if( this->atBottom )
{
this->verticalScrollBar()->setValue( this->verticalScrollBar()->maximum() );
}
}

void MyBrowser::scrolledTo( int val )
{
this->atBottom = val == this->verticalScrollBar()->maximum();
}

2 - I don't quite get your question. The browser doesn't scroll anywhere when you resize it, just show more/less text.

MTK358
21st January 2012, 01:37
1 - This QTextBrowser does it by default when text is appended. When text is inserted it doesn't but it requires very little work:

MyBrowser::MyBrowser( QWidget* parent ) :
QTextBrowser( parent ),
atBottom( false )
{
connect( this, SIGNAL( textChanged() ), this, SLOT( scrollToBottom() ) );
connect( this->verticalScrollBar(), SIGNAL( valueChanged( int ) ), this, SLOT( scrolledTo( int ) ) );
}

void MyBrowser::scrollToBottom( void )
{
if( this->atBottom )
{
this->verticalScrollBar()->setValue( this->verticalScrollBar()->maximum() );
}
}

void MyBrowser::scrolledTo( int val )
{
this->atBottom = val == this->verticalScrollBar()->maximum();
}

First of all, I'm inserting text using a QTextCursor, not the QTextBrowser's append method. Second, it should only auto-scroll if it was already at the bottom before text was inserted.


2 - I don't quite get your question. The browser doesn't scroll anywhere when you resize it, just show more/less text.

When I make it smaller horizontally, it scrolls up, and when I make it bigger horizontally, it scrolls down.

MTK358
22nd January 2012, 13:26
I misread your code, it actually does only autoscroll when at the bottom.

Spitfire
24th January 2012, 09:43
I understand that first of your problems is now solved.

As to the second one.
The browsers scrolls up/down when you resize it horizontally because of text wrapping feature.
I think that unless you turn it off you won't be able to keep the text in place and turning it off doesn't make much sense.