QT/C++ – Accessing MainWindow UI from a different class

First off it’s a bad idea to create MainGame before you create your QApplication object.
If you want to have your MainGame object globally available like this it should be a pointer:

MainWindow *Game;
int main (int argc, char **argv)
{
  QApplication a (argc, argv);

  Game = new MainWindow();
  Game->show();

  int result = a.exec();

  delete Game;
  Game = NULL;

  return result;
}

This approach is however not the most elegant. There are two much better choices.

  1. The QApplication object actually stores all top level windows like your MainGame which means you can allways aquire it through QApplication::topLevelWidgets() which is a static function and returns a list with all top level widgets. Since you only have one, the first one is your MainGame. The drawback is you’ll have to cast it, but using Qts qobject_cast<MainGame*>(...) is fairly safe. You’ll have to check the result though to make sure it isn’t a NULL pointer.

  2. Use the singelton design pattern. You should store the global Game pointer in the source (cpp) file of the Game class itself (subclass QMainWindow) and your Game class should implement a static public method which returns this global pointer. So if any other class needs the Game pointer, it simply calls:

    MyGame *theGame = MyGame::getInstance();
    

    for example.

Regarding your setEnabled() problem. Please post the relevant code. If it’s too much feel free to send me the *.ui file and the piece of code via mail.

Best regards
D

Leave a Comment