QPlainTextEdit按行截断历史记录

moo*_*eep 9 logging qt qplaintextedit log-rotation

我有一个GUI应用程序,其主要部分是QPlainTextEdit.它用于显示应用程序的日志,因此关联的文本无线逐行增长.

由于应用程序要运行很长时间,我需要限制将为此日志分配的内存.因此,我希望有一些maxNumLinesmaxNumCharacters参数可以确保在到达时将截断历史记录,即在添加新行时(即日志旋转)将删除头行.

为实现这一目标,我发现了这些功能

// get the associated text
QString toPlainText () const

// set the associated text
void setPlainText ( const QString & text )
Run Code Online (Sandbox Code Playgroud)

因此,像这个未经测试的代码可能会做的伎俩:

QString &tmp = pte.toPlainText();
while (tmp.size() > maxNumCharacters) {
  // remove lines from the head of the string until the desired size is reached
  // removes nothing if "\n" could not be found
  tmp.remove(0, tmp.indexOf("\n")+1);
}
pte.setPlainText( tmp );
Run Code Online (Sandbox Code Playgroud)

这是从第一行中删除第一行的方法QPlainTextEdit吗?是否有其他Qt Text GUI元素可以更好地适应这个任务(设置最大行数并在列表的头部截断),例如以某种方式显示QStringList我可以存储行(st我可以轻松地erase(0))?

或者QPlainTextEdit最终是否最终实现了相关QString大小的上限?

moo*_*eep 13

显然,该物业maximumBlockCount正是我所需要的:

如果要限制a中段落的总数QPlainTextEdit,例如在日志查看器中有用,则可以使用该maximumBlockCount属性.的组合setMaximumBlockCount()appendPlainText()QPlainTextEdit成一个高效的查看器记录文本.

以供参考:


cma*_*t85 8

几个月前我遇到了完全相同的问题,最后我用了一个QListView.虽然使用模型/视图/委托架构更加繁琐,但从长远来看,它的扩展性要好得多.例如,一旦基本体系结构到位,添加仅显示错误或警告条目的过滤器变得微不足道,或者创建委托以便将错误条目的背景涂成红色也很简单.