首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用QTextCursor选择最近添加的文本

如何使用QTextCursor选择最近添加的文本
EN

Stack Overflow用户
提问于 2016-09-28 15:23:53
回答 2查看 746关注 0票数 2

我使用下面的函数在QPlainTextWidget中的选定文本中增加缩进(三个空格):

代码语言:javascript
复制
QTextCursor cursor = ui->ceEditor->textCursor();
QString text = cursor.selectedText();
QString tab = "   ";
QChar sep = QChar(0x2029);
QStringList lines = text.split(sep,QString::KeepEmptyParts);
for (qint32 i = 0; i < lines.size(); i++){
    lines[i] = tab + lines.at(i);
}
text = lines.join(sep);
cursor.removeSelectedText();
cursor.insertText(text);

效果很好。但是我想做的是(在这个函数之后)选择刚才添加的文本。这样,如果我愿意的话,我可以增加两到三倍的缩进。我该怎么做?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-29 00:04:30

我将通过在调用anchor()之前从cursor中保存cursorinsertText()来实现这一点,这样我们就可以在插入文本后使用这些旧值和游标的position() (因为这保证在插入文本的末尾)来计算新的选择。

此外,不需要像在removeSelectedText()中已经做的那样调用insertText(),下面是代码的外观:

代码语言:javascript
复制
QTextCursor cursor = ui->ceEditor->textCursor();
QString text = cursor.selectedText();
QString tab = "   ";
QChar sep = QChar(0x2029);
QStringList lines = text.split(sep,QString::KeepEmptyParts);
for (qint32 i = 0; i < lines.size(); i++){
    lines[i] = tab + lines.at(i);
}
text = lines.join(sep);
textEdit.setFocus();
//save anchor and position before inserting text
int oldAnchor= cursor.anchor();
int oldPosition= cursor.position();
cursor.insertText(text);
//select text between new cursor position and old selection start
int newPosition, newAnchor;
if(oldAnchor< oldPosition){
    newAnchor= oldAnchor;
    newPosition= cursor.position();
} else {
    newAnchor= cursor.position();
    newPosition= oldPosition;
}
cursor.setPosition(newAnchor, QTextCursor::MoveAnchor);
cursor.setPosition(newPosition, QTextCursor::KeepAnchor);
ui->ceEditor->setTextCursor(cursor);

请注意,您可以从光标的新position()开始选择文本,然后返回到text.length()中,避免保存旧的anchor()position()值。但是这样,你就不能保持选择的方向。无论选择是从左到右还是从右到左)

票数 2
EN

Stack Overflow用户

发布于 2016-09-28 23:50:27

尝试在函数的末尾添加以下代码

代码语言:javascript
复制
for(int i = 0; i<text.length(); i++)
    ui->ceEditor->moveCursor(QTextCursor::MoveOperation::Left,QTextCursor::MoveMode::KeepAnchor);        
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39751663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档