My question is two parts:
mainWindow
spawned in a thread other than the one running main()?mainWindow
not immediately go out of scope when main() returns?In the below example a window is created, shown, and main returns almost immediately.
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindowExample.pro
#-------------------------------------------------
#
# Project created by QtCreator 2016-05-23T10:55:03
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = MainWindowExample
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
mainWindow
mainWindow
event loop is executed in scope of a.exec()
- it blocks until application exits (for example - last top-level window is closed).So mainWindow
does not go out of scope, because it is main
that executes everything.
Check it using code like:
std::cout << "starting application event loop" << std::endl;
const int ret = a.exec();
std::cout << "after exec" << std::endl; // or any other code here
return ret;
From QApplication doc:
Enters the main event loop and waits until exit() is called, then returns the value that was set to exit() (which is 0 if exit() is called via quit()).