PDA

View Full Version : access to ui in a threaded application



mastupristi
17th June 2010, 09:43
Hi,

I need to to manage serial port stream, and update my ui consequently.
Reading some post here in the forum I wrote the attached example 4792, where the thread zotthread simulates serial port management.

here is the screenshot
4793

the application is very simple.

that are slots in dialog:

void Dialog::ovvaivai(void)
{
zotThread *zt;

zt = new zotThread;

connect(zt, SIGNAL(lancettasecondi(const QString&)), this, SLOT(cambiatestobottone(const QString&)));
connect(zt, SIGNAL(uscita()), this, SLOT(chiusura()));
zt->start();
}

void Dialog::cambiatestobottone(const QString &s)
{
ui->pushButton->setText(s);
}

void Dialog::chiusura(void)
{
close();
}


and this is the thread taht simulates serial management

void zotThread::run(void)
{
int i;
QString s;
QTimer qt;
for(i=5;i>0;i--)
{
s.setNum(i);
emit lancettasecondi(s);
qt.setSingleShot(true);
qt.start(1000);
while(qt.isActive()) QCoreApplication::processEvents();
}
emit uscita();
}


when clicking the pushbutton ovvaivai(void) is called, so then thread starts. It perform a 5 seconds countdown before close the application.

I wonder if this is the right way to change the ui from a thread.
An also I wonder if is correct to call QCoreApplication::processEvents(); from inside trhead main loop. Without that call timer dosn't walk.

Now I want to read the spin value from thread. How can I perform that action? I don't think through signal/slot.

thanks

Lesiok
17th June 2010, 10:15
Better and more elegant will be something like this :

class zotThread : public QThread
{
.
.
private slots :
void oneStep( void );
private :
int count_down;
}

void zotThread::run(void)
{
count_down = 5;
QTimer::singleShot(0,this, SLOT(oneStep()));
QThread::run();//event loop is starting
}

void zotThread::singleStep(void)
(
if( count_down < 0 )
{
quit();//event loop is stopped
return;
}
QString s;
s.setNum(count_down--);
emit lancettasecondi(s);
QTimer::singleShot(1000,this, SLOT(oneStep()));
}

Lesiok
17th June 2010, 10:18
Now I want to read the spin value from thread. How can I perform that action? I don't think through signal/slot.
Why not ? Just connect signal QSpinBox::valueChanged ( int i ) (http://doc.trolltech.com/4.6/qspinbox.html#valueChanged) to slot in Yours thread and all.

wysota
17th June 2010, 10:31
I wonder if this is the right way to change the ui from a thread.
You can't access ui from a thread.


An also I wonder if is correct to call QCoreApplication::processEvents(); from inside trhead main loop.
It's not.

Without that call timer dosn't walk.
Use QThread::exec().