PDA

View Full Version : To jump to a specific line in a textedit



aaditya190
20th November 2013, 10:51
Can anyone suggest me some code to jump to a specific line of a text edit widget. I have tried using blockNumber() function through QTextCursor but this returns only the current line where cursor is placed. I want to set the cursor to a specific line. Can someone help me in this?

patrik08
20th November 2013, 11:56
You can iterate QTextDocument rootframe and count line, and having cursor position from each block

RootDocFrame = doc->rootFrame();

sample code
bool RTF::Writer::write(QIODevice* device, QTextDocument* text)
on file https://manual-indexing.googlecode.com/svn/trunk/RTF_OASI_DOC/rtf/writer.cpp writing rtf format.. parse all line and element..

or from event or findBlockByLineNumber(line_number));



void C_MainWindow::goToLineAction() {

bool ok;
int line_number = QInputDialog::getInt(this, tr("Go to Line"),
tr("Enter a line number to go to: "), 1, 1, central_widget_TextDocument->blockCount(), 1, &ok);
if (ok) {
QTextCursor text_cursor(central_widget_TextDocument->findBlockByLineNumber(line_number));
text_cursor.select(QTextCursor::BlockUnderCursor);
central_widget_TextEdit->setTextCursor(text_cursor);
}

}

aaditya190
21st November 2013, 05:50
I tried this set of code but it gives an error that QTextEdit has an unknown member function findBlockByLineNumber. The element central_widget_TextDocument is a textedit only? .. And can you also tell me is C_MainWindow::goToLineAction() a pre-defined function or a user-defined function?

thomas@itest
21st November 2013, 10:16
Hi,

this is what i've done on a previous project from a QPlainTextEdit :


class MyTxtEdit : public QPlainTextEdit
{
Q_OBJECT
public:
explicit MyTxtEdit(QWidget *parent = 0);

int currentLine() const
{
return textCursor().blockNumber()+1;
}

public slots:
void setCurrentLine(int line)
{
QTextCursor cursor = textCursor();

int moves = line-currentLine();

if(moves)
{
if(moves<0) cursor.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor, -moves);
else cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, moves);

cursor.movePosition(QTextCursor::StartOfLine);

setTextCursor(cursor);
}
}
}

but the text contents were really simple (raw text, no images, ...), so, in your case, maybe the "currentLine()" method won't give you a correct value.

aaditya190
21st November 2013, 10:51
It worked.. Thank You very much...:)