“实时"更新 Qt TextView

2022-01-23 00:00:00 qt4 qt c++ mono

我有一个带有嵌入式脚本/jit 的 Qt 应用程序.现在我想在 QTextEdit(更具体的 QPlainTextEdit)上接收脚本的输出.为此,正在发出回调.我面临的问题是,无论我尝试向 TextEdit 输出什么,要么延迟到脚本完成,要么在 2-3 秒后卡住(然后延迟到脚本完成).我尝试使用信号和插槽进行更新,但也尝试使用直接函数调用 - 均未奏效.还重新绘制/更新 TextEdit 和父表单以及甚至 QCoreApplication::flush() 确实显示很少/没有效果.好像我在做一些根本错误的事情.任何想法或示例如何实现实时"更新?

I have a Qt application with an embedded script/jit. Now I'd like to receive the output from the script on an QTextEdit (more specific QPlainTextEdit). For this purpose callbacks are being issued. The problem I'm facing is that whatever I try the output to the TextEdit is either delayed until the script has finished or gets stuck after 2-3 seconds (and is delayed then until the script has finished). I tried to use signals and slots for the update but also direct function calls - neither worked. Also repainting / updating the TextEdit and the parent form as well as even QCoreApplication::flush() did show little/no effect. Seems like I'm doing something fundamentally wrong. Any ideas or examples how to achive the "real time" updates?

顺便说一句,更新例程正在被调用 - 调试输出到标准输出是实时可用的.

Btw, the update routines are being called - debug output to stdout is avaiable in real time.

推荐答案

只是使用线程来绘制一个解决方案,我已经多次使用它来进行日志记录,并且可以按需要工作:

Just to sketch a soluting using threads, which I have used numerous times for logging purposes and which works as desired:

定义你的线程类:

class MyThread : public QThread
{
  Q_OBJECT
public:
  MyThread(QObject *parent=0) : QThread(parent) {}
signals:
  void signalLogMessage(const QString &logMessage);

...
};

只要你想在主线程中显示日志消息,只需使用

Whenever you want a log message to be shown in the main thread, just use

发出 signalLogMessage("Foo!");

在你的主线程中:

MyThread *thread = new MyThread(this);
connect(thread, SIGNAL(signalLogMessage(const QString&)), 
        this, SLOT(logMessageFromThread(const QString&)));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
...
thread->start();

logMessageFromThread 的作用类似于 myPlainTextEdit->appendPlainText(message).这工作没有任何延迟或其他问题.

where logMessageFromThread does something like myPlainTextEdit->appendPlainText(message). This works without any delay or other problems.

希望对你有帮助.

相关文章