本文首发于个人博客https://kezunlin.me/post/cf628dd8/,欢迎阅读!

guide to build qt library and use in another project

Guide

build qt library

QObject class

class  SHARED_EXPORT CameraGrabber : public QObject
{
    Q_OBJECT
        signals :
    void sendFrameTrash(int nCameraID, int nTotalTrashFrame);
public:
    explicit CameraGrabber(QObject *parent = 0);
}

CMakeLists.txt

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)  # for qt SLOTS

add_library(${CAMERA_GRABBER_TARGET}
    CaptureProcess.h
    CaptureProcess.cpp
    FindGrabber.h
    FindGrabber.cpp
    CameraGrabber.h
    CameraGrabber.cpp
)

qt5_use_modules(${CAMERA_GRABBER_TARGET} Core)

target_link_libraries (${CAMERA_GRABBER_TARGET}
    ${CONGIF_TARGET}
    ${SAPERA_LIBRARIES}
)

build and get CameraGrabber.h,CameraGrabber.lib,CameraGrabber.dll and mocs_compilation.cpp.

use qt library in MainWindow

MainWindow.h

#include "Sensor/CameraGrabber/CameraGrabber.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent=0);
    ~MainWindow();

private:
    CameraGrabber *graber = nullptr;
}

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

// moc cpp files for QObject
#include "build/src/car/Sensor/CameraGrabber/MySensorCameraGrabber_autogen/mocs_compilation.cpp"

CMakeLists.txt

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)  # for qt project

#==============================================================
# cpp,ui,resource files
#==============================================================
# cpp files
#aux_source_directory(. SRC_LIST)
set(SRC_LIST
    main.cpp
    mainwindow.h
    mainwindow.cpp
)

# ui files
qt5_wrap_ui(ui_FILES mainwindow.ui)

# resource files
qt5_add_resources(qrc_FILES resource.qrc)

message( [Main] ${SRC_LIST} )
message( [Main] ${ui_FILES} )
message( [Main] ${qrc_FILES} )

#==============================================================
# generate and link target for point_cloud_viewer
#==============================================================
set(TARGET_NAME aa_qt_main)
add_executable(${TARGET_NAME} ${SRC_LIST} ${ui_FILES} ${qrc_FILES})

# link qt libraries
qt5_use_modules(${TARGET_NAME} Core Widgets OpenGL Xml Gui Sql)

# link vtk and pcl libraries
target_link_libraries(${TARGET_NAME}
    ${CONFIG_TARGET}
    ${UTIL_TARGET}
    ${MODEL_TARGET}
    ${DETECTION_TARGET}
    ${DATABASE_TARGET}

    # sensor
    ${CODER_LINKER_TARGET}
    ${RFID_TARGET}
    ${CAMERA_GRABBER_TARGET}
    ${LIDAR_GRABBER_TARGET}

    ${GTEST_LIBRARIES}
    ${BOOST_THREAD_LIBRARY}
    ${GLOG_LIBRARIES}

    ${Boost_LIBRARIES}
    ${OpenCV_LIBS}
    ${PCL_LIBRARIES}
)

tips

If we reference qt dll which use QObject,when we include header in MainWindow.h,we must also include mocs_compilation.cpp in MainWindow.cpp. Otherwise error will occur:

error LNK2001: 无法解析的外部符号 "public: static struct QMetaObject const staticMetaObject

Reference

History

  • 20180409: created.

Copyright

01-01 15:45