views:

35

answers:

2

I'm working on a multi-threaded Qt application and would like to connect a signal in a thread with slot in another thread. My problem is that I only have the string used to set the QObject:objectName in the signaling thread that is defined in a project wide constants file.

My overall goal is to avoid having to pass pointers to objects that are several layers deep inside of other objects. I've done this in the past and while it works, it adds much unneeded complexity to code. And it is a very un-elegant solution to the problem.

What I would like to do is to do a global search through all of the QObjects in my application to find the one that matches the name. In reading the Qt documentation, there is considerable discussion about how to search for child objects of the current one or you can search using parent classes. But with objects in different threads, this doesn't appear to work. In particular, as the object doing the connection does not have a direct access to the QThread that owns the object doing the signaling.

Any suggestions?

+1  A: 

you could write your own name=>object map. Qt's container classes are thread-safe.

Javier
In reviewing Qt's documentation, I see that they are all reentrant, however, I have not seen the documentation say that the containers are thread-safe. Just last week, I was working with QQueue in a multi-threaded app and missed one mutex. It took a while to figure out why I sometimes had junk data coming out of the QQueue. So based on my experience, I would not agree that Qt container's are thread-safe.
photo_tom
A: 

Trees of objects must all belong to the same thread. The detailed description of QObject states:

Use the moveToThread() function to change the thread affinity for an object and its children (the object cannot be moved if it has a parent).

I have seen an interesting solution to the problem of finding objects implemented in Qt Creator: its plugin manager has a global object registry where you can add and remove objects and later query them by type. It would be easy to extend it and allow querying by name too. Just remember names need not be unique.

andref
Very interesting link. Thanks!
photo_tom