Search code examples
c++qtuser-interfaceqwidget

Creating a window in Qt outside of main()?


Is it possible to make a window in Qt outside of the main() function like it's done in the tutorials? What's wrong with they way I did it here? There are no errors when I try to compile, but the window just never shows up. Thanks.

main.cpp

#include <QtGui>
#include "Calculator.h"

int main(int argc, char *argv[]) {
    QApplication application(argc, argv);
    Calculator calculator();
    return application.exec();
}

Calculator.h

class Calculator {
    public:
        Calculator();
};

Calculator.cpp

#include <QtGui>
#include "Calculator.h"

Calculator::Calculator() {

    QWidget window;
    window.show();

}

Solution

  • Curiously, you have two separate errors here :)

    1. window is a local variable in the constructor that goes out of scope (and thus is destroyed) once the constructor exits. You must use a persistent object (one that lives after the function exits), such as a member of Calculator.
    2. In main, the code Calculator calculator(); declares a function calculator returning Calculator. This is a common gotcha when instantiating default-constructed objects in C++. The parentheses are unnecessary (and harmful) in this case.

    To fix both errors:

    class Calculator {
    public:
        Calculator();
    private:
        QWidget m_window;            // persistent member
    };
    Calculator::Calculator() {
        m_window.show();
    }
    
    
    int main(int argc, char *argv[]) {
        QApplication application(argc, argv);
        Calculator calculator;       // note, no () after calculator
        return application.exec();
    }