erfan zangeneh
erfan zangeneh

Reputation: 354

Cannot create a QWidget without QApplication

When i compile my qt project showed below error?

QWidget: Cannot create a QWidget without QApplication

What is the problem?

Main.cpp

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

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    MainWindow w;
    w.show();
    return app.exec();
}

Upvotes: 12

Views: 30704

Answers (2)

Ho1
Ho1

Reputation: 1289

You need a QApplication to have a QWidget. Change QGuiApplication to QApplication and the code will run just fine.

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

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow w;
    w.show();
    return app.exec();
}

If you want to know "Why there are three main classes like QApplication, QGuiApplication and QCoreApplication", see this. It says:

QCoreApplication is the base class, QGuiApplication extends the base class with functionality related to handling windows and GUI stuff (non-widget related, e.g. OpenGL or QtQuick), QApplication extends QGuiApplication with functionality related to handling widgets.

Btw, isn't it the basic example available on Qt Creator? You need a book to learn Qt, and I suggest you to read "C++ GUI Programming with Qt 4 (2nd Edition)" from Jasmin Blanchette.

Qt Book

Upvotes: 25

A. Sarid
A. Sarid

Reputation: 3996

You should change QGuiApplication to QApplication in your main.

From QGuiApplication Class Description:

For QWidget based Qt applications, use QApplication instead, as it provides some functionality needed for creating QWidget instances.

Upvotes: 6

Related Questions