Ruixiang Du

Using QT in ROS Catkin Packages

Rviz plugins are basically QT widgets. CMakeLists.txt of the ROS package using QT needs to be modified accordingly for the compilation. ROS wiki provides several tutorials/examples about how to write a plugin for Rviz and how to configure the package. However, these materials are mainly for rosbuild. This article introduces how to use QT in ROS catkin packages, in other words, how to use QT for a package of ROS Groovy/Hydro or later. This article shows how to write the CMakeLists.txt for a package, which uses librviz for visualization.

The example package includes the following files:

++ rviz_gui_package
 ++ src
   +- rviz_gui.cpp
   +- rviz_gui.h
   +- rviz_gui.ui
   +- main.cpp
 +- CMakeLists.txt
 +- package.xml

To compile a QT executable widget, you need to add the following to your CMakeLists.txt:

find_package(Qt4 COMPONENTS QtCore QtGui REQUIRED)

include(${QT_USE_FILE})
add_definitions(-DQT_NO_KEYWORDS)
add_definitions(${QT_DEFINITIONS})

set(HEADER_FILES 
  src/rviz_gui.h
  include/myviz.h
)

set(SOURCE_FILES
  src/rviz_gui.cpp
  src/main.cpp
  ${MOC_FILES}
)

set(FORM_FILES 
  src/rviz_gui.ui
)

QT4_WRAP_CPP(MOC_SRC_H
  ${HEADER_FILES}
)

QT4_WRAP_UI(MOC_GUI_H 
  ${FORM_FILES}
)

include_directories(${CMAKE_CURRENT_BINARY_DIR})

add_executable(rviz_gui ${SOURCE_FILES} ${MOC_SRC_H} ${MOC_GUI_H})
target_link_libraries(rviz_gui ${QT_LIBRARIES} ${catkin_LIBRARIES})

To understand why you should do this, you need to understand the QT build system. For detailed illustration, read this Document from qt-project.org. The image shown below is also from this document. I include it here just for convinence of reference.

The basic idea of the above code snippet,

  • Line 1-4 set up the environment.
  • Line 7-20 tells the build system the source/header/form files for the qt application.
  • Line 22-24 correspond to “generated moc_*.cpp” block in the above image.
  • Line 26-28 correspond to “generated ui_*.h” block in the above image.
  • No resource file is used in this example, so “Resource files” and “generated qrc_*.cpp” blocks are not used.
  • Line 30, according to Document, “As all intermediate files are generated outside the source tree, the header file generated by uic will not be located by the compiler. In order to handle this, the build directory needs to be added to the list of include directories.”
  • Line 32-33 compile and link executables based on all user files and Qt intermediate files.

The complete copy of CMakeLists.txt (modified from the original file generated by command catkin_create_pkg)

#####Reference:

  1. Using CMake to Build Qt Projects
  2. Using QT in a ROS Catkin Package