Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create a QWidget without QApplication

Tags:

c++

qt

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();
}
like image 580
erfan zangeneh Avatar asked Apr 30 '16 06:04

erfan zangeneh


2 Answers

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

like image 164
Ho1 Avatar answered Oct 17 '22 08:10

Ho1


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.

like image 30
A. Sarid Avatar answered Oct 17 '22 07:10

A. Sarid