[SOLVED]How do I use a global varaible in qt
-
Hi and welcome
Global vars are not the best design. It would be better to
give the list as parameter to the other windows.
Like
mywindow.setlist( thelist );
so each would have its own pointer to the list versus just having a global one.
Anyway, to create a global list:
create a mylist.h file and a mylist.cpp to contain your list.
In the .h file
extern list mylist;
and in the cpp file
mylist list;
then include mylist.h in the other windows.
and it will know mylist; -
Depending on what the list contains using a global for this might range from moderately bad idea to a horrible bug.
Remember that you can't make global QObjects, as they should be born and die during the lifespan of QApplication object. So if the list contains QObjects it's a no-no.
Design-wise there should be no state that belongs to no one, which is the case for global variables. The data should always belong to some object that will be responsible for cleaning it up when its time is due, otherwise you've got a curious case of questionable responsibility.So my advice is to make it a member of the class that feels best for this and expose it to others via an access method. Passing it to all the classes via parameter like @mrjj suggested is also an option (a good one in some cases), although from my experience the responsibility for the data tends to blur this way the deeper into class structure it gets passed. Qt has a nice tree-like dependency structure provided by its parent-child relations. If you can't find a suitable object to host the data in that tree, tie it to the root - the application object, but don't make it hang around rootless - it usually causes a bug or a maintenance headache down the line.
-
well, if you post your code we can try to help.
Also the errors if possible.If you are new to c++ , maybe try some simple stuff before trying with Qt ?
-
@TLoZ_KZP You can take a look at the singleton design pattern if you want a more OO approach to having a global variable.
The singleton is a highly debated pattern but sometimes it is the correct solution, in most situations it is better than global variables.
Although the best and recommended approach is as @mrjj pointed out: Pass the list to the objects that needs it through a function.