adi
adi

Reputation: 590

Sending objects as signal arguments between threads in Qt

I am new to Qt and trying to learn the Qt threading mechanism. I am in a situation where I would like a background thread to perform some long running task and report the results to another (or main) thread after processing every 100 items. Right now I am doing this by emitting a signal from the background thread containing a list of the processed objects that is received in a slot in the main thread. Does Qt make a copy of the signal argument when it is received in the slot ? If so, how does how does calling qRegisterMetaType help with that ? This is what I am tying to accomplish in my code :

//background thread
void run(){
   //get a query object from database
   int fireCount = 0;
   QList< QList<QVariant> > data;
   while(query->next()){
        fireCount++;
        QList<QVariant> row;
        //do some calculations on the fields read from the query
        processRow(query,&row);
        data.append(row);
        if(fireCount>100){
            emit publishDataToMainThread(data);
            fireCount = 0;
            data.clear();
        }
   }

}

//slot in main thread
void receiveData(QList< QList<Qvariant> > data){
\\display the data
}

Also , is this a recommended practice for transferring objects between threads ?

Upvotes: 1

Views: 2099

Answers (1)

ar31
ar31

Reputation: 3816

This is a perfectly fine way of doing it. QList uses implicit sharing (i.e. copy on write) so copying it means copying one pointer and increasing the reference count. It only gets copied once you try to modify it. Just remember to use Qt::QueuedConnection when connection the signal to the slot so that the slots gets run in the receivers thread.

qRegisterMetaType or Q_DECLARE_METATYPE are needed so that you can pass parameters by value in signals. It tells the Qt Metatype system (which is sort of like reflection) that this type exists.

Upvotes: 1

Related Questions