c++ - How in Qt to add text to a text editor using a thread -
for project working on in qt need make several things happen @ same time. 1 of these events take temperature reading , display reading in text edit box along time stamp. temp , time stamp not display until while loop wrote finishes. know while loop blocking trying write thread display time , temp, can not figure out how write gui thread.
here start thread , while loop
qthread cthread; timetempobject cobject; cobject.dosetup(cthread); cobject.movetothread(&cthread); cthread.start(); while(flowtime > 0) { // set 0 pin high while flowtime more 0 digitalwrite(0,1); displaycurrenttime(); // set second pin led flash according 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 thread
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 space out time readings, can adjusted timer->start(1500); // gets time qtime time = qtime::currenttime(); // converts string chosen format qstring stime = time.tostring("hh:mm:ss:ms"); // displays current time in text edit box ui::noheatmode* noheatmode::ui->temptimenoheatmode->append(stime); }
how alter thread can write text editor in gui?
since qtextedit::append
slot, it's easy call other threads:
void temptimeobject::dowork() { ... qmetaobject::invokemethod(ui->temptimenoheatmode, "append", qt::queuedconnection, q_arg(qstring, temp)); ... }
if wished execute arbitrary code, boils down "how execute functor in given thread", thread being main thread. answers this question provide multiple ways of doing it.
the simplest way on qt 5 be:
void temptimeobject::dowork() { ... { qobject signalsource; qobject::connect(&signalsource, &qobject::destroyed, qapp, [=](qobject *){ ui->temptimenoheatmode->append(text); ... // other gui manipulations }); } // here signalsource emits signal , posts functor gui thread ... }
Comments
Post a Comment