3

Well, I'm doing a Goto Line System. But it seems it doesn't work. It did before but I think I broke it.

void ScriptWindow::gotoLine()
{
    int line = QInputDialog::getInteger(myEdit, "Line Number","To what line do you want to go?", 1, 1, myEdit->document()->lineCount());
    QTextCursor cursor = myEdit->textCursor();
    myEdit->setTextCursor(cursor);
    cursor.setPosition(QTextCursor::Start, QTextCursor::MoveAnchor);
    while(cursor.position() == QTextCursor::Start) {
        cursor.setPosition(line - 1, QTextCursor::MoveAnchor);
    }    
}

Could you please tell me what am I doing wrong?

Kazuma
  • 1,371
  • 6
  • 19
  • 33

1 Answers1

5

Set the cursor position to zero, move down by number of lines, and set myEdit's text cursor.

QTextCursor cursor = myEdit->textCursor();
cursor.setPosition(0);
cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, line-1);
myEdit->setTextCursor(cursor);

Alternatively, find the position via the QTextDocument and then just set the position.

int pos = myEdit->document()->findBlockByLineNumber(line-1).position();
QTextCursor cursor = myEdit->textCursor();
cursor.setPosition(pos);
myEdit->setTextCursor(cursor);
baysmith
  • 5,082
  • 1
  • 23
  • 18
  • When i go to line 5 it just goes to line 2. o_O – Kazuma Feb 26 '11 at 19:18
  • My first solution just fixed the error where the setTextCursor() call must be after the cursor is modified. The cursor position was also not being set properly. I've updated my answer with a more complete solution. – baysmith Mar 02 '11 at 17:59