Reputation: 1536
I am having a weird problem with my Qt app. I have a QMainWindow
, conveniently MainWindow
.
The following code works from the main()
function:
int main(int argc, char *argv[])
{
..
MainWindow mainWindow;
mainWindow.show();
..
}
But, with the following does not show the MainWindow at all:
int main(int argc, char *argv[])
{
AnotherClass::staticFunction();
}
class AnotherClass: public QObject {
Q_OBJECT
public:
static void staticFunction();
}
void AnotherClass::staticFunction() {
MainWindow mainWindow;
mainWindow.show();
return ;
}
Upvotes: 1
Views: 499
Reputation: 1706
In this code
void AnotherClass::staticFunction() {
MainWindow mainWindow;
mainWindow.show();
return ;
}
The instance mainWindow
will go out of scope after the closing }
, and then destroyed. You will have to allocate it on the heap using new
to have it outlive staticFunction()
.
void AnotherClass::staticFunction() {
MainWindow * mainWindow = new MainWindow;
mainWindow->show();
return ;
}
You will also need to somehow keep track of the pointer and having it delete
d later (perhaps using a smart pointer).
And of course you will have to have a QApplication
and call exec()
on it in order to start the main event loop.
Upvotes: 1
Reputation: 1536
Oh my bad! Its because main never returns and enters the exec loop. However, since my function was returning immediately, the window was getting destroyed. Changing MainWindow mainWindow;
to MainWindow* mainWindow = new MainWindow();
solved my problem:
Upvotes: 2