Modify a vtkMRMLNode via another thread

Operating system: macOS 10.14.6
Slicer version: 4.10.2

I want to simulate respiratory motion on another thread via QTimer. I did it like this :

connect(processTimer, &QTimer::timeout, [=]() {breathingProcess();});

void qSlicerSimulationModuleWidget::breathingProcess()
{
    // if theres is no current animation (mutex is a kind of thread safe guard)
    if (mutex->tryLock())
    {

        int index = 0;

        generateFactor();

        // For each node in the movement data base
        for(std::vector<std::pair<vtkMRMLNode*, int>>::const_iterator itS = organType.begin(); itS != organType.end(); itS++)
        {
            vtkSmartPointer<vtkPolyData> input = vtkMRMLModelNode::SafeDownCast((*itS).first)->GetPolyData();

            vtkIdType numberOfPoints = input->GetNumberOfPoints();

            // According to the type of the organ, apply the right movement
            switch((*itS).second){
            case 0 :
                // Liver, Spleen, Pancreas
                BreathingSimulation::move_liver_like(input, numberOfPoints, factor, translation.x(),  translation.y(), translation.z(), translationFactor.x(), translationFactor.y(), translationFactor.z());
                break;
            case 4 :
                // Ribs
                BreathingSimulation::move_ribs(input, numberOfPoints, factor, translation.x(),  translation.y(), translation.z(), translationFactor.x(), translationFactor.y(), translationFactor.z());
                break;
            default:
                // Default
                // Do nothing
                break;
            }

            // Refresh display and view
            (*itS).first->Modified();
        }
        mutex->unlock();
    }
}

But it would not display the modifications in Viewer. Can you help me to modify nodes regularly, please ?

Thank you.

You can compute the updated polydata on a background thread but you need to update the model node (by deep or shallow copy) from the main thread from a timer callback.

1 Like