Solved How to properly subclass QApplication and access new methods elsewhere?
-
Wouldn't QSettings be more suitable for that ?
-
if what I were doing were as straightforward as I described, perhaps :)
-
basically i was trying to take advantage of the fact that it is already a singleton in the application.. I suppose I could move all my "stuff" into another class and make it a singleton if this isn't an appropriate use of subclassing QApplication
-
I was referring to the scope of the method; because you mentioned calling
QApplication::SomeCustomMethod()
but that method does not exist in QApplication.You need an object unless it is a static function.
-
Well technically you can do it however from a cleanliness point view, it's rather an abuse.
-
You simply need to add this method:
static MyApplication* instance() { return static_cast<MyApplication*>(QApplication::instance()); }
then you can do:
MyApplication* myApp=MyApplication::instance(); myApp->SomeCustomMethod();
-
Ignoring whether this is a "good thing" to do or not... if the method is not static, you should be able to:
MyApplication * const myApp = qobject_cast<MyApplication *>(QCoreApplication::instance()); if (myApp != NULL) { myApp->SomeCustomMethod(); }
-
@Paul-Colby said in how to properly subclass QApplication and access new methods elsewhere?:
if the method is not static
In fact, you're correct either way, even more so. Otherwise:
QApplication app; MyApplication::instance()->someMethod();
get's pretty ugly pretty fast. ;)
-
ugly and obtuse indeed. I'm going to re-think this. thanks!
-
@pmh4514 said in how to properly subclass QApplication and access new methods elsewhere?:
ugly and obtuse indeed. I'm going to re-think this. thanks!
Well, it's the same with a singleton anyway. If you need a global state of your application
QApplication
is as good a place as any I suppose, I think you should rather rethink how to pass the data around without resorting to using a singleton. For example your settings object (which you might create inmain()
) can raise a few signals and if you need you can propagate those signals around to other objects (i.e. through signal forwarding). Ultimately, the interested parties could just subscribe to whatever they're interested in. -
Thanks, good insights.
I generally use the singleton in my case as it is modeling/controlling an external piece of hardware, of which there can only be one.
I've been doing C++ much longer than Qt.. Still wrapping my head around "The Qt Way" for lots of things!