Skip to content
Cannot retrieve contributors at this time
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import numpy as np
from ..visuals import Compound
from ...visuals.mesh import MeshVisual
from ...visuals.transforms import STTransform
from ...visuals.filters import Clipper
from ...util.event import Event
from ...geometry import Rect
from ...color import Color
class Widget(Compound):
"""A widget takes up a rectangular space, intended for use in
a 2D pixel coordinate frame.
The widget is positioned using the transform attribute (as any
node), and its extent (size) is kept as a separate property.
pos : (x, y)
A 2-element tuple to specify the top left corner of the widget.
size : (w, h)
A 2-element tuple to spicify the size of the widget.
border_color : color
The color of the border.
border_width : float
The width of the border line in pixels.
bgcolor : color
The background color.
padding : int
The amount of padding in the widget (i.e. the space reserved between
the contents and the border).
margin : int
The margin to keep outside the widget's border.
def __init__(self, pos=(0, 0), size=(10, 10), border_color=None,
border_width=1, bgcolor=None, padding=0, margin=0, **kwargs):
# For drawing border.
# A mesh is required because GL lines cannot be drawn with predictable
# shape across all platforms.
self._mesh = MeshVisual(color=border_color, mode='triangles')
self._mesh.set_gl_state('translucent', depth_test=False,
self._picking_mesh = MeshVisual(mode='triangle_fan')
self._picking_mesh.set_gl_state(cull_face=False, depth_test=False)
self._picking_mesh.visible = False
# reserved space inside border
self._padding = padding
self._border_width = border_width
# reserved space outside border
self._margin = margin
self._size = 100, 100
# layout interaction
self._width_limits = [0, None]
self._height_limits = [0, None]
self._stretch = [None, None]
# used by the constraint solver
# in Grid - these are Cassowary variables
self._var_w = self._var_h = None
self._var_x = self._var_y = None
self._widgets = []
self._border_color = Color(border_color)
self._bgcolor = Color(bgcolor)
self._face_colors = None
# Flag to allow rect setter to know if pos or size changed.
self._pos_or_size_changed = False
Compound.__init__(self, [self._mesh, self._picking_mesh], **kwargs)
self.transform = STTransform()
self.pos = pos
self.size = size
def pos(self):
return tuple(self.transform.translate[:2])
def pos(self, p):
assert isinstance(p, tuple)
assert len(p) == 2
# Handle floating point discrepancies
if abs(p[0] - self.pos[0]) < 1e-4 and \
abs(p[1] - self.pos[1]) < 1e-4:
self._pos_or_size_changed = True
self.transform.translate = p[0], p[1], 0, 0
def size(self):
"""The size (w, h) of this widget.
If the widget is a child of another widget, then its size is assigned
automatically by its parent.
return self._size
def size(self, s):
assert isinstance(s, tuple)
assert len(s) == 2
# Handle floating point discrepancies
if abs(s[0] - self._size[0]) < 1e-4 and \
abs(s[1] - self._size[1]) < 1e-4:
self._pos_or_size_changed = True
self._size = s
def width(self):
"""The actual width of this widget"""
return self._size[0]
def width_min(self):
"""The minimum width the widget can have"""
return self._width_limits[0]
def width_min(self, width_min):
"""Set the minimum height of the widget
height_min: float
the minimum height of the widget
if width_min is None:
self._width_limits[0] = 0
width_min = float(width_min)
assert(0 <= width_min)
self._width_limits[0] = width_min
def width_max(self):
"""The maximum width the widget can have"""
return self._width_limits[1]
def width_max(self, width_max):
"""Set the maximum width of the widget.
width_max: None | float
the maximum width of the widget. if None, maximum width
is unbounded
if width_max is None:
self._width_limits[1] = None
width_max = float(width_max)
assert(self.width_min <= width_max)
self._width_limits[1] = width_max
def height(self):
"""The actual height of the widget"""
return self._size[1]
def height_min(self):
"""The minimum height of the widget"""
return self._height_limits[0]
def height_min(self, height_min):
"""Set the minimum height of the widget
height_min: float
the minimum height of the widget
if height_min is None:
self._height_limits[0] = 0
height_min = float(height_min)
assert(height_min >= 0)
self._height_limits[0] = height_min
def height_max(self):
"""The maximum height of the widget"""
return self._height_limits[1]
def height_max(self, height_max):
"""Set the maximum height of the widget.
height_max: None | float
the maximum height of the widget. if None, maximum height
is unbounded
if height_max is None:
self._height_limits[1] = None
height_max = float(height_max)
assert(0 <= self.height_min <= height_max)
self._height_limits[1] = height_max
def rect(self):
return Rect((0, 0), self.size)
def rect(self, r):
self._pos_or_size_changed = False
self.pos = r.pos
self.size = r.size
if self._pos_or_size_changed:
def inner_rect(self):
"""The rectangular area inside the margin, border, and padding.
Generally widgets should avoid drawing or placing sub-widgets outside
this rectangle.
m = self.margin + self._border_width + self.padding
if not self.border_color.is_blank:
m += 1
return Rect((m, m), (self.size[0]-2*m, self.size[1]-2*m))
def stretch(self):
"""Stretch factors (w, h) used when determining how much space to
allocate to this widget in a layout.
If either stretch factor is None, then it will be assigned when the
widget is added to a layout based on the number of columns or rows it
return self._stretch
def stretch(self, s):
self._stretch = [float(s[0]), float(s[1])]
if self._stretch[0] == 0:
raise RuntimeError("received 0 as stretch parameter: %s", s)
if self._stretch[1] == 0:
raise RuntimeError("received 0 as stretch parameter: %s", s)
def _update_layout(self):
if isinstance(self.parent, Widget):
def _update_clipper(self):
"""Called whenever the clipper for this widget may need to be updated."""
if self.clip_children and self._clipper is None:
self._clipper = Clipper()
elif not self.clip_children:
self._clipper = None
if self._clipper is None:
self._clipper.rect = self.inner_rect
self._clipper.transform = self.get_transform('framebuffer', 'visual')
def border_color(self):
"""The color of the border."""
return self._border_color
def border_color(self, b):
self._border_color = Color(b)
def bgcolor(self):
"""The background color of the Widget."""
return self._bgcolor
def bgcolor(self, value):
self._bgcolor = Color(value)
def margin(self):
return self._margin
def margin(self, m):
self._margin = m
def padding(self):
return self._padding
def padding(self, p):
self._padding = p
def _update_line(self):
"""Update border line to match new shape"""
w = self._border_width
m = self.margin
# border is drawn within the boundaries of the widget:
# size = (8, 7) margin=2
# internal rect = (3, 3, 2, 1)
# ........
# ........
# ..BBBB..
# ..B B..
# ..BBBB..
# ........
# ........
left = bot = m
right = self.size[0] - m
top = self.size[1] - m
pos = np.array([
[left, bot], [left+w, bot+w],
[right, bot], [right-w, bot+w],
[right, top], [right-w, top-w],
[left, top], [left+w, top-w],
], dtype=np.float32)
faces = np.array([
[0, 2, 1],
[1, 2, 3],
[2, 4, 3],
[3, 5, 4],
[4, 5, 6],
[5, 7, 6],
[6, 0, 7],
[7, 0, 1],
[5, 3, 1],
[1, 5, 7],
], dtype=np.int32)
start = 8 if self._border_color.is_blank else 0
stop = 8 if self._bgcolor.is_blank else 10
face_colors = None
if self._face_colors is not None:
face_colors = self._face_colors[start:stop]
self._mesh.set_data(vertices=pos, faces=faces[start:stop],
# picking mesh covers the entire area
def _update_colors(self):
self._face_colors = np.concatenate(
(np.tile(self.border_color.rgba, (8, 1)),
np.tile(self.bgcolor.rgba, (2, 1)))).astype(np.float32)
def picking(self):
return self._picking
def picking(self, p):
Compound.picking.fset(self, p)
def _update_visibility(self):
blank = self.border_color.is_blank and self.bgcolor.is_blank
picking = self.picking
self._picking_mesh.visible = picking and self.interactive
self._mesh.visible = not picking and not blank
def _update_child_widgets(self):
# Set the position and size of child boxes (only those added
# using add_widget)
for ch in self._widgets:
ch.rect = self.rect.padded(self.padding + self.margin)
def add_widget(self, widget):
Add a Widget as a managed child of this Widget.
The child will be
automatically positioned and sized to fill the entire space inside
this Widget (unless _update_child_widgets is redefined).
widget : instance of Widget
The widget to add.
widget : instance of Widget
The widget.
widget.parent = self
return widget
def add_grid(self, *args, **kwargs):
Create a new Grid and add it as a child widget.
All arguments are given to Grid().
from .grid import Grid
grid = Grid(*args, **kwargs)
return self.add_widget(grid)
def add_view(self, *args, **kwargs):
Create a new ViewBox and add it as a child widget.
All arguments are given to ViewBox().
from .viewbox import ViewBox
view = ViewBox(*args, **kwargs)
return self.add_widget(view)
def remove_widget(self, widget):
Remove a Widget as a managed child of this Widget.
widget : instance of Widget
The widget to remove.
widget.parent = None