如何在Qt中使用线程将文本添加到文本编辑器中
How in Qt to add text to a text editor using a thread
对于我在Qt中工作的项目,我需要同时完成几件事。其中一个事件是获取温度读数,并将该读数与时间戳一起显示在文本编辑框中。直到我写的while循环结束,temp和时间戳才会显示。我知道while循环阻塞了它,所以我试图写一个线程来显示时间和临时,但不知道如何从线程写入gui。
这是我开始线程和while循环的地方
QThread cThread;
timeTempObject cObject;
cObject.DoSetup(cThread);
cObject.moveToThread(&cThread);
cThread.start();
while(flowTime > 0)
{
// set zero pin to be high while flowtime is more than 0
digitalWrite(0,1);
displayCurrentTime();
// set second pin LED to flash according to dutyCycle
digitalWrite(2,1);
delay(onTime);
// displayCurrentTime();
ui->tempTimeNoHeatMode->append(temp);
digitalWrite(2,0);
delay(offTime);
flowTime--;
}
无加热模式.h
namespace Ui {
class noheatmode;
}
class noheatmode : public QWidget
{
Q_OBJECT
public:
explicit noheatmode(QWidget *parent = 0);
~noheatmode();
private slots:
void on_startButtonNoHeatMode_clicked();
void on_noHeatModeBack_clicked();
public slots:
void displayCurrentTime();
private:
Ui::noheatmode *ui;
};
#endif // NOHEATMODE_H
线程的timetempobject.h
class timeTempObject : public QObject
{
Q_OBJECT
public:
explicit timeTempObject(QObject *parent = 0);
void DoSetup(QThread &cThread);
public slots:
void DoWork();
};
#endif // TIMETEMPOBJECT_H
timetempobject.cpp
timeTempObject::timeTempObject(QObject *parent) :
QObject(parent)
{
}
void timeTempObject::DoSetup(QThread &cThread)
{
connect(&cThread,SIGNAL(started()),this,SLOT(DoWork()));
}
void timeTempObject::DoWork()
{
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(displayCurrentTime()));
// delay set to space out time readings, can be adjusted
timer->start(1500);
// Gets the time
QTime time = QTime::currentTime();
// Converts to string with chosen format
QString sTime = time.toString("hh:mm:ss:ms");
// displays current time in text edit box
Ui::noheatmode* noheatmode::ui->tempTimeNoHeatMode->append(sTime);
}
如何更改线程,使其能够写入到gui中的文本编辑器?
由于QTextEdit::append
是一个插槽,因此很容易从其他线程调用它:
void tempTimeObject::DoWork() {
...
QMetaObject::invokeMethod(ui->tempTimeNoHeatMode, "append",
Qt::QueuedConnection, Q_ARG(QString, temp));
...
}
如果你想执行任意代码,它可以归结为"如何在给定的线程中执行函子",线程是主线程。这个问题的答案提供了多种方法
Qt 5上最简单的方法是:
void tempTimeObject::DoWork() {
...
{
QObject signalSource;
QObject::connect(&signalSource, &QObject::destroyed, qApp, [=](QObject *){
ui->tempTimeNoHeatMode->append(text);
... // other GUI manipulations
});
} // here signalSource emits the signal and posts the functor to the GUI thread
...
}
相关文章:
- 从文本文件在组合框中添加项目
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- 如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?
- 如何从 c++ winrt UWP 应用中的代码将文本添加到富文本块
- c++ 添加具有写入文件错误的文本变量
- 在 MFC 组合框中设置文本,而不将其添加到列表中
- 将时间戳添加到文本文件中的空行中
- 将文本添加到鼠标位置时,请单击“给出分割故障”
- 如何在C++的文本变量中添加变量值
- 如何使用键盘输入和sf ::文本在SFML中添加一种文本框以显示文本字符串
- 将文本注释添加到exe文件mingw
- 使用FreeImage向图像添加文本
- 将文本添加到另一个程序文本框 C++
- 问答游戏/单击按钮将文本添加到标签
- 如何将文本添加到QTextEdit的顶部
- 从数据库检索后,将其他文本添加到组合框中
- 如何在Qt中使用线程将文本添加到文本编辑器中
- 使用QPushButton将文本添加到QTextEdit
- 为什么将文本添加到 RichEdit 窗口会冻结它
- C++将字符串文本添加到字符文本