PDA

View Full Version : QThread/QObject and QTimer



swiety
24th January 2008, 22:03
I'm using QTimer in QThread( or QObject ) class :


class InfoThread: public QThreed
{
Q_OBJECT
...
void run();
signals:
void newInfoAvalible( /* some data */ );
private slots:
void update();
..
private:
QTimer *p_timer;
};

InfoThread::Infothread( QObject *parent ) : QThread( parent )
{
p_timer = new QTimer( this );
connect( p_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
}

void InfoThread::run()
{
p_timer->start( 1000 );
exec(); // event loop for QTimer
}

void InfoThread::update()
{
...
emit newInfoAvalible( /* some data */ );
}


For me code is good, but signal newInfoAvalible( /* some data */ ) causes apps to crash. Wher's the problem?

seveninches
25th January 2008, 03:16
Is newInfoAvalible() connected to a slot in another QThread?
If so, does the /*some data*/ contain pointers to something which are invalid after you leave this function? If so, this is expected, as signals between threads use "queued connections".

jpn
25th January 2008, 08:37
The QTimer object must be created in InfoThread::run() without a parent (preferably on the stack since QThread::exec() blocks) and the connection must be forced as direct

connect( &timer, SIGNAL( timeout() ), this, SLOT( update() ), Qt::DirectConnection );
because QThread itself lives in different thread than what's being executed in QThread::run().