How to find a line number after an Enter key press in QTextEdit.



  • Say I have some lines in QTextEdit.

    Line number 1
    Line number 2
    Line number 3

    Now I press an Enter key after Line number 2 and it looks like this now

    Line number 1
    Line number 2
    '\r'
    Line number 3

    Now I wont to get a line before the Enter key - Line number 2

    So I can do like this

    switch (keyEvent->key())
     {
          case Qt::Key_Return:
            {
                 if (term_str.isEmpty())
                  {
                            QTextDocument *doc = ui->textEditTerminalTx->document();
                            QTextBlock tb = doc->findBlockByLineNumber(???);
                            QString s = tb.text();
                  }
         }
         break;
    }
    

    But how do I get a line number to put in doc->findBlockByLineNumber(???) ?



  • To retrieve the block under the cursor, you can do:

    QTextDocument *doc = ui->textEditTerminalTx->document();
    //QTextCursor cursor=doc->textCursor();
    QTextCursor cursor=ui->textEditTerminalTx->textCursor();
    QTextBlock tb = cursor.block();
    


  • @mpergand said in How to find a line number after ann Enter key in QTextEdit.:

    To retrieve the block under the cursor, you can do:

    QTextDocument *doc = ui->textEditTerminalTx->document();
    QTextCursor cursor=doc->textCursor();
    QTextBlock tb = cursor.block();
    

    I need the line above the cursor - only one line above.



  • int QTextCursor::blockNumber() const
    Returns the number of the block the cursor is in, or 0 if the cursor is invalid.



  • @mpergand
    QTextCursor cursor=doc->textCursor();
    I get - error: no member named 'textCursor' in 'QTextDocument'



  • Sorry, it is:
    ui->textEditTerminalTx->textCursor();



  • QTextCursor cursor(ui->textEditTerminalTx->document());
    const int oldPosition = cursor.position();
    cursor.movePosition(QTextCursor::Up);
    QString s = cursor.block().text();
    cursor.setPosition(oldPosition); //restore the cursor
    


  • @mpergand
    Thank you. This way it works good.

    QTextCursor cursor= ui->textEditTerminalTx->textCursor();
    QTextBlock tb = cursor.block();
    QString line = tb.text();
    

    Always get the last line above the cursor. Exactly what I need.


Log in to reply