Embedding VTK object in PyQT5 window

孤人 提交于 2019-12-06 13:46:49

When you call the method Start() you are starting the event loop, which means that the following instructions will not be executed. Tipically you start the event loop after you completed the VTK pipeline, i.e, after you defined your actors, mappers, etc.

Have you checked this example here? https://www.vtk.org/Wiki/VTK/Examples/Python/Widgets/EmbedPyQt

It works fine, but assumes that you have PyQt4. In order to work with PyQt5, I made a few changes. Try this:

import sys
import vtk
from PyQt5 import QtCore, QtGui
from PyQt5 import Qt

from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor

class MainWindow(Qt.QMainWindow):

    def __init__(self, parent = None):
        Qt.QMainWindow.__init__(self, parent)

        self.frame = Qt.QFrame()
        self.vl = Qt.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()

        # 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)

        self.ren.AddActor(actor)

        self.ren.ResetCamera()

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        self.show()
        self.iren.Initialize()
        self.iren.Start()


if __name__ == "__main__":
    app = Qt.QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

Important note: if your qt application becomes increasingly complex and you will be using multiple QVTKRenderWindowInteractor objects in it, do not call the interactor through the Start() method. Otherwise, as I mentioned before, you are creating another unnecessary event loop inside your qt application (app.exec() starts the qt loop). In this case, I think you should call app.exec() after you declared you necessary objects. More information can be found in these links:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!