Joe Carr
Joe Carr

Reputation: 455

Qt must construct QApplication before a QWidget

Qt recently started crashing without having a reason for it. The most recent one which is currently grinding my nerves down to a pulp is crashing due to starting another form programmatically. The "must construct QApplication before a QWidget" apparently is a common issue with Qt 5.7.* versions and the solutions I have found so far in StackOverflow haven't helped me.

This is a screenshot of the error message I got after the application crashed: crash image

And here is the bit of the code that I remove which allows me to restart the application without any noticeable problems:

#include "operations.h"
Operations o;
void mainWindow::on_thisButton_clicked()
    {
        o.show();
        this->hide();
    }

----

The main.cpp as requested :)

#include "mainWindow.h"

#include <QApplication>

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

    w.show();

    return a.exec();
}

Upvotes: 1

Views: 3658

Answers (4)

Joe Carr
Joe Carr

Reputation: 455

Okay, I have managed to find a solution, however, it is borderline idiotic as it does not make any sense why it does not work in its prior state. Technically, all you need to do in order to have the error not appearing is to stick the declaration of the form class you are referring within the function itself(ie Operations o;).

Here is the code solution itself:

#include "operations.h"

void mainWindow::on_thisButton_clicked()
{
    Operations o;
    o.show();
    this->hide();
}

Bare in mind that this is not the end of all problems as I currently have the problem of the new form closing in the very same 1 second period it opens. If I manage to solve it I will update my solution.

Upvotes: 0

Alain
Alain

Reputation: 11

Don't create Operations object as a global variable, as it will be created as a static BEFORE running main(), therefore the error message is simply correct and relevant. This is a C++ issue, not a Qt one. All other suggestions work because you now create the object at the right time, after the QApplication...

Upvotes: 1

Uwe
Uwe

Reputation: 725

"must construct QApplication before a QWidget" is the standard type of error you get with Qt applications, when linking something incompatible ( like mixing debug/release ).

So in most use cases this indicates a build problem and has nothing to with the code itself.

Upvotes: 2

Benjamin T
Benjamin T

Reputation: 8311

Try this:

#include "operations.h"

void mainWindow::on_thisButton_clicked()
{
    Operations *o = new Operations();
    o->show();
    this->hide();
}

You might want to declare Operations *o as a member of mainWindow and initialize it the the constructor if you don't want to create a new one each time the button is clicked.

Upvotes: 3

Related Questions