新建Qt Quick Application。
main.cpp(保持原有的即可):
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int
main (int argc, char *argv[])
{
QGuiApplication app (argc, argv);
QQmlApplicationEngine engine;
const QUrl url (QStringLiteral ("qrc:/MainWindow/Main.qml"));
QObject::connect (
&engine,
&QQmlApplicationEngine::objectCreationFailed,
&app,
[] () { QCoreApplication::exit (-1); },
Qt::QueuedConnection
);
engine.load (url);
return app.exec();
}
main.qml:
import QtQuick
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Image{
id:logo
source:"qrc:/images/img.png"
anchors.centerIn:parent
}
MyText{
anchors.top:logo.bottom
anchors.horizontalCenter:logo.horizontalCenter
}
}
新建MyText.qml:
import QtQuick
Text{
text: qsTr("这是一行绿色的文字")
color: "green"
}
新建images.qrc(注意设置CMAKE_AUTORCC
并添加到CMakeLists.txt的qt_add_executable
):
<RCC>
<qresource prefix="/">
<file>images/img.png</file>
</qresource>
</RCC>
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16)
project(MainWindow VERSION 0.1 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 6.4 REQUIRED COMPONENTS Quick)
qt_standard_project_setup()
set(CMAKE_AUTORCC ON)
qt_add_executable(appMainWindow
main.cpp
images.qrc
)
qt_add_qml_module(appMainWindow
URI MainWindow
VERSION 1.0
QML_FILES Main.qml
QML_FILES MyText.qml
RESOURCES images.qrc
)
# 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(appMainWindow PROPERTIES
# MACOSX_BUNDLE_GUI_IDENTIFIER com.example.appMainWindow
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(appMainWindow
PRIVATE Qt6::Quick
)
include(GNUInstallDirs)
install(TARGETS appMainWindow
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
效果
另外如果只进行UI设计,可以新建Qt Quick UI项目,避免了编译C++程序,可以更快地预览效果。