简体   繁体   中英

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: 崩溃图片

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();
}

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.

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...

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.

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM