QTextCursor的一些用法

来源:互联网 发布:java冒泡排序法 编辑:程序博客网 时间:2024/05/01 06:47
  1.  if (!currentTextCursor.hasSelection()) {
  2.             currentTextCursor.insertText("**" + tr("Boldface") + "**");
  3.             currentTextCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 2);
  4.             currentTextCursor.movePosition(QTextCursor::WordLeft, QTextCursor::KeepAnchor, 1);
  5.             currentTextEdit->setTextCursor(currentTextCursor);
  6.         } else {
  7.             currentTextCursor.insertText("**" + currentTextCursor.selectedText() + "**");
  8.         }

问题:

如果光标没有选中文字,就插入文本**Boldface**,并且选中其中的Boldface,如果已经选中有文字,则在文字的左右两边分别加上**,问题是这样的
在第一次选中的文字文字之后,当我在QTextEdit中单击后,理论上是选中的文字被清空,也就是hasSelection()应该返回false,但实际上hasSelection()还是true,并且我用qDebug()测试了之后,确实还是刚才选中的文字,难道还需要对单击事件做处理吗,不知道表述的清不清楚,请各位不吝指教,谢谢


问题已经解决,原因是没有更新QTextCursor,也就是说在每次使用QTextCursor时,需要将现在QTextEdit的光标再传递给QTextCursor,我以前是把QTextCursor当作一个类内全局变量用了,以为自己会更新的,所以会出现上述问题,也就说,每次使用QTextCursor,需要如下动作:

  1. QTextCursor currentTextCursor = currentTextEdit->textCursor();

问题:

想用QTextEdit做一个程序执行状态的显示窗口。
设置了readOnly属性。结果有两个问题:
1.在程序执行过程中去翻看前面的信息,如果不把光标(虽然光标看不见)定位到最后一行,就会从翻看的位置打印信息。有没有把光标定位到最后的API?

解决:

QTextCursor cursor = this->textCursor();
if(!cursor.atEnd())
{
cursor.movePosition(QTextCursor::End,QTextCursor::MoveAnchor,1);
this->setTextCursor(cursor);
}
cursor.insertText(str);

原创粉丝点击