You shouldn't use your example directly in another thread. However, it isn't too difficult to work things into a good form using signals and slots.
class UpThread : public QThread
{
Q_OBJECT
...
public slots:
void countUp()
{
for ( int i = 0; i < 100; ++i )
{
emit ( newText( QString::number( i ) ) );
sleep( 1 );
}
}
signals:
void newText( QString text );
}
class DownThread : public QThread
{
Q_OBJECT
...
public slots:
void countDown()
{
for ( int i = 100; i > 0; --i )
{
emit ( newText( QString::number( i ) ) );
sleep( 1 );
}
}
signals:
void newText( QString text );
}
int main( int argc, char **argv )
{
QApplication app( argc, argv );
MainWindow window;
UpThread up;
DownThread down;
QObject::connect( window.buttonUp, SIGNAL( clicked() ), &up, SLOT( countUp() ) );
QObject::connect( &up, SIGNAL( newText( QString ) ), &window.textEntry, SLOT( setText( QString ) ) );
QObject::connect( window.buttonDown, SIGNAL( clicked() ), &down, SLOT( countDown() ) );
QObject::connect( &down, SIGNAL( newText( QString ) ), &window.textEntry, SLOT( setText( QString ) ) );
window.show();
up.run();
down.run();
return ( app.exec() );
}
Note: I haven't compiled or tested this. Up and down don't care if the other is running, so if you click both buttons, your text entry may jump all over the place. I obviously left out a lot of stuff. I also added a sleep( 1 )
to each loop to show that they shouldn't block the main UI.