1

I am completely new to QT and I want to prepare one window and take some input from the user then with this input run one console and show output in the console. I have tried to write code after exec but it seems it is not possible:

int main(int argc, char *argv[])
{
    int retmain = 0;
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    cout<<"pos500"<<endl;
    retmain = a.exec();
    cout<<"pos50"<<endl;
//doing something

    return retmain;
}

I don't know why but after a.exec(); nothing happens. So I searched on the internet and found below topic in stackoverflow: How to call function after window is shown?

But I want to end the graphic window and then do my process.

OleDahle
  • 305
  • 2
  • 8
SpongeBob
  • 383
  • 3
  • 16
  • Qt advises against running any code after [`QApplication::exec()`](https://doc.qt.io/qt-5/qapplication.html#exec) since it may not always return. It seems like `QDialog` is not what you want instead of `QMainWindow` and call exec on that. You could also override the [close event](https://doc.qt.io/qt-5/qwidget.html#closeEvent) of your main window and launch your calculations from there. – perivesta May 10 '19 at 09:44
  • If a.exec() does not show your `MainWindow w` (as you say nothing happens). then I don't think console output is not your problem! – hyde May 10 '19 at 12:19
  • What happens if you replace `MainWindow` with `QWidget`, does the window appear then? Does it print your output after you close that window? – hyde May 10 '19 at 12:20

1 Answers1

1

You need to call QCoreApplication::exit() to make exec return control to you.

After this function has been called, the application leaves the main event loop and returns from the call to exec(). The exec() function returns returnCode. If the event loop is not running, this function does nothing.

A simple example would be:

//mainwindow.h
//////////////////////////////////////////////////
#pragma once
#include <QtWidgets/QMainWindow>
#include <QtCore/QCoreApplication>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    void closeEvent(QCloseEvent *event);
    ~MainWindow();
};

//mainwindow.cpp
//////////////////////////////////////////////////
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    QCoreApplication::exit(0);
    QMainWindow::closeEvent(event);
}
MainWindow::~MainWindow(){}

//main.cpp
//////////////////////////////////////////////////
#include "mainwindow.h"
#include <QApplication>

#include <iostream>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    a.exec();
    std::cout << "test" << std::endl;
    return 0;
}
PeterT
  • 7,981
  • 1
  • 26
  • 34