本文主要是介绍PyQt创建VTK,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.定义和调用全局函数来创建VTK图形
import sys
import vtk
from PyQt4 import QtCore, QtGui
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractorclass 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 sourcesource = vtk.vtkSphereSource()source.SetCenter(0, 0, 0)source.SetRadius(5.0)# Create a mappermapper = vtk.vtkPolyDataMapper()mapper.SetInputConnection(source.GetOutputPort())# Create an actoractor = 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 QVTKRenderWindowInteractorclass 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=radiusself.solution=solutionself.height=heightself.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.mapperdef setActor(self):self.actor.SetMapper(self.mapper)def getActor(self):self.createCone()self.setMapper()self.setActor()return self.actorif __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类,并实例化时的执行结果如下:
这篇关于PyQt创建VTK的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!