QVTKRenderWindowInteractor.py 11.8 KB
Newer Older
1
2
3
"""
A simple VTK input file for PyQt, the qt bindings for python.
See http://www.trolltech.com for qt documentation, and
Ken Martin's avatar
Ken Martin committed
4
5
http://www.river-bank.demon.co.uk or http://www.thekompany.com
for the qt python bindings.
6
7
8
9
10
11
12

This class is based on the vtkGenericRenderWindowInteractor and is
therefore fairly powerful.  It should also play nicely with the
vtk3DWidget code.

Created by Prabhu Ramachandran, May 2002
Based on David Gobbi's QVTKRenderWidget.py
Ken Martin's avatar
Ken Martin committed
13
14

Changes by Gerard Vermeulen Feb. 2003
15
 Win32 support.
Ken Martin's avatar
Ken Martin committed
16

17
18
Changes by Gerard Vermeulen, May 2003
 Bug fixes and better integration with the Qt framework.
19
20
21
"""

"""
Ken Martin's avatar
Ken Martin committed
22
This class works with the UNIX and Win32 versions of Qt.
23
24
25
26
27
28
29
30

Depending on the OpenGL graphics drivers, it may not
be possible to have more than one QVTKRenderWidget
per application.

In short, this class is experimental.
"""

Ken Martin's avatar
Ken Martin committed
31
32
33
34
35

# To do for Win32:
# 1. More testing to assure that the widget is always cleaned up
#    properly and does not crash the application.

36
37
38
39
40
41
42
43
44
import qt
import vtk

class QVTKRenderWindowInteractor(qt.QWidget):

    """ A QVTKRenderWindowInteractor for Python and Qt.  Uses a
    vtkGenericRenderWindowInteractor to handle the interactions.  Use
    GetRenderWindow() to get the vtkRenderWindow.  Create with the
    keyword stereo=1 in order to generate a stereo-capable window.
Ken Martin's avatar
Ken Martin committed
45
46
47
48
49
50
51
52

    The user interface is summarized in vtkInteractorStyle.h:

    - Keypress j / Keypress t: toggle between joystick (position
    sensitive) and trackball (motion sensitive) styles. In joystick
    style, motion occurs continuously as long as a mouse button is
    pressed. In trackball style, motion occurs when the mouse button
    is pressed and the mouse pointer moves.
53

Ken Martin's avatar
Ken Martin committed
54
55
56
57
    - Keypress c / Keypress o: toggle between camera and object
    (actor) modes. In camera mode, mouse events affect the camera
    position and focal point. In object mode, mouse events affect
    the actor that is under the mouse pointer.
58

Ken Martin's avatar
Ken Martin committed
59
60
61
62
63
64
    - Button 1: rotate the camera around its focal point (if camera
    mode) or rotate the actor around its origin (if actor mode). The
    rotation is in the direction defined from the center of the
    renderer's viewport towards the mouse position. In joystick mode,
    the magnitude of the rotation is determined by the distance the
    mouse is from the center of the render window.
65

Ken Martin's avatar
Ken Martin committed
66
67
68
69
70
71
    - Button 2: pan the camera (if camera mode) or translate the actor
    (if object mode). In joystick mode, the direction of pan or
    translation is from the center of the viewport towards the mouse
    position. In trackball mode, the direction of motion is the
    direction the mouse moves. (Note: with 2-button mice, pan is
    defined as <Shift>-Button 1.)
72

Ken Martin's avatar
Ken Martin committed
73
74
75
76
77
78
    - Button 3: zoom the camera (if camera mode) or scale the actor
    (if object mode). Zoom in/increase scale if the mouse position is
    in the top half of the viewport; zoom out/decrease scale if the
    mouse position is in the bottom half. In joystick mode, the amount
    of zoom is controlled by the distance of the mouse pointer from
    the horizontal centerline of the window.
79
80
81
82
83
84
85
86

    - Keypress 3: toggle the render window into and out of stereo
    mode.  By default, red-blue stereo pairs are created. Some systems
    support Crystal Eyes LCD stereo glasses; you have to invoke
    SetStereoTypeToCrystalEyes() on the rendering window.  Note: to
    use stereo you also need to pass a stereo=1 keyword argument to
    the constructor.

Ken Martin's avatar
Ken Martin committed
87
    - Keypress e: exit the application.
88

Ken Martin's avatar
Ken Martin committed
89
    - Keypress f: fly to the picked point
90

Ken Martin's avatar
Ken Martin committed
91
92
    - Keypress p: perform a pick operation. The render window interactor
    has an internal instance of vtkCellPicker that it uses to pick. 
93

Ken Martin's avatar
Ken Martin committed
94
95
96
    - Keypress r: reset the camera view along the current view
    direction. Centers the actors and moves the camera so that all actors
    are visible.
97

Ken Martin's avatar
Ken Martin committed
98
99
    - Keypress s: modify the representation of all actors so that they
    are surfaces. 
100

Ken Martin's avatar
Ken Martin committed
101
102
    - Keypress u: invoke the user-defined function. Typically, this
    keypress will bring up an interactor that you can type commands in.
103

Ken Martin's avatar
Ken Martin committed
104
105
    - Keypress w: modify the representation of all actors so that they
    are wireframe.
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    """
    
    def __init__(self, parent=None, name=None, *args, **kw):
        # the current button
        self._ActiveButton = 0

        # private attributes
        self.__oldFocus = None
        self.__saveX = 0
        self.__saveY = 0
        self.__saveState = 0
        self.__connected = 0  # is QT->VTK connection done?

        # do special handling of some keywords:
        # stereo, rw
        
        stereo = 0
        
        if kw.has_key('stereo'):
            if kw['stereo']:
                stereo = 1
            del kw['stereo']

        rw = None

        if kw.has_key('rw'):
            rw = kw['rw']
            del kw['rw']

        # create qt-level widget
136
137
138
        # You cannot pass kw anymore, you'll a TypeError: keyword arguments are not supported
        # http://goldenspud.com/webrog/archives/2004/07/20/pyqt-platform-inconsistencies/
        apply(qt.QWidget.__init__, (self,parent,name) + args)
139
140
141
142
143
144
145
146
147
148
149
150
151
152

        if rw: # user-supplied render window
            self._RenderWindow = rw
        else:
            self._RenderWindow = vtk.vtkRenderWindow()

        if stereo: # stereo mode
            self._RenderWindow.StereoCapableWindowOn()
            self._RenderWindow.SetStereoTypeToCrystalEyes()

        self._Iren = vtk.vtkGenericRenderWindowInteractor()
        self._Iren.SetRenderWindow(self._RenderWindow)

        # do all the necessary qt setup
153
        self.setBackgroundMode(qt.Qt.NoBackground)
154
        self.setMouseTracking(1) # get all mouse events
155
        self.setFocusPolicy(qt.QWidget.ClickFocus)
156
157
158
159
160
161
162
163
164
165
        if parent == None:
            self.show()
        
        self._Timer = qt.QTimer(self, 'timer handler')
        self.connect(self._Timer, qt.SIGNAL('timeout()'),
                     self.TimerEvent)

        self._Iren.AddObserver('CreateTimerEvent', self.CreateTimer)
        self._Iren.AddObserver('DestroyTimerEvent', self.DestroyTimer)
        
166
    def __getattr__(self, attr):
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        """Makes the object behave like a
        vtkGenericRenderWindowInteractor"""
        if attr == '__vtk__':
            return lambda t=self._Iren: t
        elif hasattr(self._Iren, attr):
            return getattr(self._Iren, attr)
        elif hasattr(qt.QWidget, attr):
            return getattr(self.sipThis, attr)
        else:
            raise AttributeError, self.__class__.__name__ + \
                  " has no attribute named " + attr

    def CreateTimer(self, obj, evt):
        self._Timer.start(10)

    def DestroyTimer(self, obj, evt):
        self._Timer.stop()
        return 1

    def TimerEvent(self):
        self._Iren.TimerEvent()

189
190
191
192
193
194
195
196
    def polish(self):
        """Final initialization just before the widget is displayed."""
        size = self.size()
        self._Iren.SetSize(size.width(), size.height())
        self._RenderWindow.SetWindowInfo(str(int(self.winId())))
        self._Iren.ConfigureEvent()
        self.__connected = 1
        
Ken Martin's avatar
Ken Martin committed
197
198
    def show(self):
        qt.QWidget.show(self)
199
        self.update() # needed for initial contents display on Win32
Ken Martin's avatar
Ken Martin committed
200

201
202
203
204
205
206
    def paintEvent(self,ev):
        if self.__connected:
            self.Render()

    def resizeEvent(self,ev):
        size = self.size()
207
        self._Iren.SetSize(size.width(), size.height())
208
        self._Iren.ConfigureEvent()
209
        self.update()
210

211
212
213
214
215
216
217
218
219
220
221
222
223
224
    def _GetCtrlShift(self, ev):
        ctrl, shift = 0, 0
        if hasattr(ev, 'state'):
            if (ev.state() & 8):
                shift = 1
            if (ev.state() & 16):
                ctrl = 1
        elif self.__saveState:
            if (self.__saveState & 8):
                shift = 1
            if (self.__saveState & 16):
                ctrl = 1            
        return ctrl, shift

225
226
227
228
    def enterEvent(self,ev):
        if not self.hasFocus():
            self.__oldFocus = self.focusWidget()
            self.setFocus()
229
        ctrl, shift = self._GetCtrlShift(ev)
230
        self._Iren.SetEventInformationFlipY(self.__saveX, self.__saveY,
231
                                            ctrl, shift, chr(0), 0, None)
232
233
234
235
236
237
        self._Iren.EnterEvent()

    def leaveEvent(self,ev):
        if (self.__saveState & 0x7) == 0 and self.__oldFocus:
            self.__oldFocus.setFocus()
            self.__oldFocus = None
238
        ctrl, shift = self._GetCtrlShift(ev)
239
        self._Iren.SetEventInformationFlipY(self.__saveX, self.__saveY,
240
                                            ctrl, shift, chr(0), 0, None)
241
242
243
244
        self._Iren.LeaveEvent()

    def mousePressEvent(self,ev):
        ctrl, shift = self._GetCtrlShift(ev)
Clinton Stimpson's avatar
   
Clinton Stimpson committed
245
246
247
        repeat = 0
        if ev.type() == qt.QEvent.MouseButtonDblClick:
          repeat = 1
248
        self._Iren.SetEventInformationFlipY(ev.x(), ev.y(),
Clinton Stimpson's avatar
   
Clinton Stimpson committed
249
                                            ctrl, shift, chr(0), repeat, None)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277

        self._ActiveButton = 0
        if ev.button() == 1:
            self._Iren.LeftButtonPressEvent()
            self._ActiveButton = 'Left'
        elif ev.button() == 2:
            self._Iren.RightButtonPressEvent()
            self._ActiveButton = 'Right'
        elif ev.button() == 4:
            self._Iren.MiddleButtonPressEvent()
            self._ActiveButton = 'Middle'

    def mouseReleaseEvent(self,ev):
        ctrl, shift = self._GetCtrlShift(ev)
        self._Iren.SetEventInformationFlipY(ev.x(), ev.y(),
                                            ctrl, shift, chr(0), 0, None)
        
        if self._ActiveButton == 'Right':
            self._Iren.RightButtonReleaseEvent()
        elif self._ActiveButton == 'Left':
            self._Iren.LeftButtonReleaseEvent()
        elif self._ActiveButton == 'Middle':
            self._Iren.MiddleButtonReleaseEvent()

    def mouseMoveEvent(self,ev):
        self.__saveState = ev.state()
        self.__saveX = ev.x()
        self.__saveY = ev.y()
278
        ctrl, shift = self._GetCtrlShift(ev)
279
        self._Iren.SetEventInformationFlipY(ev.x(), ev.y(),
280
                                            ctrl, shift, chr(0), 0, None)
281
282
283
284
285
286
        self._Iren.MouseMoveEvent()

    def keyPressEvent(self,ev):
        ctrl, shift = self._GetCtrlShift(ev)
        key = chr(0)
        if ev.key() < 256:
287
            key = str(ev.text())
288
289

        self._Iren.SetEventInformationFlipY(self.__saveX, self.__saveY,
290
                                            ctrl, shift, key, 0, None)
291
292
293
294
295
296
297
298
299
300
        self._Iren.KeyPressEvent()
        self._Iren.CharEvent()
        
    def keyReleaseEvent(self,ev):
        ctrl, shift = self._GetCtrlShift(ev)
        key = chr(0)
        if ev.key() < 256:
            key = chr(ev.key())

        self._Iren.SetEventInformationFlipY(self.__saveX, self.__saveY,
301
                                            ctrl, shift, key, 0, None)
302
303
304
305
306
307
308
309
        self._Iren.KeyReleaseEvent()

    def GetRenderWindow(self):
        return self._RenderWindow

    def Render(self):
        self._RenderWindow.Render()

310
311
312
313
314
315

#-----------------------------------------------------------------------  
def QVTKRenderWidgetConeExample():    
    """A simple example that uses the QVTKRenderWindowInteractor
    class.  """
    
316
317
318
319
320
321
322
323
    # every QT app needs an app
    app = qt.QApplication(['QVTKRenderWindowInteractor'])

    # create the widget
    widget = QVTKRenderWindowInteractor()
    widget.Initialize()
    widget.Start()
    # if you dont want the 'q' key to exit comment this.
Ken Martin's avatar
Ken Martin committed
324
    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
    
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    widget.show()
    # close the application when window is closed
    app.setMainWidget(widget)
    # start event processing
    app.exec_loop()
    
if __name__ == "__main__":
    QVTKRenderWidgetConeExample()