VTK QT 之 RenderWindowNoUiFile

islinyoubiao發表於2020-12-20

VTK9之不用Qt ui檔案顯示

1.背景

VTK9已經沒有了 #include <QVTKWidget.h>,可能是因為QtCreator的許可的原因。

像以下程式碼,不合用了:

#include <QApplication>

#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>

#include <QVTKWidget.h>

int main(int argc, char** argv)
{
  QApplication app(argc, argv);

  QVTKWidget widget;
  widget.resize( 256, 256 );

  vtkSmartPointer<vtkSphereSource> sphereSource =
      vtkSmartPointer<vtkSphereSource>::New();

  vtkSmartPointer<vtkPolyDataMapper> sphereMapper =
      vtkSmartPointer<vtkPolyDataMapper>::New();
  sphereMapper->SetInputConnection( sphereSource->GetOutputPort() );

  vtkSmartPointer<vtkActor> sphereActor =
      vtkSmartPointer<vtkActor>::New();
  sphereActor->SetMapper( sphereMapper );

  vtkSmartPointer<vtkRenderer> renderer =
      vtkSmartPointer<vtkRenderer>::New();
  renderer->AddActor( sphereActor );
 
  widget.GetRenderWindow()->AddRenderer( renderer );
  widget.show();

  app.exec();

  return EXIT_SUCCESS;
}

2.VTK8.9之後

VTK9當然是沒有了,所以有新的方法,程式碼如下:

#include <QApplication>

#include <vtkActor.h>
#include <vtkGenericOpenGLRenderWindow.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkSphereSource.h>
#include <vtkVersion.h>

#if VTK_VERSION_NUMBER >= 89000000000ULL
#define VTK890 1
#endif

#include <QSurfaceFormat>
#include <QVTKOpenGLNativeWidget.h>

int main(int argc, char** argv)
{
    // needed to ensure appropriate OpenGL context is created for VTK rendering.
    QSurfaceFormat::setDefaultFormat(QVTKOpenGLNativeWidget::defaultFormat());

    QApplication app(argc, argv);

    QVTKOpenGLNativeWidget widget;

    vtkNew<vtkNamedColors> colors;

    vtkNew<vtkGenericOpenGLRenderWindow> renderWindow;
#if VTK890
    widget.setRenderWindow(renderWindow);
#else
    widget.SetRenderWindow(renderWindow);
#endif

    widget.resize(600, 600);

    vtkNew<vtkSphereSource> sphereSource;

    vtkNew<vtkPolyDataMapper> sphereMapper;
    sphereMapper->SetInputConnection(sphereSource->GetOutputPort());

    vtkNew<vtkActor> sphereActor;
    sphereActor->SetMapper(sphereMapper);
    sphereActor->GetProperty()->SetColor(colors->GetColor4d("Tomato").GetData());

    vtkNew<vtkRenderer> renderer;
    renderer->AddActor(sphereActor);
    renderer->SetBackground(colors->GetColor3d("SteelBlue").GetData());

#if VTK890
    widget.renderWindow()->AddRenderer(renderer);
    widget.renderWindow()->SetWindowName("RenderWindowNoUIFile");
#else
    widget.GetRenderWindow()->AddRenderer(renderer);
    widget.GetRenderWindow()->SetWindowName("RenderWindowNoUIFile");
#endif
    widget.show();

    app.exec();

    return EXIT_SUCCESS;
}

3.執行結果

在這裡插入圖片描述

總結

以前就是不習慣那個QVTKWidget,不好用,不如不要。這個簡潔好多了。
PCL1.11.1庫還不支援最新的VTK,不知道什麼時候會升級VTK相關的程式碼。

相關文章