I have an application that opens a QDialog for some flow, and when it is closed, the QMainWindow is opened.
In the QDialog I create some objects that I’d like to pass as a pointer (or some other way) to the QMainWindow. For example I create a SysTray object that needs to change its state from the QMainWindow. What is the best way? Singletons?
update .
after implementing the sulotion another question was rises , does the QDialog is cleaned from memory that means , invoked its destructor ? i don’t think its the case . i have to do some object cleaning , and there destructor never invoked
One approach is to allocate on the heap with the
QMainWindowas a parent. The QObject-hierarchy will take care of freeing the memory and you will access the object for the lifetime of theQMainWindow.If at any point you know for sure that you don’t need the
QDialogor the shared object anymore, you can call deleteLater.Example:
Where you use your QDialog:
A better (and likely more memory-friendly) approach is to use a shared pointer implementation. Qt has a variety of smart pointer classes, one of which is
QSharedPointer. It is basically a thread-safe, reference-counted pointer which means that if you grab one that points to the shared object of yourQDialog, it will not get freed as long as there are any otherQSharedPointers pointing to it. Keep in mind that this might cause circular references if you are not careful.Example:
Where you use your QDialog:
From this point on, even if d goes out of scope (i.e. destroyed), you will still have a valid pointer to the shared data (well, of course unless you do something explicitly to invalidate it).