c++qtcmakeqt4

Cmake link issue: undefined reference to QPushButton


I just started using Qt. I have a problem with compiling the first example.
main.cpp:

#include <QCoreApplication>
#include <QPushButton>

int main(int argc, char** argv)
{
  QCoreApplication app(argc, argv);
  QPushButton button ("Hello world !");

 return app.exec();
}

CMake.txt:

 cmake_minimum_required(VERSION 2.6)
 project(new)
 find_package(Qt4 REQUIRED)
 enable_testing()
 include_directories(${QT_INCLUDES} ${CMAKE_CURRENT_BINARY_DIR})
 set(source_SRCS main.cpp)
 qt4_automoc(${source_SRCS})
 add_executable(new ${source_SRCS})
 target_link_libraries(new${QT_QTCORE_LIBRARY})
 add_subdirectory(tests)
 install(TARGETS new RUNTIME DESTINATION .)

The error I get upon building is:

undefined reference to `QPushButton::QPushButton(QString const&,QWidget*)'

It is a linking problem, but how can I solve it?


Solution

  • You have three problems:

    1. You're not linking with the Gui module (Widgets module in Qt 5). This is covered in the other answer.

    2. You you must use QApplication in widgets-based applications. Since QPushButton comes from the Gui module (Widgets in Qt5), you can't merely use QCoreApplication nor QGuiApplication: your program will crash as soon as you attempt to instantiate a QWidget.

    3. You're not showing the button, so when your program starts you'll see nothing once you fix the above.

    Your main.cpp should look like:

    #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    #include <QtGui>
    #else
    #include <QtWidgets>
    #endif
    
    int main(int argc, char** argv)
    {
      QApplication app(argc, argv);
      QPushButton button ("Hello world !");
      button.show();
      return app.exec();
    }