In VTK, interactions typically occur using command/observer mode, where the observer waits for a command and executes the interaction function once a command is triggered.
There are two implementation modes:
- Set the callback function. 2. Inherit the Command class and implement the internal function
Let’s look at the first way.
If we look at the code, first define a callback function. Notice that the function signature of the callback function must be the same except for the function name, such as the return value, and the argument list.
`void MyCallbackFunc(vtkObject*, unsigned long eid, void* clientdata, void *calldata) { std::cout << "aaaaaaaa " << std::endl; } `Copy the code
Then inside the main function we define the callback function
`vtkSmartPointer<vtkCallbackCommand> mouseCallback = vtkSmartPointer<vtkCallbackCommand>::New(); mouseCallback->SetCallback(MyCallbackFunc); `Copy the code
Finally, add the callback function command object to the observer list.
`interactor->SetRenderWindow(viewer->GetRenderWindow()); interactor->AddObserver(vtkCommand::LeftButtonPressEvent, mouseCallback); `Copy the code
// The interactor is defined as vtkSmartPointer Interactor so that when we click VTK, the terminal will output “aaaaaaaa”
Let’s look at the second way: subclass from the vtkCommand class.
First we derive:
Class vtkMyCallback: public vtkCommand {public: static vtkMyCallback *New() {return New vtkMyCallback; } void someFunction(int a) { value = a; } // Just print the value. Virtual void Execute(vtkObject * Caller, unsigned long eventId, void* callData) { std::cout << "value = " << value << std::endl; } private: int value; }; `Copy the code
For the sake of effect, we assign a value to the inside of the box, mainly because the argument is fixed, so we have nothing else to output, just output a value.
The remaining steps are similar to before:
VtkSmartPointer <vtkMyCallback> callback = vtkSmartPointer<vtkMyCallback>::New(); callback->someFunction(222); / / the third interactor - > AddObserver (vtkCommand: : LeftButtonPressEvent, callback); `Copy the code
Click on the screen area and it will output “value = 222”.