0

If you have a simple QMainWindow or even app with single QWidget, you can connect any button to close() slot on it and it will close the program. You can even do this in designer without any coding:

image description

But this will cease to work once you have more complex structure where MainMenu is a child of another widget. Under that circumstances, the close slot only hides MainMenu (so you just see black screen) but the application keeps running. I was wondering if there's non-hacky way to terminate the program regardless of the widget hierarchy.

Calling abort or similar methods are considered hacky. There's allways some cleanup that must occur.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

2 Answers2

1

Simply connect your QPushButton::clicked() signal to the QCoreApplication::quit() slot. This will close the application for good when button is clicked.

Note: QCoreApplication can be accessed via qApp global object.

connect( myButton, SIGNAL(clicked()), qApp, SLOT(quit()) );

You mentioned in the OP:

you can connect any button to close() slot on it and it will close the program

Note that this is not necessarily true. It's only true if QGuiApplication::quitOnLastWindowClosed() is true (which is the default, I must admit).

jpo38
  • 20,821
  • 10
  • 70
  • 151
0

Roughly:

  • Use Qt parent\children model
  • call the static methodQCoreApplication::exit when you need to stop the application. It calls QEventLoop::exit on the main (GUI) thread. It triggers the destruction of top level objects as well as their children
  • Optionally, If you start work threads, do it using the movetoThread design . Then the owner of the QThread object just need to do the following:

    QThread workthread;
    workthread.exit(code);
    workthread.wait(time_ms);
    if(workthread.isRunning())
    {
       workthread.terminate();
    }
    

In general you don't want to use terminate.

Community
  • 1
  • 1
UmNyobe
  • 22,539
  • 9
  • 61
  • 90
  • I don't understand the thread part. I'm not starting any threads manually - maybe I don't need that part? The `QEventLoop::exit` is static? If not, how do I access it from my ui class? I will probably need to call it from the click event handler. – Tomáš Zato Dec 17 '15 at 15:52
  • you dont need that part if you are not starting threads. edited – UmNyobe Dec 17 '15 at 16:00