RadioButton
Repository source: RadioButton
Description¶
Display a sphere and three radio buttons controlling the appearance of the sphere.
This example is based on this discussion How to implement radio buttons in C++ with [vtkButtonWidget](https://www.vtk.org/doc/nightly/html/classvtkButtonWidget.html) using VTK 9.3?.
Other languages
See (PythonicAPI)
Question
If you have a question about this example, please use the VTK Discourse Forum
Code¶
RadioButton.cxx
#include <vtkActor.h>
#include <vtkButtonWidget.h>
#include <vtkCameraOrientationWidget.h>
#include <vtkCommand.h>
#include <vtkImageData.h>
#include <vtkInteractorStyleSwitch.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkTexturedButtonRepresentation2D.h>
#include <vtkVersion.h>
#include <array>
#include <vector>
#if VTK_VERSION_NUMBER >= 90520250602ULL
#define USE_VTK5 1
#endif
// #undef USE_VTK5
namespace {
vtkNew<vtkImageData> CreateColorImage(std::string const& color);
class RadioButtonCallback : public vtkCommand
{
public:
static RadioButtonCallback* New()
{
return new RadioButtonCallback;
}
void Execute(vtkObject* caller, unsigned long event, void* calldata) override
{
if (event == vtkCommand::StateChangedEvent)
{
vtkButtonWidget* pressedButton = static_cast<vtkButtonWidget*>(caller);
int pressedButtonIndex = -1;
// Find the index of the pressed button.
for (size_t i = 0; i < this->buttons.size(); ++i)
{
if (this->buttons[i] == pressedButton)
{
pressedButtonIndex = static_cast<int>(i);
break;
}
}
// If the pressed button is not already "on", turn it "on" and others
// "off" Assuming 0 is "off" and 1 is "on".
#ifdef USE_VTK5
for (size_t i = 0; i < this->buttons.size(); ++i)
{
if (i != pressedButtonIndex)
{
this->buttons[i]->GetButtonRepresentation()->SetState(0);
}
else
{
this->buttons[i]->GetButtonRepresentation()->SetState(1);
}
#else
if (auto* buttonRep = vtkButtonRepresentation::SafeDownCast(
pressedButton->GetRepresentation()))
{
// Turn "on" the pressed button
buttonRep->SetState(1);
// Turn "off" all other buttons in the group
for (size_t i = 0; i < this->buttons.size(); ++i)
{
if (i != pressedButtonIndex)
{
buttonRep->SetState(0);
}
}
#endif
}
// --- Add your radio button specific actions here ---
// For example, you might print a message indicating
// the button pressed and surface selected:
std::cout << "Radio Button " << pressedButtonIndex << " selected -> ";
//<< std::endl;
// Or change the surface property:
switch (pressedButtonIndex)
{
case 1:
std::cout << "Wireframe" << std::endl;
actor->GetProperty()->SetRepresentationToWireframe();
break;
case 2:
std::cout << "Points" << std::endl;
actor->GetProperty()->SetPointSize(10);
actor->GetProperty()->SetRepresentationToPoints();
break;
default:
std::cout << "Surface" << std::endl;
actor->GetProperty()->SetRepresentationToSurface();
}
// Force a render to update the button appearances.
if (this->interactor)
{
this->interactor->GetRenderWindow()->Render();
}
}
}
// Add the buttons that belong to this radio group.
void AddButton(vtkButtonWidget* button)
{
this->buttons.push_back(button);
}
void SetActor(vtkActor* actor)
{
this->actor = actor;
}
void SetInteractor(vtkRenderWindowInteractor* interactor)
{
this->interactor = interactor;
}
private:
std::vector<vtkSmartPointer<vtkButtonWidget>> buttons;
vtkSmartPointer<vtkRenderWindowInteractor> interactor;
vtkSmartPointer<vtkActor> actor;
};
} // namespace
int main(int, char*[])
{
vtkNew<vtkNamedColors> colors;
colors->SetColor("ParaViewBlueGrayBkg",
std::array<unsigned char, 4>{84, 89, 109, 255}.data());
colors->SetColor("ParaViewWarmGrayBkg",
std::array<unsigned char, 4>{98, 93, 90, 255}.data());
// 1. Create a renderer and render window.
vtkNew<vtkRenderer> renderer;
// renderer->SetBackground(colors->GetColor3d("ParaViewBlueGrayBkg").GetData());
renderer->SetBackground(colors->GetColor3d("ParaViewWarmGrayBkg").GetData());
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer);
renderWindow->SetSize(600, 600);
renderWindow->SetWindowName("RadioButton");
// 2. Create an interactor.
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow);
auto is = vtkInteractorStyleSwitch::SafeDownCast(
renderWindowInteractor->GetInteractorStyle());
if (is)
{
is->SetCurrentStyleToTrackballCamera();
}
// 3. Create some geometry.
vtkNew<vtkSphereSource> sphereSource;
sphereSource->Update();
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetInputConnection(sphereSource->GetOutputPort());
vtkNew<vtkProperty> actorProp;
actorProp->SetColor(colors->GetColor3d("Peru").GetData());
actorProp->SetEdgeColor(colors->GetColor3d("DarkSlateBlue").GetData());
actorProp->EdgeVisibilityOn();
vtkNew<vtkActor> actor;
actor->SetMapper(mapper);
actor->SetProperty(actorProp);
// Add the actors to the scene.
renderer->AddActor(actor);
// 4. Create textures for button states (on and off).
// (Assuming you have functions like CreateButtonOn and CreateButtonOff to
// generate textures) For simplicity, we'll create simple filled squares as
// textures. You would typically load image files for your desired radio
// button appearance.
std::array<std::string, 3> onColors = {"Lavender", "GreenYellow", "Cornsilk"};
std::array<std::string, 3> offColors = {"Indigo", "ForestGreen", "Sienna"};
std::array<vtkNew<vtkImageData>, 3> onImages;
std::array<vtkNew<vtkImageData>, 3> offImages;
for (int i = 0; i < 3; ++i)
{
onImages[i] = CreateColorImage(onColors[i]);
offImages[i] = CreateColorImage(offColors[i]);
}
// vtkNew<vtkImageData> imageOn = CreateImage("Blue");
// vtkNew<vtkImageData> imageOff = CreateImage("Gray");
// 5. Create multiple vtkButtonWidget instances.
std::vector<vtkSmartPointer<vtkButtonWidget>> radioButtons;
const int numRadioButtons = 3;
for (int i = 0; i < numRadioButtons; ++i)
{
vtkNew<vtkTexturedButtonRepresentation2D> buttonRepresentation;
buttonRepresentation->SetNumberOfStates(2); // Two states: on and off.
buttonRepresentation->SetButtonTexture(0, offImages[i]); // State 0: off.
buttonRepresentation->SetButtonTexture(1, onImages[i]); // State 1: on.
// Place the buttons in the scene.
std::array<double, 6> bounds{0.0, 0.0, 0.0, 100.0, 0.0, 0.0};
bounds[0] = 215.0 + i * 60.0; // Adjust for spacing.
bounds[1] = bounds[0] + 50.0;
buttonRepresentation->PlaceWidget(bounds.data());
vtkNew<vtkButtonWidget> buttonWidget;
buttonWidget->SetInteractor(renderWindowInteractor);
buttonWidget->SetRepresentation(buttonRepresentation);
buttonWidget->EnabledOn(); // Enable the button.
radioButtons.push_back(buttonWidget);
}
// 6. Create a callback and associate it with the radio buttons.
vtkNew<RadioButtonCallback> callback;
callback->SetActor(actor);
callback->SetInteractor(renderWindowInteractor);
for (int i = 0; i < numRadioButtons; ++i)
{
callback->AddButton(radioButtons[i]);
radioButtons[i]->AddObserver(vtkCommand::StateChangedEvent, callback);
}
// Initialize the first radio button to "on".
if (!radioButtons.empty())
{
#ifdef USE_VTK5
radioButtons[0]->GetButtonRepresentation()->SetState(1);
#else
if (auto* buttonRep = vtkButtonRepresentation::SafeDownCast(
radioButtons[0]->GetRepresentation()))
{
buttonRep->SetState(1);
}
#endif
}
vtkNew<vtkCameraOrientationWidget> cow;
cow->SetParentRenderer(renderer);
// Enable the widget.
cow->On();
// 7. Start the interaction.
renderWindow->Render();
renderWindowInteractor->Start();
return 0;
}
namespace {
vtkNew<vtkImageData> CreateColorImage(std::string const& color)
{
vtkNew<vtkNamedColors> colors;
std::array<unsigned char, 3> dc{0, 0, 0};
auto c = colors->GetColor3ub(color).GetData();
for (auto i = 0; i < 3; ++i)
{
dc[i] = c[i];
}
vtkNew<vtkImageData> image;
// Specify the size of the image data.
image->SetDimensions(10, 10, 1);
image->AllocateScalars(VTK_UNSIGNED_CHAR, 3);
auto dims = image->GetDimensions();
// Fill the image with color.
for (int y = 0; y < dims[1]; y++)
{
for (int x = 0; x < dims[0]; x++)
{
unsigned char* pixel =
static_cast<unsigned char*>(image->GetScalarPointer(x, y, 0));
for (int i = 0; i < 3; ++i)
{
pixel[i] = dc[i];
}
}
}
return image;
}
} // namespace
CMakeLists.txt¶
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(RadioButton)
find_package(VTK COMPONENTS
CommonColor
CommonCore
CommonDataModel
FiltersSources
InteractionStyle
InteractionWidgets
RenderingContextOpenGL2
RenderingCore
RenderingFreeType
RenderingGL2PSOpenGL2
RenderingOpenGL2
)
if (NOT VTK_FOUND)
message(FATAL_ERROR "RadioButton: Unable to find the VTK build folder.")
endif()
# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(RadioButton MACOSX_BUNDLE RadioButton.cxx )
target_link_libraries(RadioButton PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
TARGETS RadioButton
MODULES ${VTK_LIBRARIES}
)
Download and Build RadioButton¶
Click here to download RadioButton and its CMakeLists.txt file. Once the tarball RadioButton.tar has been downloaded and extracted,
cd RadioButton/build
If VTK is installed:
cmake ..
If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:
cmake -DVTK_DIR:PATH=/home/me/vtk_build ..
Build the project:
make
and run it:
./RadioButton
WINDOWS USERS
Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.