Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only the visible text from a QTextEdit widget

Tags:

c++

qt

qtextedit

I have been searching for a day and not found an answer to this. This thread How do I get the currently visible text from a QTextEdit or QPlainTextEdit widget? merely answers how to get ALL the text contained in the widget.

In my situation, I have a QTextWidget with a lot of text. Much more than can be displayed at any one time. I would like to respond to the visible text changing and then take some actions.

When a user scrolls the text area or new text is added to the widget, I would like to take some action on the visible text. I can easily connect to a signal from the QTextEdit::verticalScrollBar() but how to find what the visible text is?

I have this so far but after reading pages and pages of documentation it seems like QTextEdit doesn't have any method to let you know what the text in it's visible area is.

 void MyProject::on_textEdit_scrollBar_valueChanged(int value)
 {
    QStringList visibleText = // how do I do this?
 }
like image 944
Raj Avatar asked Mar 21 '23 17:03

Raj


1 Answers

You can use QTextEdit::cursorForPosition:

QTextEdit textEdit;
//...
QTextCursor cursor = textEdit.cursorForPosition(QPoint(0, 0));
QPoint bottom_right(textEdit.viewport()->width() - 1, textEdit.viewport()->height() - 1);
int end_pos = textEdit.cursorForPosition(bottom_right).position();
cursor.setPosition(end_pos, QTextCursor::KeepAnchor);
qDebug() << cursor.selectedText();
like image 133
Pavel Strakhov Avatar answered Apr 26 '23 14:04

Pavel Strakhov