简体   繁体   中英

How can I globally access a QT dialog from any class

I have a QT dialog which I need to have access to from anywhere in the program. Basically what I need to do is something like creating a static instance of it somewhere in my program, something like:

'''Note''': This is just an example of what I am trying to do, not actual code (which is too long to post here)

class Core
{
  public:
    static DialogType *MyDialog;
};

DialogType *Core::MyDialog = NULL;

// later in main.cpp

int main(int argc, char *argv[])
{
    try
    {
        Core::Init();
        QApplication a(argc, argv);
        Core::MyDialog = new DialogType();
        ...

However, despite this would work for any other type, it just doesn't work for classes that are inherited from QDialog. The compiler just return: DialogType does not name a type (and yes I do #include that .h file with declaration of DialogType)

What am I doing wrong? Why QT doesn't allow that? How could I make it possible to access single instance of my dialog from ANY class anywhere in the program?

If you genuinely do need just one single, always available instance of that specific class then you could build it off the Singleton pattern so it either creates a pointer and returns it, or just returns a pointer if it's created. Singletons are often recommended as there's plenty of faults with them, but for something along these lines it's probably easier than setting up a static reference to a QDialog inherited class.

If you are getting an error that the compiler doesn't know what type you are using then you must either insert a forward declaration, or #include a header file that contains either a forward declaration or a definition.

A forward declaration is sufficient if your member type is a pointer or a reference but if it is any other ADT, an #include becomes required.

In the code you posted, you could have:

Core.h:

class DialogType; // forward declaration.

class Core
{
  public:
    static DialogType *MyDialog;
};

In your source file, you could then have:

Core.cpp:

#include "Core.h"
#include "DialogType.h"

DialogType *Core::MyDialog = new DialogType();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM