Qt:如何移动textit光标到特定的冷和行

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

本文关键字:光标 textit 何移动 移动 Qt      更新时间:2023-10-16

我可以通过QTextCursor::blockNumber()QTextCursor::positionInBlock()获得行和col的当前位置。我的问题是,如何移动光标到特定的位置与行和col.如

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
}
如果你需要"选择"文本来改变它,

moveCursor也是goto-way。没有循环的类似方法也在最后。

更多的解释,也许更好的解决方案:

理论上,文本没有像gui那样的"行",但endline-character ( nrn取决于操作系统和框架)只是另一个字符。所以对于一个光标来说,几乎所有的东西都只是一个没有行的"文本"。

有包装器函数来处理这个问题,但我稍后再讨论它们。首先,你不能通过QTextEdit接口直接访问它们,但是你必须直接操作光标。

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

现在对于"操作":

如果你知道在字符串的哪个位置你有setPosition()在这里。这个"位置"不是关于竖线的,而是关于整个文本的。

这是多行字符串内部的样子:

"Hello, World!nAnotherLine"

显示

Hello, World!
AnotherLine

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

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

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

你可以这样写:

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

然后像上面那样用光标调用setTextCursor

注意:

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


你需要注意行的长度。

some longer line
short
another longer line

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


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

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.
}

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

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