Qt:如何将文本编辑光标移动到特定的列和行

Qt: how to move textEdit cursor to specific col and row

我可以通过 QTextCursor::blockNumber()[= 获取行和列的当前位置15=]QTextCursor::positionInBlock()。我的问题是如何将光标移动到行和列的特定位置。喜欢

setPosition(x,y) // The current cursor would move to row x and col y.

可以吗?

简单的解决方法:

只需将光标移动到那里:

textEdit.moveCursor(QTextCursor::Start); //set to start
for( <... y-times ...> )
{
    textEdit.moveCursor(QTextCursor::Down); //move down
}
for( < ... x-times ...>) 
{
    textEdit.moveCursor(QTextCursor::Right); //move right
}
如果您需要 "select" 文本来更改它,

moveCursor 也是一种转到方式。没有循环的类似方法也在最后。

更多解释和更好的解决方案:

理论上,文本没有 GUI 中显示的 "lines",而是 endline-character\n\r\n,具体取决于操作系统和框架) 只是另一个字符。所以对于游标来说,几乎所有的东西都只是一个 "text" 没有行。

有包装函数可以处理这个问题,但我稍后再讲。首先,您不能通过 QTextEdit 界面直接访问它们,但您必须直接操作光标。

QTextCursor curs = textEdit.textCursor(); //copies current cursor
//... cursor operations
textEdit.setTextCursor(curs);

现在 "operations":

如果您知道要在字符串中的哪个位置,您在此处有 setPosition()。这个 "position" 不是针对垂直线,而是针对整个文本。

多行字符串在内部看起来是这样的:

"Hello, World!\nAnotherLine"

这会显示

Hello, World!
AnotherLine

setPosition() 想要内部字符串的位置。

要移动到另一行,您必须通过查找文本中的第一个 \n 来计算位置并添加 x 偏移量。如果您想要第 3 行,请查找前 2 \n

幸运的是还有函数 setVerticalMovement 似乎包装了这个,也许这就是你想要做的。它垂直移动光标。

所以你可以这样做:

curs.setPosition(x); //beginning at first line
curs.setVerticalMovement(y); //move down to the line you want.

之后用光标调用 setTextCursor,如上所示。

注:

顺序很重要。 setPosition 设置在全文中的位置。所以 setPosition(5) 虽然可能在第 3 行 而不是 将它设置为你所在行中的第 5 个字符,但在整个文本中。所以先移动 x 坐标再移动 y。


不过您需要注意线条的长度。

some longer line
short
another longer line

如果您现在指定第 2 行和第 7 列,它将是 "out-of-bounds"。我不确定 verticalMovement 在这里的表现如何。我假设光标将位于行尾。


当您直接使用 QTextCursor class 时,您也可以使用没有循环的移动操作,因为它们有一个额外的参数来重复操作。

curs.movePosition(QTextCursor::Start);
curs.movePosition(QTextCursor::Down,<modeMode>,y); //go down y-times
curs.movePosition(QTextCursor::Right,<moveMode>,x); //go right x-times

我认为最好的方法是通过 QTextCursor

例如,如果您的 QTextEdit 被称为 textEdit:

QTextCursor textCursor = ui->textEdit->textCursor();

textCursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, x);
textCursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, y);

ui->textEdit->setTextCursor(textCursor);

其中 xy 是所需的位置。

如果文档布局使用每行 1 个块(例如它是 QPlainTextEdit 或文档包含格式非常基本的文本),那么您可以直接设置位置:

void setCursorLineAndColumn (QTextCursor &cursor, int line, int col, 
                             QTextCursor::MoveMode mode) 
{
    QTextBlock b = cursor.document()->findBlockByLineNumber(line);
    cursor.setPosition(b.position() + col, mode);
    // you could make it a one-liner if you really want to, i guess.
}

与向下 + 向右方法相比的主要优点是 select 两个位置之间的文本要简单得多:

QTextCursor cursor = textEdit->textCursor();
setCursorLineAndColumn(cursor, startLine, startCol, QTextCursor::MoveAnchor);
setCursorLineAndColumn(cursor, endLine, endCol, QTextCursor::KeepAnchor);
textEdit->setTextCursor(cursor);

如果相关的话,还有性能优势。