Searching for a QObject
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 th开发者_运维知识库e 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?
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.
you could write your own name=>object map. Qt's container classes are thread-safe.
精彩评论