Documentation/Nightly/Developers/Tutorials/MigrationGuide

From SlicerWiki
Jump to: navigation, search
Home < Documentation < Nightly < Developers < Tutorials < MigrationGuide


Migration Guide



Contents

Slicer backward incompatible changes

Slicer 5.0: API changes since 4.10

  • Removed protected method vtkMRMLModelDisplayableManager::FindPickedDisplayNodeFromMesh

Slicer 4.9: Update of VTK version from 9.0 to 8.2

Following kitware/VTK@b703d78be, VTK has updated to use version number 8.2 instead of 9.0. This was discussed in on the VTK mailing list in http://vtk.1045678.n5.nabble.com/Discussion-OK-to-change-VTK-s-version-number-from-9-0-to-8-2-tt5748702.html

At first, this VTK commit and its companion kitware/VTK@8a00b357e were both reverted from the Slicer/VTK fork. Then, since having the corresponding changes reverted in VTK was not possible, it was decided to also update Slicer. This was done in the following commits:

  • r27472: COMP: Update c++ classes to support building against VTK >= 9 and VTK >= 8.2
  • r27473: COMP: Update VTK to include version change from 9.0 to 8.2. Fixes #4623

This means that code depending on VTK must also be updated to include similar fixes.

Replace this:

 #if VTK_MAJOR_VERSION >= 9

By this:

 #if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2)

and

Replace this:

 #if VTK_MAJOR_VERSION < 9

By this:

 #if VTK_MAJOR_VERSION <= 7 || (VTK_MAJOR_VERSION <= 8 && VTK_MINOR_VERSION <= 1)


Slicer 4.9: ITK_LEGACY_REMOVE is now OFF

In preparation to switch to ITK 5.0, we disable legacy functionality in ITK. This might affect some modules which rely on ITK. Take a look at ITK 4 migration guide before ITK 5 migration guide.

Slicer 4.9: vtkMRMLPlotDataNode renamed to vtkMRMLPlotSeriesNode

Plotting was improved in this commit

Replace this:

 vtkMRMLPlotDataNode

By this:

 vtkMRMLPlotSeriesNode

Slicer 4.9: CMake: Module MIDAS not available

The test infrastructure of your project should be updated to use ExternalData built-in CMake module instead of the specific MIDAS module.

See EMSegment commit r17150 for an example of transition.

This means that instead of using midas_add_test with the MIDAS{path/to/file.ext.md5} syntax for addressing the test data, the function ExternalData_add_target is used by specifying both DATA{path/to/file.ext} and a download target name.

Replace this:

 midas_add_test(NAME test1 COMMAND ...)
 midas_add_test(NAME test2 COMMAND ...)

By this:

 ExternalData_add_test(EMSegmentData NAME test1 COMMAND ...)
 ExternalData_add_test(EMSegmentData NAME test2 COMMAND ...)
 
 [...]
 
 ExternalData_add_target(EMSegmentData)


A key difference with the former approaches is that instead of adding two tests (one named <testName>_fetchData to downoad the data and one running the test command), only one test is added but a common download target is added at the end using ExternalData_add_target function.

This means that test data can now be downloaded in parallel (and cached) at build time instead of testing time.

Slicer 4.9: CMake: Module SlicerMacroCheckExternalProjectDependency not available

Since the module was removed in r26992, consider updating your build system to use CMake module ExternalProjectDependency

Slicer 4.9: CMake: Module SlicerMacroEmptyExternalProject not available

Since the module was removed in r26991

Replace this:

include(SlicerMacroEmptyExternalProject)

[...]

SlicerMacroEmptyExternalProject("${proj}" "${${proj}_DEPENDENCIES}")

By this:

include(ExternalProjectDependency)

[...]

ExternalProject_Add_Empty(${proj} DEPENDS ${${proj}_DEPENDENCIES})

Slicer 4.9: CMake: Module SlicerBlockSetCMakeOSXVariables not available

Since it was renamed to SlicerInitializeOSXVariables in r26982

Replace this:

include(SlicerBlockSetCMakeOSXVariables)

By this:

include(SlicerInitializeOSXVariables)

Slicer 4.9: Application: isRelease() function not available

See #Slicer_4.8:_Application:_isRelease.28.29_function_not_available_or_deprecated

Slicer 4.9: slicer.util.getNode() raises exception if node not found

If slicer.util.getNode() is called and the node is not found then instead of just returning None (Slicer 4.8 behavior), the method now raises a MRMLNodeNotFoundException. This makes code debugging easier (the error is reported when it happens), and in general more consistent with Python conventions.

How to update existing code:

It is advisable to only use slicer.util.getNode in tests, or interactively in the Python console, as its behavior is somewhat unpredictable (it may either found a node by name or ID, and result of wildcard search is even less deterministic). In general, it is recommended to use the MRML scene's GetFirstNodeByName and GetNodeByID methods instead.

Replace this:

n = slicer.util.getNode(nodeNameOrID)

By one of these:

If node is to be found by name:

  n = slicer.mrmlScene.GetFirstNodeByName(nodeName)

If node is to be found by ID:

  n = slicer.mrmlScene.GetNodeByID(nodeID)

If node is to be found by name or ID (slower, less predictable, recommended for testing only):

try:
  n = slicer.util.getNode(nodeNameOrID)
except slicer.util.MRMLNodeNotFoundException:
  n = None

More information: https://github.com/Slicer/Slicer/commit/b63484af1b1b413f35396f8f7efb73e870448bd4

Slicer 4.8: Application: isRelease() function not available or deprecated

Error message similar to:

   Missing/deprecated qSlicerCoreApplication::isRelease()

or

   Missing/deprecated slicer.app.isRelease()


Solution:

Use qSlicerCoreApplication::releaseType() == "Stable"

Summary:

Prior to r26420, the variable Slicer_VERSION_TWEAK was used to check if a "stable release" was built. The variable value was set by updating the sources and defining the variable to an integer greater or equal to 0. In other word, if the variable evaluated to an empty string, a nighty or experimental build was being done, if it evaluated to an integer, a stable release build was being done.

The approach had few issues:

  • the name of the variable was confusing
  • identifying a "stable release" only from a source tree revision was not enough. Indeed the environment defining a "release" is the one found on the build machines used to generate the installer.
  • nightly build are also considered as release

To address this, the CMake variable Slicer_RELEASE_TYPE was introduced. As of 2017-10-04, it can be set to Experimental, Nightly or Stable with Experimental being the value hard-coded in the source.

Identifying a build as "stable" is now explicitly done by setting Slicer_RELEASE_TYPE to Stable at configure time.

Also, since the concept of release types was introduced, the function isRelease() has been removed in favor of releaseType().

References:

https://github.com/Slicer/Slicer/pull/354

Slicer Python Module: modulewidget and others removed.

Summary Python classes formerly in "slicer.moduledm", "slicer.modulelogic", "slicer.modulemrml" and "slicer.modulewidget" are now directly available in the slicer module.

See example of change here.

Rational:

See comments in commit messages referenced blow.

References:

https://github.com/Slicer/Slicer/commit/628f83fe7a6f4e0710e306bcaf7c04b9e3e5e6bd

https://github.com/Slicer/Slicer/commit/9cb5668fde1abc8f0430a91ca37fc29277ceeb4e

MRML: Slicer 4.6: Moved up vtkMRMLStorableNode in the MRML node hierarchy.

Rational:

vtkMRMLStorableNode is not a children of vtkMRMLTransformable node anymore, but directly a children of vtkMRMLNode.

This allows making a node storable without requiring it to be also transformable. It is important for several node types (color maps, tables, etc), which require separate storage node but are not transformable.

References:

Error message similar to:

   /tmp/LongitudinalPETCT/MRML/vtkMRMLLongitudinalPETCTStudyNode.cxx: In member function ‘void vtkMRMLLongitudinalPETCTStudyNode::ObserveRegistrationTransform(bool)’:
   /tmp/LongitudinalPETCT/MRML/vtkMRMLLongitudinalPETCTStudyNode.cxx:478:28: error: ‘class vtkMRMLVolumePropertyNode’ has no member named ‘GetParentTransformNode’
                  && propNode->GetParentTransformNode()
                               ^
   /tmp/LongitudinalPETCT/MRML/vtkMRMLLongitudinalPETCTStudyNode.cxx:480:23: error: ‘class vtkMRMLVolumePropertyNode’ has no member named ‘SetAndObserveTransformNodeID’
                propNode->SetAndObserveTransformNodeID(
                          ^
   /tmp/LongitudinalPETCT/MRML/vtkMRMLLongitudinalPETCTStudyNode.cxx:503:23: error: ‘class vtkMRMLVolumePropertyNode’ has no member named ‘SetAndObserveTransformNodeID’
                propNode->SetAndObserveTransformNodeID(NULL);
                          ^

Solution:

Removes lines and/or refactor code


MRML: Slicer 4.5: Introduction of vtkMRMLLabelMapVolumeNode

Rational:

Before vtkMRMLScalarVolumeNode was used for both scalar and label map volumes and the LabelMap custom MRML node attribute was used for distinguishing between them (0=scalar; 1=label map volume).

This made conversion between labelmap/scalar volumes very easy but made it difficult to customize behavior, display, processing of segmentation information.

Now a new vtkMRMLLabelMapVolumeNode class is used for storing segmentation information (still using vtkMRMLScalarVolume used as base class for backward compatibility; but in the future the base class may be changed to reflect that segmentation can be represented in various ways, not just as volumes).

Error message similar to:

 error: ‘class vtkMRMLScalarVolumeNode’ has no member named ‘SetLabelMap’
    outputVolumeNode->SetLabelMap(1);
                      ^

Solution (part1: down cast to vtkMRMLLabelMapVolumeNode, remove call to SetLabelMap)

Replace lines like:

    vtkMRMLNode* outputNode = d->OutputLabelVolumeMRMLNodeComboBox->currentNode();
    vtkMRMLScalarVolumeNode* outputVolumeNode = vtkMRMLScalarVolumeNode::SafeDownCast(outputNode);
    [...]
    outputVolumeNode->SetLabelMap(1);


with:

    vtkMRMLLabelMapVolumeNode* outputVolumeNode =
      vtkMRMLLabelMapVolumeNode::SafeDownCast(d->OutputLabelVolumeMRMLNodeComboBox->currentNode());
    [...]


Solution (part2: Update UI file):

Replace lines like:

 <widget class="qMRMLNodeComboBox" name="InputLabelVolumeMRMLNodeComboBox">
  <property name="nodeTypes">
   <stringlist>
    <string>vtkMRMLScalarVolumeNode</string>
   </stringlist>
  </property>
  [...]
 </widget>

with:

 <widget class="qMRMLNodeComboBox" name="InputLabelVolumeMRMLNodeComboBox">
  <property name="nodeTypes">
   <stringlist>
    <string>vtkMRMLLabelMapVolumeNode</string>      <------------- Update Here
   </stringlist>
  </property>
  [...]
 </widget>


Solution (part3: Update node selector configuration):

Replace lines like:

 nodeSelector.setNodeTypes(QStringList("vtkMRMLScalarVolumeNode"));
 nodeSelector.addAttribute("vtkMRMLScalarVolumeNode", "LabelMap", "1");

with:

 nodeSelector.setNodeTypes(QStringList("vtkMRMLLabelMapVolumeNode"));


References:


CLI: Slicer 4.3: Add ITKFactoryRegistration library centralizing ITK IO factory registration

Rational:

 Linking against ITKFactoryRegistration ensures that ITK IO factory are properly registered on all supported platforms.

Error message similar to:

 Undefined symbols for architecture x86_64:
 "itk::itkFactoryRegistration()", referenced from:
 _main in ImageMakerTest.cxx.o
 ld: symbol(s) not found for architecture x86_64

Solution:

Replace lines like:

 target_link_libraries(${CLP}Test ${CLP}Lib)

with:

 target_link_libraries(${CLP}Test ${CLP}Lib ${SlicerExecutionModel_EXTRA_EXECUTABLE_TARGET_LIBRARIES})

References:

Slicer Extension updates

Slicer 4.9: Explicit initialization of CMAKE_BUILD_TYPE not needed anymore

Following r26978, calling find_package(Slicer REQUIRED) and include(${Slicer_USE_FILE}) initializes CMAKE_BUILD_TYPE and ensures the variables CMAKE_BUILD_TYPE and CMAKE_CONFIGURATION_TYPES are passed to all external projects when configuring SuperBuild based extension.

The module SlicerInitializeBuildType is automatically included in UserSlicer.

Slicer 4.9: Subversion not required anymore

Following r27060, Subversion is not required anymore.

Slicer 4.9: Support EP_GIT_PROTOCOL and use of ExternalProject_SetIfNotDefined for setting GIT_REPOSITORY, GIT_TAG and alike

Following r26957, extension may use the following convention to define GIT_REPOSITORY and GIT_TAG, this allows developer to override the value before the first configuration by setting the corresponding environment variable, or by explicitly configuring the project with that variable.

The option EP_GIT_PROTOCOL is also already set in ExternalProjectDependency module included by Slicer and its value is updated based on the <SUPERBUILD_TOPLEVEL_PROJECT>_USE_GIT_PROTOCOL option.

  ExternalProject_SetIfNotDefined(
    ${CMAKE_PROJECT_NAME}_${proj}_GIT_REPOSITORY
    "${EP_GIT_PROTOCOL}://github.com/jcfr/shape4D.git"
    QUIET
    )

  ExternalProject_SetIfNotDefined(
    ${CMAKE_PROJECT_NAME}_${proj}_GIT_TAG
    "12fef84ca2a56feffc59d8159bdadd2ce4a4138e" # slicersalt-2018-01-22-c74c766a4c
    QUIET
    )

See:

Slicer 4.9: Use ExternalProject_AlwaysConfigure to force reconfigure of inner project

Following r26551, the function ExternalProject_AlwaysConfigure may be used to ensure the inner project is always reconfigured.

Using the `BUILD_ALWAYS` option supported by ExternalProject_Add will not have the intended effect.

See https://cmake-artichoke.readthedocs.io/en/latest/ExternalProjectDependency.html#function:ExternalProject_AlwaysConfigure

Slicer 4.9: Specifying external projects to install in SuperBuild extension

Following r27267 and r27232, the following should be used to ensure the extension can also be bundled into a Slicer custom application. When bundled, the variable ${EXTENSION_NAME}_CPACK_INSTALL_CMAKE_PROJECTS is then used to update the application's list of project to install.

#-----------------------------------------------------------------------------
set(EXTENSION_CPACK_INSTALL_CMAKE_PROJECTS)
#list(APPEND EXTENSION_CPACK_INSTALL_CMAKE_PROJECTS "${Foo_DIR};Foo;RuntimeLibraries;/")
set(${EXTENSION_NAME}_CPACK_INSTALL_CMAKE_PROJECTS "${EXTENSION_CPACK_INSTALL_CMAKE_PROJECTS}" CACHE STRING "List of external projects to install" FORCE)

#-----------------------------------------------------------------------------
list(APPEND CPACK_INSTALL_CMAKE_PROJECTS "${CMAKE_BINARY_DIR};${EXTENSION_NAME};ALL;/")
list(APPEND CPACK_INSTALL_CMAKE_PROJECTS "${${EXTENSION_NAME}_CPACK_INSTALL_CMAKE_PROJECTS}")
include(${Slicer_EXTENSION_GENERATE_CONFIG})
include(${Slicer_EXTENSION_CPACK})

Slicer 4.9: Generating (Extension)Config.cmake

Initially introduced in r25944, and later improved in r25991, including ${Slicer_EXTENSION_GENERATE_CONFIG} ensure a config is generated and allow an extension to import targets from another extension by using find_package(ExtensionName REQUIRED).

[...]

include(${Slicer_EXTENSION_GENERATE_CONFIG})
include(${Slicer_EXTENSION_CPACK})

Slicer 4.9: Initializing <projectName>_BUILD_SLICER_EXTENSION option: Standalone vs Slicer extension build

The following snippet allows to automatically initialize <projectName>_BUILD_SLICER_EXTENSION to ON if Slicer_DIR is defined.

#-----------------------------------------------------------------------------
# Standalone vs Slicer extension option
#-----------------------------------------------------------------------------

# This option should be named after the project name, it corresponds to the
# option set to ON when the project is build by the Slicer Extension build
# system.

set(_default OFF)
set(_reason "${PROJECT_NAME}_BUILD_SLICER_EXTENSION is ON")
if(NOT DEFINED ${PROJECT_NAME}_BUILD_SLICER_EXTENSION AND DEFINED Slicer_DIR)
  set(_default ON)
  set(_reason "Slicer_DIR is SET")
endif()

option(${PROJECT_NAME}_BUILD_SLICER_EXTENSION "Build as a Slicer Extension" ${_default})

set(_msg "Checking if building as a Slicer extension")
message(STATUS ${_msg})
if(${PROJECT_NAME}_BUILD_SLICER_EXTENSION)
  message(STATUS "${_msg} - yes (${_reason})")
else()
  message(STATUS "${_msg} - no (${PROJECT_NAME}_BUILD_SLICER_EXTENSION is OFF)")
endif()
mark_as_superbuild(${PROJECT_NAME}_BUILD_SLICER_EXTENSION:BOOL)

Transition from VTK7-Qt4 to VTK8-Qt5

This section lists categories of code changes necessary to build and run Slicer with VTK 8.0 and Qt5. Each category has a short description, a suggested upgrade path, and references to relevant commits (TBD once merged).

Slicer SuperBuild Extension: Enable C++11 in external projects

SuperBuild extensions may have to enable C++11 for their external projects. Add the following lines to CMAKE_CACHE_ARGS in ExternalProject_Add

   -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD}
   -DCMAKE_CXX_STANDARD_REQUIRED:BOOL=${CMAKE_CXX_STANDARD_REQUIRED}
   -DCMAKE_CXX_EXTENSIONS:BOOL=${CMAKE_CXX_EXTENSIONS}

Suggested commit message:

COMP: Enable C++11 in external projects

See https://www.slicer.org/wiki/Documentation/Nightly/Developers/Tutorials/MigrationGuide/VTK7-Qt4-to-VTK8-Qt5#Slicer_SuperBuild_Extension:_Enable_C.2B.2B11_in_external_projects

Error message similar to:

/path/to/Slicer-build/ITKv4-build/Modules/Core/Common/itkConfigure.h:59:6: warning: #warning "WARNING:  The current project is configured to use a C++ standard version older than the C++ standard used for this build of ITK" [-Wcpp]
     #warning "WARNING:  The current project is configured to use a C++ standard version older than the C++ standard used for this build of ITK"
      ^

Qt5: Update loadable modules to use new plugin macros

In Qt5, the Q_EXPORT_PLUGIN, Q_EXPORT_PLUGIN2 macros have been deprecated in favor of the new Q_PLUGIN_METADATA macro.

Error message similar to:

error: static assertion failed: Old plugin system used

Suggested commit message:

COMP: Qt5: Fix error: static assertion failed: Old plugin system used

See https://www.slicer.org/wiki/Documentation/Nightly/Developers/Tutorials/MigrationGuide/VTK7-Qt4-to-VTK8-Qt5#Qt5:_Update_loadable_modules_to_use_new_plugin_macros

Solution (part 1):

In qSlicer<NameOfModule>Module.h, replace lines like:

  Q_OBJECT
  Q_INTERFACES(qSlicerLoadableModule);

with:

  Q_OBJECT
#ifdef Slicer_HAVE_QT5
  Q_PLUGIN_METADATA(IID "org.slicer.modules.loadable.qSlicerLoadableModule/1.0");
#endif
  Q_INTERFACES(qSlicerLoadableModule);

Solution (part 2):


In qSlicer<NameOfModule>Module.cxx, Replace lines like:

Q_EXPORT_PLUGIN2(qSlicer<NameOfModule>Module, qSlicer<NameOfModule>Module);

with:

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QtPlugin>
Q_EXPORT_PLUGIN2(qSlicer<NameOfModule>Module, qSlicer<NameOfModule>Module);
#endif

References:

Qt5: Update DesignerPlugin to use QtUiPlugin/QDesignerCustomWidgetInterface

In Qt5, the QtDesigner/QDesignerCustomWidgetInterface header have been deprecated in favor of the new QtUiPlugin/QDesignerCustomWidgetInterface header.

Error message similar to:

/path/to/include/QtDesigner/QDesignerCustomWidgetInterface:4:4: warning: #warning Header <QtDesigner/QDesignerCustomWidgetInterface> is deprecated. Please include <QtUiPlugin/QDesignerCustomWidgetInterface> instead. [-Wcpp]
 #  warning Header <QtDesigner/QDesignerCustomWidgetInterface> is deprecated. Please include <QtUiPlugin/QDesignerCustomWidgetInterface> instead.
    ^

Suggested commit message:

COMP: Update designer plugin to support Qt5

See https://www.slicer.org/wiki/Documentation/Nightly/Developers/Tutorials/MigrationGuide/VTK7-Qt4-to-VTK8-Qt5#Qt5:_Update_DesignerPlugin_to_use_QtUiPlugin.2FQDesignerCustomWidgetInterface

Solution (part 1):

In Widgets/DesignerPlugins/qSlicer<NameOfModule>ModuleWidgetsAbstractPlugin.h, replace lines like:

#include <QDesignerCustomWidgetInterface>

with:

#include <QtGlobal>
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QDesignerCustomWidgetInterface>
#else
#include <QtUiPlugin/QDesignerCustomWidgetInterface>
#endif

Solution (part 2):

In Widgets/DesignerPlugins/qSlicer<NameOfModule>ModuleWidgetsAbstractPlugin.h, replace lines like:

Q_INTERFACES(QDesignerCustomWidgetInterface);

with:

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetInterface")
#endif
  Q_INTERFACES(QDesignerCustomWidgetInterface);

Qt5: Update DesignerPlugin to use QtUiPlugin/QDesignerCustomWidgetCollectionInterface

Error message similar to:

/path/to/5.9.1/gcc_64/include/QtDesigner/QDesignerCustomWidgetCollectionInterface:4:4: warning: #warning Header <QtDesigner/QDesignerCustomWidgetCollectionInterface> is deprecated. Please include <QtUiPlugin/QDesignerCustomWidgetCollectionInterface> instead. [-Wcpp]
 #  warning Header <QtDesigner/QDesignerCustomWidgetCollectionInterface> is deprecated. Please include <QtUiPlugin/QDesignerCustomWidgetCollectionInterface> instead.
    ^

Solution (part 1):

In Widgets/DesignerPlugins/qSlicer<NameOfModule>ModuleWidgetsPlugin.h, replace lines like:

#include <QDesignerCustomWidgetCollectionInterface>

with:

#include "vtkSlicerConfigure.h" // For Slicer_HAVE_QT5

 // Qt includes
#ifdef Slicer_HAVE_QT5
#include <QtUiPlugin/QDesignerCustomWidgetCollectionInterface>
#else
#include <QDesignerCustomWidgetCollectionInterface>
#endif

Solution (part 2):

In Widgets/DesignerPlugins/qSlicer<NameOfModule>ModuleWidgetsPlugin.h, replace lines like:

Q_INTERFACES(QDesignerCustomWidgetCollectionInterface);

with:

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetInterface")
#endif
   Q_INTERFACES(QDesignerCustomWidgetCollectionInterface);

Qt5: any use of QWebKit needs to switch to QWebEngine

TBD

Qt5: QVTKOpenGLWidget

When using Qt5, QVTKOpenGLWidget should be used in place of QVTKGLWidget.

To ensure that QVTKOpenGLWidget receives a properly configured OpenGL context it's necessary to call QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance. QVTKOpenGLWidget::defaultFormat() supplies a suitable format, although it's recommended to disable multisampling for full compatibility with advanced rendering techniques. See http://doc.qt.io/qt-5/qopenglwidget.html.


Error message similar to:

 error: no matching function for call to ‘QVTKWidget::QVTKWidget(QWidget*&)’
        scalarsToColorsView = new QVTKWidget(ctkVTKDiscretizableColorTransferWidget);
                                                                                   ^

Solution (part 1):

In NameOfClass.h file, replace lines like:

 #include <QVTKWidget.h>

with:

 #if CTK_USE_QVTKOPENGLWIDGET
 #include <QVTKOpenGLWidget.h>
 #else
 #include <QVTKWidget.h>
 #endif


Solution (part 2):

In NameOfClass.h file, replace lines like:

 QVTKWidget* View;

with:

 #if CTK_USE_QVTKOPENGLWIDGET
   QVTKOpenGLWidget* View;
 #else
   QVTKWidget* View;
 #endif


Solution (part 3):

In NameOfClass.cpp file, replace lines like:

 this->View = new QVTKWidget;

with:

 #if CTK_USE_QVTKOPENGLWIDGET
   this->View = new QVTKOpenGLWidget;
 #else
   this->View = new QVTKWidget;
 #endif

Qt5: Fix error: 'class QString' has no member named 'toAscii'

Replace call to toAscii().data() with toLatin1().data()

References:

Qt5: Fix error: ‘class QHeaderView’ has no member named ‘setResizeMode’

Error message similar to:

 error: ‘class QHeaderView’ has no member named ‘setResizeMode’
    headerView->setResizeMode(FileColumn, QHeaderView::Stretch);

Solution:

Replace lines like:

 headerView->setResizeMode(FileColumn, QHeaderView::Stretch);

with:

 #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
   headerView->setResizeMode(FileColumn, QHeaderView::Stretch);
 #else
   headerView->setSectionResizeMode(FileColumn, QHeaderView::Stretch);
 #endif

Solution for Python:

 from packaging import version
 ...
 def _setSectionResizeMode(header, *args, **kwargs):
   """ To be compatible with Qt4 and Qt5 """
   if version.parse(qt.Qt.qVersion()) < version.parse("5.0.0"):
     header.setResizeMode(*args, **kwargs)
   else:
     header.setSectionResizeMode(*args, **kwargs)
 ...
 _setSectionResizeMode(horizontalHeader, 1, qt.QHeaderView.ResizeToContents)

VTK8: Use hierarchy files for VTK Python wrapping

In VTK8 it's necessary to generate hierarchy files for proper wrapping VTK classes in Python. Without the information provided by the hierarchy files, the Python wrapping tool lacks complete information about classes and types. In this case, the generated classes contain methods that shouldn't be wrapped and fail to compile, and include references to types such as vtkTypeBool. Once the hierarchy files are generated and provided to the Python wrapping tool, the generated classes compile and typedefs like vtkTypeBool are correctly resolved.

Once the VTK8 changes are merged, generating hierarchy files is handled by https://github.com/Slicer/Slicer/blob/master/CMake/vtkMacroKitPythonWrap.cmake.

References:

VTK8: Use of vtkTypeMacro requires to use the correct base class

Error message similar to:

error: expected unqualified-id before 'protected'

This error is usually a symptom of an incorrect base class when using vtkTypeMacro.

Solution:

Assuming the class vtkIGTLToMRMLPoint derives from vtkIGTLToMRMLBase,

Replace lines like:

vtkTypeMacro(vtkIGTLToMRMLPoint,vtkObject);

with:

vtkTypeMacro(vtkIGTLToMRMLPoint,vtkIGTLToMRMLBase);

References:

VTK8: Copy constructor and equal operator should be disabled

Error message similar to:

error: use of deleted function 'vtkMyClass::vtkMyClass(const vtkMyClass&)'

This error is usually a symptom of not disabling the copy constructor and equal operator.

Solution:

Replace lines like:

protected:
  vtkMyClass();
  ~vtkMyClass();

with:

protected:
  vtkMyClass();
  ~vtkMyClass();
  vtkMyClass(const vtkMyClass&);
  void operator=(const vtkMyClass&);

VTK8: Call InitializeObjectBase() in vtkObject New() methods

In VTK8 it's necessary for vtkObject New() methods to call InitializeObjectBase() on the new object for proper tracking with vtkDebugLeaks. The standard macros (vtkStandardNewMacro, vtkObjectFactoryNewMacro) handle this. For those classes that don't use the macros, add a call to InitializeObjectBase() immediately after constructing the object by new vtkXXX().

Additionally, vtkObjectFactory::CreateInstance() now doesn't register the class name with vtkDebugLeaks if the factory fails to create the object. Therefore, it's no longer necessary to unregister the class name with vtkDebugLeaks. Remove calls to vtkDebugLeaks::DestructClass(className) following vtkObjectFactory::CreateInstance().

To support both VTK8 and earlier versions of VTK, wrap these changes in preprocessor checks for whether VTK_HAS_INITIALIZE_OBJECT_BASE is defined.

References:

VTK8: Add C++11 keywords

VTK8 requires C++11. Subclasses of VTK classes must mark overridden methods with VTK_OVERRIDE.

VTK8: vtkWindowToImageFilter::SetMagnification() is deprecated

VTK8.1 deprecated vtkWindowToImageFilter::SetMagnification() and vtkWindowToImageFilter::GetMagnification(). Replace calls to those methods with SetScale() and GetScale(). See https://github.com/Kitware/VTK/commit/af0a95fa7dd4e25ef869a0bc6077e547f18baa29.

VTK8: vtkInstantiator is deprecated

VTK8.1 deprecated vtkInstantiator. See https://github.com/Kitware/VTK/commit/11bb6a4d395e877847355a63de2e2e8f8d9e1d91

Error message similar to:

/path/to/SlicerIGT-Release/ToolWatchdog/MRMLDM/WatchdogInstantiator.cxx:10:1: error: expected constructor, destructor, or type conversion before ‘void’
 void WatchdogInstantiator::ClassInitialize()
 ^
/path/to/SlicerIGT-Release/ToolWatchdog/MRMLDM/WatchdogInstantiator.cxx: In static member function ‘static void WatchdogInstantiator::ClassFinalize()’:
/path/to/SlicerIGT-Release/ToolWatchdog/MRMLDM/WatchdogInstantiator.cxx:21:3: error: ‘vtkInstantiator’ has not been declared
	 vtkInstantiator::UnRegisterInstantiator("vtkMRMLWatchdogDisplayableManager", vtkInstantiatorvtkMRMLWatchdogDisplayableManagerNew);
	 ^
/path/to/SlicerIGT-Release/ToolWatchdog/MRMLDM/WatchdogInstantiator.cxx:21:80: error: ‘vtkInstantiatorvtkMRMLWatchdogDisplayableManagerNew’ was not declared in this scope
	 vtkInstantiator::UnRegisterInstantiator("vtkMRMLWatchdogDisplayableManager", vtkInstantiatorvtkMRMLWatchdogDisplayableManagerNew);
	                                                                              ^

Solution (part 1):

Update associated CMakeLists.txt replacing lines like:

set(VTK_USE_INSTANTIATOR_NEW 1)
if(${VTK_VERSION_MAJOR} GREATER 5)
  include(${VTK_CMAKE_DIR}/vtkMakeInstantiator.cmake)
endif()
VTK_MAKE_INSTANTIATOR3("${MODULE_NAME}Instantiator"
  displayable_manager_instantiator_SRCS
  "${displayable_manager_SRCS}"
  "${${KIT}_EXPORT_DIRECTIVE}"
  ${CMAKE_CURRENT_BINARY_DIR}
  "${KIT}Export.h"
  )

with:

SlicerConfigureDisplayableManagerObjectFactory(
  TARGET_NAME ${KIT}
  SRCS "${displayable_manager_SRCS}"
  EXPORT_MACRO "${${KIT}_EXPORT_DIRECTIVE}"
  EXPORT_HEADER "${KIT}Export.h"
  OUTPUT_SRCS_VAR displayable_manager_instantiator_SRCS
  )

Solution (part 2):

Update associated qSlicer<NameOfModule>Module.h (or any test requiring displayable manager) adding lines like:

 // DisplayableManager initialization
 #include <vtkAutoInit.h>
 VTK_MODULE_INIT(vtkSlicer<NameOfModule>ModuleMRMLDisplayableManager)


Solution (part 2 - maintaining backward compatibility with Slicer 4.8):

 #include <vtkSlicerVersionConfigure.h> // For Slicer_VERSION_MAJOR, Slicer_VERSION_MINOR
 
 
 [...]
 
 // DisplayableManager initialization
 #if Slicer_VERSION_MAJOR == 4 && Slicer_VERSION_MINOR >= 9
 #include <vtkAutoInit.h>
 VTK_MODULE_INIT(vtkSlicer<NameOfModule>ModuleMRMLDisplayableManager)
 #endif

For example, see https://github.com/SlicerIGT/SlicerIGT/pull/155/commits/2f866ea8872435b9a3a7382dd0549231da00406f

VTK 8.2: Signature of vtkFSLookupTable::MapValue updated

The signature of the function was updated in Kitware/VTK@43f6ee3

Error message similar to:

 error: invalid conversion from ‘const unsigned char*’ to ‘unsigned char*’ [-fpermissive]
 overriding virtual function return type differs and is not covariant from 'vtkLookupTable::MapValue'

Solution:

Update code to use `const` keyword. For example, see r26708

Slicer scripted module initialization steps after application startup

In Slicer 4.8 and earlier versions, those module initialization steps that required application startup completed, often were called using a singleshot timer, because timer events were only processed after the application startup was completed. In Slicer 4.9, some event processing is performed before the application startup is completed, therefore instead of relying on a timer, the application's startupCompleted() signal must be used.

Replace line like:

   qt.QTimer.singleShot(0, self.myAdditionalInitializationSteps)

with:

   slicer.app.connect("startupCompleted()", self.myAdditionalInitializationSteps)

Transition from VTK6 to VTK7

This section lists categories of code changes necessary to build Slicer with VTK 7.1. Each category has a short description, an example error message, a suggested upgrade path, and references to relevant commits.

Referencing this list might be helpful if Slicer extensions require updates to be compatible with VTK 7.1.

Deprecated the vtkStreamer class hierarchy

VTK has deprecated the vtkStreamer class hierarchy.

Error message similar to:

'VTK_INTEGRATE_FORWARD' : undeclared identifier

Solution:

Replace lines like:

#include "vtkStreamer.h"

with:

#include "vtkHyperStreamline.h"

References:

Deprecated vtkMatrix4x4::operator[] method

VTK has deprecated the vtkMatrix4x4::operator[] method.

Error message similar to:

binary '[' : 'vtkMatrix4x4' does not define this operator or a conversion to a type acceptable to the predefined operator

Solution:

Replace lines like:

(*mat)[i][j] = val;
val = (*mat)[i][j];

with:

mat->SetElement(i, j, val);
val = mat->GetElement(i, j);

References:

Removed vtksys/ios, vtksys/stl compatibility layers

VTK has removed the vtksys/ios and vtksys/stl compatibility layers.

Error message similar to:

Cannot open include file: 'vtksys/ios/iostream': No such file or directory

Solution:

Replace lines like:

#include <vtksys/ios/iostream>
#include <vtksys/ios/sstream>

vtksys_ios::ofstream ofs;

with:

#include <iostream>
#include <sstream>

std::ofstream ofs;

Replace lines like:

#include <vtksys/stl/string>
#include <vtksys/stl/vector>

vtksys_stl::string str;
vtksys_stl::vector<double> vec;

with:

#include <string>
#include <vector>

std::string str;
std::vector<double> vec;

References:

vtkDataArray refactored

VTK has refactored the vtkDataArray class hierarchy.

Error message similar to:

'class XXX’ has no member named ‘SetTupleValue’

Solution:

Replace lines like:

array->GetTupleValue(0, val);
array->SetTupleValue(0, val);
array->InsertTupleValue(i, val);
array->InsertNextTupleValue(val);

with:

array->GetTypedTuple(0, val);
array->SetTypedTuple(0, val);
array->InsertTypedTuple(i, val);
array->InsertNextTypedTuple(val);

Replace lines like:

#include <vtkDataArrayTemplate.h>

<any reference to "vtkDataArrayTemplate">

with:

#include <vtkAOSDataArrayTemplate.h>

<reference to "vtkAOSDataArrayTemplate">

References:

Deprecated pipeline update methods

VTK has deprecated and replaced certain pipeline update methods.

Error message similar to:

'class XXX’ has no member named ‘SetUpdateExtent’

Solution:

Follow suggestions in VTK changelog: https://github.com/Kitware/VTK/blob/master/Documentation/Doxygen/ChangesVTK-7-1.md#pipeline-update-methods

References:

Updated Python wrapping

VTK has updated its Python wrapping to support Python 3 and to wrap more code by default.

Symptoms:

Compile or link error while building a Python-wrapped class or library.

Solution 1:

In CMakeLists.txt, add the WRAP_EXCLUDE_PYTHON property anywhere that the WRAP_EXCLUDE property is defined on source files.

Solution 2:

Replace lines of code like:

//BTX
...
//ETX

with:

#ifndef __VTK_WRAP__
...
#endif // __VTK_WRAP__

References:

vtkMTimeType

VTK introduced a specific type—vtkMTimeType—to be used for vtkObject modified time (MTime).

Error message similar to:

vtkDiffusionTensorGlyph::GetMTime': overriding virtual function return type differs and is not covariant from 'vtkObject::GetMTime'

Solution:

Update code that uses unsigned long or unsigned long int for modified times to use vtkMTimeType.

References:

vtkStandardNewMacro expects vtkObjectFactory.h

Error message similar to:

 expected constructor, destructor, or type conversion before ‘;’ token
   vtkStandardNewMacro(vtkSlicerModelClipLogic);

Solution:

Add:

 #include <vtkObjectFactory.h>

Transition from VTK5 to VTK6

This section documents required change to make Slicer code work with VTK6.


Use SetInputPolyDataConnection and GetPolyDataConnection

Starting with Slicer r24801, support for VTK5 API was removed and VTK6 API should be used.

Error message similar to:

error: ‘class vtkMRMLModelDisplayNode’ has no member named ‘SetInputPolyData’
 resultDisplay->SetInputPolyData(resultModel->GetPolyData());
                ^

Solution:

Replace occurrences of SetInputPolyData/GetPolyData with SetInputPolyDataConnection/GetPolyDataConnection.

Use AllocateScalars

Starting with Slicer r24801, support for VTK5 API was removed and VTK6 API should be used.

Error message similar to:

  error: no matching function for call to ‘vtkImageData::SetNumberOfScalarComponents(int)’
    mp_phi->SetNumberOfScalarComponents(1);
                                         ^

Solution:

Replace lines like:

 imageData->SetScalarTypeToUnsignedShort();		
 imageData->SetNumberOfScalarComponents(1); // image holds one value intensities		
 imageData->AllocateScalars(); // allocate storage for image data

with:

 imageData->AllocateScalars(VTK_UNSIGNED_SHORT, 1); // allocate storage for image data