Search code examples
c++qtqplaintextedit

Qt 5.3 QPlainTextEdit implement scroll lock


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?


Solution

  • 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);
    }