Cmake link 问题:对 QPushButton 的未定义引用

Cmake link issue: undefined reference to QPushButton

我刚开始使用 Qt。我在编译第一个示例时遇到问题。
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 .)

我在构建时遇到的错误是:

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

这是链接问题,请问如何解决?

您还需要 link 针对 QtGui 和 QtWidgets 库。在 qmake 中,它处理构成 Qt 的众多库中的哪些,您必须在 cmake 中手动执行此操作。

如果您查看 QPushButton (http://doc.qt.io/qt-5/qpushbutton.html) 的文档,"qmake" 行会显示您需要的库。

考虑在 Qt 中使用 qmake 而不是 cmake。

无论如何,QCoreApplication(参见docs)是主应用程序class的控制台版本,不能在GUI应用程序中运行。 QPushButton 是一个小部件 class 并且可以单独存在并且会创建一个 window(尽管你必须 show() 明确地为此)但只能与 QApplication 一起使用。

在 *.pro 文件中使用 qmake 时,您需要像这样包含 widgets

CONFIG += widgets

并确保你没有

CONFIG -= gui

如果您坚持使用 cmake,请参阅 here

以下是我认为您遗漏的内容:

find_package(Qt4 REQUIRED QtGui)

查看您的 cmake,您可能想要更改 target_link_libraries 以下内容:

target_link_libraries(new ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY})

你遇到了三个问题:

  1. 您没有链接到 Gui 模块(Qt 5 中的 Widgets 模块)。 .

  2. 中对此进行了介绍
  3. 您必须在基于小部件的应用程序中使用 QApplication。由于 QPushButton 来自 Gui 模块(Qt5 中的 Widgets),您不能仅使用 QCoreApplicationQGuiApplication:一旦您尝试实例化 [=15,您的程序就会崩溃=].

  4. 你没有显示按钮,所以当你的程序启动时,一旦你修复了上面的问题,你将什么也看不到。

您的 main.cpp 应如下所示:

#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();
}

这个答案解决了我同样的问题:)


ok, i had can solve it by myself.

For all they have they problem too:

The error is sourced from the use of "Q_OBJECT". To solve the error, right-cklick on the Project and choose "Run qmake" and after >this: "Rebuild".

Then the error should be disappeared ;-)

-casisto

https://forum.qt.io/topic/52439/get-undefined-reference-error-but-don-t-know-why/2