Frage

I'm learning Qt from a youtube channel. In one of tutorials it was explained how to create empty qt projects, the tutorial intended to write this code:

#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QLabel *label = new QLabel("hello World!");

    label->show();

    return app.exec();
}

I was getting a "no such file or directory exists" in both #includes so I searched the Qt include directory for those files and modifies the include statements to:

#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>

Now, I get 51 errors about "unresolved external symbol" and "File not found: main.obj". If I change char *argv[] to char *argv, I get an error in the line:

QApplication app(argc, argv);

stating

cannot convert parameter 2 from 'char *' to 'char **'

I do not know what is the problem as the code in tutorial works fine (though he used Qt 2.1).

War es hilfreich?

Lösung

The code below works fine for me. Do not forget the QT += widgets entry in your qmake project file for Qt 5 if you happen to use qmake.

The widget classes were moved into their separate widgets module in Qt 5. They were living in the gui module in Qt 4, and the core and gui modules are added by default to the QT variable.

Alternatively, I am providing the raw compilation command as well.

main.cpp

#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QLabel *label = new QLabel("hello World!");

    label->show();

    return app.exec();
}

Build

g++ -Wall -fPIC -lQt5Widgets -lQt5Core -I/usr/include/qt -I/usr/include/qt/QtWidgets -I/usr/include/qt/QtCore main.cpp

Use this in your qmake project file:

main.pro

TEMPLATE = app
TARGET = test
greaterThan(QT_MAJOR_VERSION, 4):QT += widgets
SOURCES += main.cpp

Do not forget to rerun qmake if you use QtCreator. Unfortunately, there is a long-standing (more than four years old at the time of writing this) issue reported against QtCreator that it does not always know when to rerun qmake when needed. See the details here:

Creator should know when to rerun qmake

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top