Selecting a piece of text using QTextCursor

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 03:01:35

问题


Having problems with selecting pieces of text using the Qt framework. For example if i have this document : "No time for rest". And i want to select "ime for r" and delete this piece of text from the document, how should i do it using QTextCursor? Here is my code:

QTextCursor *cursor = new QTextCursor(ui->plainTextEdit->document());
cursor->setPosition(StartPos,QTextCursor::MoveAnchor);
cursor->setPosition(EndPos,QTextCursor::KeepAnchor);
cursor->select(QTextCursor::LineUnderCursor);
cursor->clearSelection();

Unfortunately it deletes the whole line from the text. I've tried using other selection types like WordUnderCursor or BlockUnderCursor, but no result. Or maybe there is a better way to do it? Thanks in advance.


回答1:


There are several issues in your code:

  1. cursor->select(QTextCursor::LineUnderCursor); line selects whole current line. You don't want to delete whole line, so why would you write this? Remove this line of code.
  2. clearSelection() just deselects everything. Use removeSelectedText() instead.
  3. Don't create QTextCursor using new. It's correct but not needed. You should avoid pointers when possible. QTextCursor is usually passed by value or reference. Also you can use QPlainTextEdit::textCursor to get a copy of the edit cursor.

So, the code should look like that:

QTextCursor cursor = ui->plainTextEdit->textCursor();
cursor.setPosition(StartPos, QTextCursor::MoveAnchor);
cursor.setPosition(EndPos, QTextCursor::KeepAnchor);
cursor.removeSelectedText();



回答2:


You are clearing the selection as opposed to the characters based on your desire.

Please read the documentation of the method:

void QTextCursor::clearSelection()

Clears the current selection by setting the anchor to the cursor position.

Note that it does not delete the text of the selection.

You can see that it only deleted the selection, not the text. Please use the following method instead:

void QTextCursor::removeSelectedText()

If there is a selection, its content is deleted; otherwise does nothing.

Having discussed the theory, let us demonstrate what you could write:

QTextCursor *cursor = new QTextCursor(ui->plainTextEdit->document());
cursor->setPosition(StartPos,QTextCursor::MoveAnchor);
cursor->setPosition(EndPos,QTextCursor::KeepAnchor);
// If any, this should be block selection
cursor->select(QTextCursor::BlockUnderCursor);
cursor->removeSelectedText();
        ^^^^^^^^^^^^^^^^^^


来源:https://stackoverflow.com/questions/21122928/selecting-a-piece-of-text-using-qtextcursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!