Frage

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?
 }
War es hilfreich?

Lösung

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();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top