2

I'm using Qt 5.3 and a QPlainTextEdit based widget. I append/insert text all time time on it. I want to lock the scrolling if I manually scroll the contents, so the screen keep on the same place (the contents continuing being appended/inserted). I append/insert text on the component by positioning the cursor and using insertText/appendText:

this->cursor.insertText(text, this->format);

Any ideas?

Morix Dev
  • 2,700
  • 1
  • 28
  • 49
Yore
  • 384
  • 1
  • 4
  • 18

2 Answers2

2

My solution of this problem.

ui->plainTextEdit->insertPlainText("A");//this doesn't have auto scroll
if(global)//global is bool variable, if it is true, we autoscroll to the bottom
    ui->plainTextEdit->verticalScrollBar()->setValue(ui->plainTextEdit->verticalScrollBar()->maximum());//we auto scroll it everytime

Or

QTextCursor cursor(ui->plainTextEdit->textCursor());
cursor.insertText("A");
if(global)
    ui->plainTextEdit->verticalScrollBar()->setValue(ui->plainTextEdit->verticalScrollBar()->maximum());

Now we do next: when user hover(enter event) plainTextEdit we stop auto-scrolling, when user leave widget, we enable auto scrolling again. I did this by eventFilter, but I hope that you understanf my idea.

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(obj==ui->plainTextEdit && (event->type()==QEvent::Enter || event->type()==QEvent::Leave))
    {

        if(event->type()==QEvent::Enter)//user move mouse on widget:stop auto-scrolling
            global =false;
        else
            global =true;// leave event:enable auto-scrolling
        ui->label->setText(event->type()==QEvent::Enter ? "Hovering" : "Not Hovering");//just show it to user, you can delete this line
    }

return QObject::eventFilter(obj, event);
} 
Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • I understand you idea, but I don't use > ui->plainTextEdit->insertPlainText("A"); to append the text. Instead, I use to position the cursor and insert the text. This is auto scrolling to the bottom. Is there any way to prevent the scrolling ??? I tried to reimplement resizeEvent but without success. – Yore Sep 09 '14 at 18:25
  • @user3071624 Instead of `insertPlainText` I try my method with `QTextCursor cursor(ui->plainTextEdit->textCursor());` `cursor.insertText("A");` (if I understood you correctly, you use this, I add code which I use to the answer) Result was the same. – Jablonski Sep 09 '14 at 18:29
  • Oh ! I see it now. But still, when I add the text the scroll still occurs when the text extends the area displayed. Maybe I am using another method which is causing the scrolling then. Your code for the eventFilter is very nice. Thanks. – Yore Sep 09 '14 at 18:39
0

Try this one. I think this is what you want to implement.

QScrollBar *bar = plainTextEdit->verticalScrollBar();
bar->setValue(bar->maximum());
liveforFun
  • 16
  • 2