如何在Qt中使用线程将文本添加到文本编辑器中

How in Qt to add text to a text editor using a thread

本文关键字:文本 添加 编辑器 文本编辑 Qt 线程      更新时间:2023-10-16

对于我在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
  ...
}