近期在学习Qt,目前使用的是Cmake编译, 在自己尝试生成视频播放器的时候,不出意外的无法链接 QMultiMedia头文件,在网上查了一下教程后,也成功完成了Qt5MultiMedia的链接,以下是我的一些经验:
版本是Qt5.15.2 用Cmake编译,如果是Qmake编译则采用以下代码即可
qt += MultiMedia
1、Cmake文件中红可以不添加相应的路径
很多博客中首先要求先添加相应的路径,但是Qt5MultiMedia与Core、gui库其实在同一目录下,如果makelist能包含gui库,同理应该也能包含MultiMedia。(个人见解,如有问题麻烦各位帮忙指正)
set(CMAKE_PREFIX_PATH $ENV{QTDIR594})
2、查找相应模块
find_package(Qt5Multimedia)
3、链接相应库
target_link_libraries(myProject10 PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt5::Multimedia)
查找到相应模块后,编译正常,但是无法正确引用头文件,这个时候我怀疑是查找到了库但是没有正确的链接到工程文件中,于是尝试在target_link_libraries中添加新的库文件,于是OK。
以下是我的
cmake_minimum_required(VERSION 3.5)
project(myProject10 VERSION 0.1 LANGUAGES CXX)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
find_package(Qt5Multimedia)
set(PROJECT_SOURCES
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
)
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(myProject10
MANUAL_FINALIZATION
${PROJECT_SOURCES}
)
# Define target properties for Android with Qt 6 as:
# set_property(TARGET myProject10 APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
# ${CMAKE_CURRENT_SOURCE_DIR}/android)
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
else()
if(ANDROID)
add_library(myProject10 SHARED
${PROJECT_SOURCES}
)
# Define properties for Android with Qt 5 after find_package() calls as:
# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
else()
add_executable(myProject10
${PROJECT_SOURCES}
qmyvideowidget.h qmyvideowidget.cpp
)
endif()
endif()
target_link_libraries(myProject10 PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt5::Multimedia)
# 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.
if(${QT_VERSION} VERSION_LESS 6.1.0)
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.myProject10)
endif()
set_target_properties(myProject10 PROPERTIES
${BUNDLE_ID_OPTION}
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
include(GNUInstallDirs)
install(TARGETS myProject10
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(myProject10)
endif()
Cmake文件