简体   繁体   中英

“Must construct a QApplication before a QWidget”

I'm trying to make a simple Qt program.I have successfully build and run the program several times.These errors occurred when I added a getter method to pass a string from my MainWindow to a dialog's QFileDialog::getSaveFileName() But when I comment below lines the programs runs successfully.
MainWindow.h

class MainWindow : public QMainWindow
{
    Q_OBJECT
    public:
    QString fileName();
};

MainWindow.cpp

QString MainWindow::fileName() {
    return "F:/Users/Admin/Desktop/" + dnldName;
}

Usage of fileName()

void Dialog::on_browseButton_clicked()
{
    QFileDialog folder;
    folder.setFileMode(QFileDialog::Directory);
    folder.setOption(QFileDialog::ShowDirsOnly);
    dirPath = folder.getSaveFileName(this, tr("Save File"), mWinObj.fileName(), tr("All Files"));
    ui->savePathEdit->setText(dirPath);
}

The program builds successfully but gives the following errors when I try to run it.

Starting F:\Users\Admin\Desktop\Imp Docs\C++ apps\build-GUINetworkApp-Desktop_Qt_5_2_0_MinGW_32bit-Debug\debug\GUINetworkApp.exe...
QWidget: Must construct a QApplication before a QWidget
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
F:\Users\Admin\Desktop\Imp Docs\C++ apps\build-GUINetworkApp-Desktop_Qt_5_2_0_MinGW_32bit-Debug\debug\GUINetworkApp.exe exited with code 3   

main.cpp

#include "mainwindow.h"
#include <QApplication>

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

    return a.exec();
}

What's wrong with the code and how can I fix it?

You cannot create widgets as global objects since those objects will be created before the application object in the main function. Then your error will happen.

Create your widget within the main function after the QApplication object construction, or just keep a global pointer to your widget if you want global access (but which is not a good programming style).

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