1.定义和调用全局函数来创建VTK图形
import sys
import vtk
from PyQt4 import QtCore, QtGui
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.frame = QtGui.QFrame()
self.vl = QtGui.QVBoxLayout()
self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
self.vl.addWidget(self.vtkWidget)
self.ren = vtk.vtkRenderer()
self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
CreateCone(self.ren) ##调用全局函数
self.frame.setLayout(self.vl)
self.setCentralWidget(self.frame)
self.show()
self.iren.Initialize()
##定义为全局函数
def CreateCone(ren):
# Create source
source = vtk.vtkSphereSource()
source.SetCenter(0, 0, 0)
source.SetRadius(5.0)
# Create a mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(source.GetOutputPort())
# Create an actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)
ren.AddActor(actor)
ren.ResetCamera()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
2.面向对象OOP方法:
import sys
import vtk
from PyQt4 import QtCore, QtGui
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.frame = QtGui.QFrame()
self.vl = QtGui.QVBoxLayout()
self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
self.vl.addWidget(self.vtkWidget)
self.ren = vtk.vtkRenderer()
self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
cone=Cone(10,40,50,[0,0,0]) #声明Cone类,并实例化
self.ren.AddActor(cone.getActor()) #将cone的Actor属性添加到流水化管线中
self.frame.setLayout(self.vl)
self.setCentralWidget(self.frame)
self.show()
self.iren.Initialize()
##定义Cone类
class Cone:
def __init__(self,radius=10,height=10,solution=10,center=[0,0,0]):
self.radius=radius
self.solution=solution
self.height=height
self.center_x=center[0]
self.center_y=center[1]
self.center_z=center[2]
self.cone=vtk.vtkConeSource()
self.mapper=vtk.vtkPolyDataMapper()
self.actor=vtk.vtkActor()
def createCone(self):
self.cone.SetCenter(self.center_x,self.center_y,self.center_z)
self.cone.SetRadius(self.radius)
self.cone.SetHeight(self.height)
self.cone.SetResolution(self.solution)
def setMapper(self):
self.mapper.SetInputConnection(self.cone.GetOutputPort())
def getMapper(self):
return self.mapper
def setActor(self):
self.actor.SetMapper(self.mapper)
def getActor(self):
self.createCone()
self.setMapper()
self.setActor()
return self.actor
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
cone=Cone(10,10,50,[0,0,0]) #声明Cone类,并实例化时的执行结果如下:
当实例化语句为:
cone=Cone(10,40,50,[0,0,0]) #声明Cone类,并实例化时的执行结果如下: