参考资料:cmake.org/cmake/help/latest/manual/cmake-qt.7.html
1. 创建文件
-
$ mkdir qt_cmake
-
$ cd qt_cmake
-
$ touch hello.cpp
-
$ touch CMakeLists.txt
2. 文件内容
hello.cpp
-
#include <QApplication>
-
#include <QWidget>
-
#include <QGridLayout>
-
#include <QLabel>
-
-
int main(int argc, char *argv[]) {
-
-
QApplication app(argc, argv);
-
-
QWidget widget;
-
widget.resize(640, 480);
-
widget.setWindowTitle("Hello, world!!!");
-
-
QGridLayout *gridLayout = new QGridLayout(&widget);
-
-
QLabel * label = new QLabel("Hello, world!!!");
-
label->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
-
gridLayout->addWidget(label);
-
-
widget.show();
-
-
return app.exec();
-
}
CMakeLists.txt
-
cmake_minimum_required(VERSION 3.5)
-
project(hello)
-
-
set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
set(CMAKE_AUTOUIC ON)
-
set(CMAKE_AUTOMOC ON)
-
set(CMAKE_AUTORCC ON)
-
set(CMAKE_CXX_STANDARD 11)
-
set(CMAKE_CXX_STANDARD_REQUIRED ON)
-
find_package(Qt5 COMPONENTS Core Gui Widgets REQUIRED)
-
-
-
-
set (SRCS
-
CMakeLists.txt
-
hello.cpp
-
)
-
-
-
add_executable(${CMAKE_PROJECT_NAME} ${SRCS})
-
-
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE Qt5::Core Qt5::Gui Qt5::Widgets)
3. 编译运行
-
$ mkdir build
-
$ cmake ..
-
$ make
-
$ ./hello
4. 运行效果
5. 问题
cmake 可能提示 “By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project .....” 是 cmake 找不到 qt 安装位置,可以在通过在 cmake 配置生成阶段定义 CMAKE_PREFIX_PATH 解决
-
$ cmake .. -DCMAKE_PREFIX_PATH:STRING=/home/sunhx/Qt5.14.2/5.14.2/gcc_64
-
$ cmake --build .
-
$ ./hello
阅读(803) | 评论(0) | 转发(0) |