51. gui.viewport — Interactive OpenGL Canvas embedded in a Qt widget.

This module implements user interaction with the OpenGL canvas defined in module canvas. QtCanvas is a single interactive OpenGL canvas, while MultiCanvas implements a dynamic array of multiple canvases.

51.1. Classes defined in module gui.viewport

class gui.viewport.CursorShapeHandler(widget)[source]

A class for handling the mouse cursor shape on the Canvas.

setCursorShape(shape)[source]

Set the cursor shape to shape

setCursorShapeFromFunc(func)[source]

Set the cursor shape to shape

class gui.viewport.CanvasMouseHandler[source]

A class for handling the mouse events on the Canvas.

getMouseFunc()[source]

Return the mouse function bound to self.button and self.mod

class gui.viewport.QtCanvas(*args, **kargs)[source]

A canvas for OpenGL rendering.

This class provides interactive functionality for the OpenGL canvas provided by the canvas.Canvas class.

Interactivity is highly dependent on Qt. Putting the interactive functions in a separate class makes it esier to use the Canvas class in non-interactive situations or combining it with other GUI toolsets.

The QtCanvas constructor may have positional and keyword arguments. The positional arguments are passed to the QtOpenGL.QGLWidget constructor, while the keyword arguments are passed to the canvas.Canvas constructor.

getSize()[source]

Return the size of this canvas

saneSize(width=-1, height=-1)[source]

Return a cleverly resized canvas size.

Computes a new size for the canvas, while trying to keep its current aspect ratio. Specified positive values are returned unchanged.

Parameters:
  • width (int) – Requested width of the canvas. If <=0, it is automatically computed from height and canvas aspect ratio, or set equal to canvas width.
  • height (int) – Requested height of the canvas. If <=0, it is automatically computed from width and canvas aspect ratio, or set equal to canvas height.
Returns:

  • width (int) – Adjusted canvas width.
  • height (int) – Adjusted canvas height.

changeSize(width, height)[source]

Resize the canvas to (width x height).

If a negative value is given for either width or height, the corresponding size is set equal to the maximum visible size (the size of the central widget of the main window).

Note that this may not have the expected result when multiple viewports are used.

image(w=-1, h=-1, remove_alpha=True)[source]

Return the current OpenGL rendering in an image format.

Parameters:
  • w (int) – Requested width of the image (in pixels). If <=0, automatically computed from height and canvas aspect ratio, or set equal to canvas width.
  • h (int) – Requested height of the image (in pixels). If <=0, automatically computed from width and canvas aspect ratio, or set equal to canvas height.
  • remove_alpha (bool) – If True (default), the alpha channel is removed from the image.
Returns:

qim (QImage) – The current OpenGL rendering as a QImage of the specified size.

Notes

The returned image can be written directly to an image file with qim.save(filename).

See also

rgb()
returns the canvas rendering as a numpy ndarray
rgb(w=-1, h=-1, remove_alpha=True)[source]

Return the current OpenGL rendering in an array format.

Parameters:
  • w (int) – Requested width of the image (in pixels). If <=0, automatically computed from height and canvas aspect ratio, or set equal to canvas width.
  • h (int) – Requested height of the image (in pixels). If <=0, automatically computed from width and canvas aspect ratio, or set equal to canvas height.
  • remove_alpha (bool) – If True (default), the alpha channel is removed from the image.
Returns:

ar (array) – The current OpenGL rendering as a numpy array of type uint. Its shape is (w,h,3) if remove_alpha is True (default) or (w,h,4) if remove_alpha is False.

See also

image()
return the current rendering as an image
outline(size=(0, 0), profile='luminance', level=0.5, bgcolor=None, nproc=None)[source]

Return the outline of the current rendering

Parameters:

  • size: a tuple of ints (w,h) specifying the size of the image to be used in outline detection. A non-positive value will be set automatically from the current canvas size or aspect ratio.
  • profile: the function used to translate pixel colors into a single value. The default is to use the luminance of the pixel color.
  • level: isolevel at which to construct the outline.
  • bgcolor: a color that is to be interpreted as background color and will get a pixel value -0.5.
  • nproc: number of processors to be used in the image processing. Default is to use as many as available.

Returns the outline as a Formex of plexitude 2.

Note:

  • ‘luminance’ is currently the only profile implemented.
  • bgcolor is currently experimental.
setCursorShape(shape)[source]

Set the cursor shape to shape

setCursorShapeFromFunc(func)[source]

Set the cursor shape to shape

getMouseFunc()[source]

Return the mouse function bound to self.button and self.mod

mouse_rectangle(x, y, action)[source]

Process mouse events during interactive rectangle zooming.

On PRESS, record the mouse position. On MOVE, create a rectangular zoom window. On RELEASE, zoom to the picked rectangle.

start_selection(mode, filter, pickable=None)[source]

Start an interactive picking mode.

If selection mode was already started, mode is disregarded and this can be used to change the filter method.

wait_selection()[source]

Wait for the user to interactively make a selection.

finish_selection()[source]

End an interactive picking mode.

accept_selection(clear=False)[source]

Accept or cancel an interactive picking mode.

If clear == True, the current selection is cleared.

cancel_selection()[source]

Cancel an interactive picking mode and clear the selection.

pick(mode='actor', oneshot=False, func=None, filter=None, pickable=None, _rect=None)[source]

Interactively pick objects from the viewport.

  • mode: defines what to pick : one of ['actor','element','point','number','edge']

  • oneshot: if True, the function returns as soon as the user ends a picking operation. The default is to let the user modify his selection and only to return after an explicit cancel (ESC or right mouse button).

  • func: if specified, this function will be called after each atomic pick operation. The Collection with the currently selected objects is passed as an argument. This can e.g. be used to highlight the selected objects during picking.

  • filter: defines what elements to retain from the selection: one of [None,'single','closest,'connected'].

    • None (default) will return the complete selection.

    • ‘closest’ will only keep the element closest to the user.

    • ‘connected’ will only keep elements connected to

      • the closest element (set picked)
      • what is already in the selection (add picked).

      Currently this only works when picking mode is ‘element’ and for Actors having a partitionByConnection method.

Returns a (possibly empty) Collection with the picked items. After return, the value of the pf.canvas.selection_accepted variable can be tested to find how the picking operation was exited: True means accepted (right mouse click, ENTER key, or OK button), False means canceled (ESC key, or Cancel button). In the latter case, the returned Collection is always empty.

pickNumbers(*args, **kargs)[source]

Go into number picking mode and return the selection.

mouse_rect_pick_events(rect=None)[source]

Create the events for a mouse rectangle pick.

Parameters:rect (tuple of ints, optional) – A tuple (x0,y0,x1,y1) specifying the top left corner and the bottom right corner of the rectangular are to be picked. Values are in pixels relative to the canvas widget. If not provided, the whole canvas area will be picked.
Returns:list – A nested list of events. The list contains two sublists. The first holds the events to make the rectangle pick:
  • Press the left button mouse at (x0,y0).
  • Move the mouse while holding the left button pressed to (x1,y1).
  • Release the left mouse button at (x1,y1).

The second sublist holds the events to accept the picked area:

  • Press the right mouse button at (x1,y1).
  • Release the right mouse button at (x1,y1).
idraw(mode='point', npoints=-1, zplane=0.0, func=None, coords=None, preview=False)[source]

Interactively draw on the canvas.

This function allows the user to interactively create points in 3D space and collects the subsequent points in a Coords object. The interpretation of these points is left to the caller.

  • mode: one of the drawing modes, specifying the kind of objects you want to draw. This is passed to the specified func.
  • npoints: If -1, the user can create any number of points. When >=0, the function will return when the total number of points in the collection reaches the specified value.
  • zplane: the depth of the z-plane on which the 2D drawing is done.
  • func: a function that is called after each atomic drawing operation. It is typically used to draw a preview using the current set of points. The function is passed the current Coords and the mode as arguments.
  • coords: an initial set of coordinates to which the newly created points should be added. If specified, npoints also counts these initial points.
  • preview: Experimental If True, the preview funcion will also be called during mouse movement with a pressed button, allowing to preview the result before a point is created.

The drawing operation is finished when the number of requested points has been reached, or when the user clicks the right mouse button or hits ‘ENTER’. The return value is a (n,3) shaped Coords array. To know in which way the drawing was finished check pf.canvas.draw_accepted: True means mouse right click / ENTER, False means ESC button on keyboard.

start_draw(mode, zplane, coords)[source]

Start an interactive drawing mode.

finish_draw()[source]

End an interactive drawing mode.

accept_draw(clear=False)[source]

Cancel an interactive drawing mode.

If clear == True, the current drawing is cleared.

cancel_draw()[source]

Cancel an interactive drawing mode and clear the drawing.

mouse_draw(x, y, action)[source]

Process mouse events during interactive drawing.

On PRESS, do nothing. On MOVE, do nothing. On RELEASE, add the point to the point list.

drawLinesInter(mode='line', oneshot=False, func=None)[source]

Interactively draw lines on the canvas.

  • oneshot: if True, the function returns as soon as the user ends a drawing operation. The default is to let the user draw multiple lines and only to return after an explicit cancel (ESC or right mouse button).
  • func: if specified, this function will be called after each atomic drawing operation. The current drawing is passed as an argument. This can e.g. be used to show the drawing.

When the drawing operation is finished, the drawing is returned. The return value is a (n,2,2) shaped array.

start_drawing(mode)[source]

Start an interactive line drawing mode.

wait_drawing()[source]

Wait for the user to interactively draw a line.

finish_drawing()[source]

End an interactive drawing mode.

accept_drawing(clear=False)[source]

Cancel an interactive drawing mode.

If clear == True, the current drawing is cleared.

cancel_drawing()[source]

Cancel an interactive drawing mode and clear the drawing.

edit_drawing(mode)[source]

Edit an interactive drawing.

dynarot(x, y, action)[source]

Perform dynamic rotation operation.

This function processes mouse button events controlling a dynamic rotation operation. The action is one of PRESS, MOVE or RELEASE.

dynapan(x, y, action)[source]

Perform dynamic pan operation.

This function processes mouse button events controlling a dynamic pan operation. The action is one of PRESS, MOVE or RELEASE.

dynazoom(x, y, action)[source]

Perform dynamic zoom operation.

This function processes mouse button events controlling a dynamic zoom operation. The action is one of PRESS, MOVE or RELEASE.

wheel_zoom(delta)[source]

Zoom by rotating a wheel over an angle delta

emit_done(x, y, action)[source]

Emit a DONE event by clicking the mouse.

This is equivalent to pressing the ENTER button.

emit_cancel(x, y, action)[source]

Emit a CANCEL event by clicking the mouse.

This is equivalent to pressing the ESC button.

draw_state_rect(x, y)[source]

Store the pos and draw a rectangle to it.

mouse_pick(x, y, action)[source]

Process mouse events during interactive picking.

On PRESS, record the mouse position. On MOVE, create a rectangular picking window. On RELEASE, pick the objects inside the rectangle.

draw_state_line(x, y)[source]

Store the pos and draw a line to it.

mouse_draw_line(x, y, action)[source]

Process mouse events during interactive drawing.

On PRESS, record the mouse position. On MOVE, draw a line. On RELEASE, add the line to the drawing.

mousePressEvent(e)[source]

Process a mouse press event.

mouseMoveEvent(e)[source]

Process a mouse move event.

mouseReleaseEvent(e)[source]

Process a mouse release event.

wheelEvent(e)[source]

Process a wheel event.

class gui.viewport.MultiCanvas(parent=None)[source]

An OpenGL canvas with multiple viewports and QT interaction.

The MultiCanvas implements a central QT widget containing one or more QtCanvas widgets.

changeLayout(nvps=None, ncols=None, nrows=None, pos=None, rstretch=None, cstretch=None)[source]

Change the lay-out of the viewports on the OpenGL widget.

nvps: number of viewports ncols: number of columns nrows: number of rows pos: list holding the position and span of each viewport [[row,col,rowspan,colspan],…] rstretch: list holding the stretch factor for each row cstretch: list holding the stretch factor for each column (rows/columns with a higher stretch factor take more of the available space) Each of this parameters is optional.

If a number of viewports is given, viewports will be added or removed to match the requested number. By default they are laid out rowwise over two columns.

If ncols is an int, viewports are laid out rowwise over ncols columns and nrows is ignored. If ncols is None and nrows is an int, viewports are laid out columnwise over nrows rows. Alternatively, the pos argument can be used to specify the layout of the viewports.

newView(shared=True, settings=None)[source]

Create a new viewport.

If shared is True, and the MultiCanvas already has one or more viewports, the new viewport will share display lists and textures with the first viewport. Since pyFormex is not using display lists (anymore) and textures are needed to display text, the value defaults to True, and all viewports will share the same textures, unless a viewport is created with a specified value for shared: it can either be another viewport to share textures with, or a value False or None to not share textures with any viewport. In the latter case you will not be able to use text display, unless you initialize the textures yourself.

settings: can be a legal CanvasSettings to initialize the viewport. Default is to copy settings of the current viewport.

Returns the created viewport, which is an instance of QtCanvas.

addView()[source]

Add a new viewport to the widget

setCurrent(canv)[source]

Make the specified viewport the current one.

canv can be either a viewport or viewport number.

viewIndex(view)[source]

Return the index of the specified view

currentView()[source]

Return the index of the current view

showWidget(w)[source]

Show the view w.

removeView()[source]

Remove the last view

Link viewport vp to to

config()[source]

Return the full configuration needed to restore this MultiCanvas.

Currently only works on single viewport.

save(filename)[source]

Save the canvas settings to file

Currently only works on single viewport.

loadConfig(config)[source]

Reset the viewports size, layout and cameras from a Config dict

load(filename)[source]

Load the canvas settings from file

51.2. Functions defined in module gui.viewport

gui.viewport.dotpr(v, w)[source]

Return the dot product of vectors v and w

gui.viewport.length(v)[source]

Return the length of the vector v

gui.viewport.projection(v, w)[source]

Return the (signed) length of the projection of vector v on vector w.

gui.viewport.setOpenGLFormat()[source]

Set the correct OpenGL format.

On a correctly installed system, the default should do well. The default OpenGL format can be changed by command line options:

--dri   : use the Direct Rendering Infrastructure, if available
--nodri : do not use the DRI
--opengl : set the opengl version
--(no)multisample
gui.viewport.OpenGLFormat(fmt=None)[source]

Report information about the OpenGL format.

gui.viewport.OpenGLSupportedVersions(flags)[source]

Return the supported OpenGL version.

flags is the return value of QGLFormat.OpenGLVersionFlag()

Returns a list with tuple (k,v) where k is a string describing an Opengl version and v is True or False.

gui.viewport.OpenGLVersions(fmt=None)[source]

Report information about the supported OpenGL versions.

gui.viewport.drawDot(x, y)[source]

Draw a dot at canvas coordinates (x,y).

gui.viewport.drawLine(x1, y1, x2, y2)[source]

Draw a straight line from (x1,y1) to (x2,y2) in canvas coordinates.

gui.viewport.drawGrid(x1, y1, x2, y2, nx, ny)[source]

Draw a rectangular grid of lines

The rectangle has (x1,y1) and and (x2,y2) as opposite corners. There are (nx,ny) subdivisions along the (x,y)-axis. So the grid has (nx+1) * (ny+1) lines. nx=ny=1 draws a rectangle. nx=0 draws 1 vertical line (at x1). nx=-1 draws no vertical lines. ny=0 draws 1 horizontal line (at y1). ny=-1 draws no horizontal lines.

gui.viewport.drawRect(x1, y1, x2, y2)[source]

Draw the circumference of a rectangle.