Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does creating a new Qt Window with no parent also create a new thread?

Tags:

c++

qt

qthread

My question is two parts:

  1. Is mainWindow spawned in a thread other than the one running main()?
  2. How does 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
like image 898
Daniel Arnett Avatar asked Oct 28 '25 04:10

Daniel Arnett


1 Answers

  1. No new thread is created for mainWindow
  2. The 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()).

like image 103
Hcorg Avatar answered Oct 29 '25 19:10

Hcorg