gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:51:37 30 4
gpt4 key购买 nike

对于我在 Qt 中进行的项目,我需要同时进行多项操作。其中一个事件是获取温度读数并将该读数连同时间戳一起显示在文本编辑框中。在我编写的 while 循环完成之前,不会显示温度和时间戳。我知道 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--;
}

noheatmode.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));
...
}

如果你想执行任意代码,它归结为“如何在给定线程中执行仿函数”,线程是主线程。 this question的答案提供多种实现方式。

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
...
}

关于c++ - 如何在 Qt 中使用线程将文本添加到文本编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31170883/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com