VTK 随笔一 ,使用Qt + vtk 画一条直线
1、创建qt工程不做赘述。
2、创建一个类继承QVTKOpenGLNativeWidget (这个是vtk给qt项目准备的),此类可以是空类,vtkView.cpp 只要实现构造就可以。
#pragma once #include <QVTKOpenGLNativeWidget.h> #include <QObject> class vtkView : public QVTKOpenGLNativeWidget { Q_OBJECT public: vtkView(QWidget *parent = nullptr); ~vtkView(); };
3、创建一个布局类,用于显示布局,我使用MainWindown,之间作为布局类,具体实现如下
#pragma once #include <QGridLayout> #include <QWidget> class MainWindown : public QWidget { Q_OBJECT public: MainWindown(QWidget *parent = nullptr); ~MainWindown(); void initUI(); QWidget *makeVTKWgt(); };
#include "MainWindown.h" #include <vtkActor.h> #include <vtkAutoInit.h> #include <vtkDataSetMapper.h> #include <vtkLineSource.h> #include <vtkPlaneSource.h> #include <vtkPolyData.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include "vtkView.h" MainWindown::MainWindown(QWidget *parent) : QWidget(parent) { setFixedSize(800, 800); initUI(); } MainWindown::~MainWindown() {} void MainWindown::initUI() { QGridLayout *grid = new QGridLayout(); grid->addWidget(makeVTKWgt(), 0, 0); grid->addWidget(makeVTKWgt(), 0, 1); setLayout(grid); } #include "vtkImageData.h" void aa() { vtkImageData *img; img->GetDimensions(); img->GetSpacing(); } QWidget *MainWindown::makeVTKWgt() { double p0[3] = {100.0, 100.0, 0.0}; double p1[3] = {300.0, 300.0, 0.0}; vtkLineSource *line = vtkLineSource::New(); line->SetPoint1(p0); line->SetPoint2(p1); line->Update(); vtkDataSetMapper *mapper = vtkDataSetMapper::New(); mapper->SetInputConnection(line->GetOutputPort()); vtkActor *lineActor = vtkActor::New(); lineActor->SetMapper(mapper); lineActor->GetProperty()->SetColor(1, 0, 0); lineActor->GetProperty()->SetLineWidth(3); vtkRenderer *renderer = vtkRenderer::New(); renderer->AddActor(lineActor); // vtkRenderWindow *rendererWindow = vtkRenderWindow::New(); // rendererWindow->AddRenderer(renderer); // rendererWindow->Render(); // vtkRenderWindowInteractor *inter = vtkRenderWindowInteractor::New(); // inter->SetRenderWindow(rendererWindow); // inter->Start(); vtkView *wgt = new vtkView(this); // wgt->setFixedSize(400, 400); wgt->renderWindow()->AddRenderer(renderer); wgt->renderWindow()->Render(); return wgt; }
4、效果图展示