Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Qt, how to?

I'm using Qt and in the main method I need to declare an object that I need to use in all my other files. How can I access that object in the other files? (I need to make it global..)

I'm use to iPhone development and there we have the appDelegate that you can use all over the application to reach objects you've declared in applicationDidFinishLaunching method. How can I do the same in Qt?

like image 301
Martin Avatar asked Sep 24 '09 13:09

Martin


People also ask

How do you declare a global variable in Qt?

But if you really need it do: // In some header file extern int globalVar; // in some cpp file int globalVar = 0; Then include that header file where you need access to the global variable. Hi you can use extern variable declare in some .

How do you set a global variable?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Can you create your own global variables?

Last Updated October 11, 2022. You can create a global variable in a JavaScript script to store information that can be reused across Applications. The new global variable is stored on the server and is available to all Applications. To create a global variable, use the setVar function.


2 Answers

global_objects.hpp

extern int myGlobalInt;

global_objects.cpp

#include "global_objects.hpp"

namespace
{
    int myGlobalInt;
}

And then #include "global_objects.hpp" in every place you need myGlobalInt.

You should read C++ singleton vs. global static object and Initializing qt resources embedded in static library as well.

like image 193
Piotr Dobrogost Avatar answered Sep 20 '22 21:09

Piotr Dobrogost


In Qt there is the singleton QApplication, with its static method QApplication::instance() which gives you the one and only QApplication object back. It has many other static member functions (in an earlier age they were called "globals"), for the mainwindow, the active window etc.

http://doc.trolltech.com/4.5/qapplication.html

You can sublass it if you want to add your own statics.

like image 23
Gunther Piez Avatar answered Sep 20 '22 21:09

Gunther Piez