一、创建步骤
打开QtCreate,创建project,选择Qt Quick Application
创建工程名字,选择保存路径
选择最低使用版本
前两个选项可以根据实际情况进行勾选
选择开发的SDK
创建好后QtCreate界面如下
二、分析所创建的工程
1.工程目录分析
刚刚保存工程的目录下会生成如上图所示的文件
CMakeLists.txt
CMakeLists.txt.user
main.cpp
Main.qml
以及编译产生的文件目录build
2.CMakeLists.txt
CMake工程项目管理文件
内容如下:
cmake_minimum_required(VERSION 3.16)
#cmake最低版本要求
project(appqml VERSION 0.1 LANGUAGES CXX)
#项目名称appqml,与生成的执行文件相关
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 6.5 REQUIRED COMPONENTS Quick)
#对应的package的库
qt_standard_project_setup(REQUIRES 6.5)
#Qt库的设置
qt_add_executable(appappqml
main.cpp
)
#添加一个执行程序
qt_add_qml_module(appappqml
URI appqml
VERSION 1.0
QML_FILES
Main.qml
)
#以模块的形式把QML添加到工程中
# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1.
# If you are developing for iOS or macOS you should consider setting an
# explicit, fixed bundle identifier manually though.
set_target_properties(appappqml PROPERTIES
# MACOSX_BUNDLE_GUI_IDENTIFIER com.example.appappqml
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
target_link_libraries(appappqml
PRIVATE Qt6::Quick
)
#Qt链接库
include(GNUInstallDirs)
install(TARGETS appappqml
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
3.CMakeLists.txt.user
当前选择的编译属性,如SDK等,这个文件不会出现在QtCreate中,
xml格式可以不用关注
4.main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;//使用qml中的engine
//使用QObject信号与槽机制,当engine创建失败,执行QueuedConnection函数
QObject::connect(
&engine,
&QQmlApplicationEngine::objectCreationFailed,
&app,
[]() { QCoreApplication::exit(-1); },
Qt::QueuedConnection);
/*对engine以模块的形式进行加载,模块名称appqml对应camke中qt_add_qml_module(appappqml
URI appqml
VERSION 1.0
QML_FILES
Main.qml
)
加载模块中的Main
*/
engine.loadFromModule("appqml", "Main");
return app.exec();
}
5.Main.qml
import QtQuick
//导入Qt库
//描述一个窗口
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
}