Class ConstraintLayout
GtkConstraintLayout
is a layout manager that uses relations between
widget attributes, expressed via Constraint
instances, to
measure and allocate widgets.
How do constraints work
Constraints are objects defining the relationship between attributes
of a widget; you can read the description of the Constraint
class to have a more in depth definition.
By taking multiple constraints and applying them to the children of
a widget using GtkConstraintLayout
, it's possible to describe
complex layout policies; each constraint applied to a child or to the parent
widgets contributes to the full description of the layout, in terms of
parameters for resolving the value of each attribute.
It is important to note that a layout is defined by the totality of constraints; removing a child, or a constraint, from an existing layout without changing the remaining constraints may result in an unstable or unsolvable layout.
Constraints have an implicit "reading order"; you should start describing each edge of each child, as well as their relationship with the parent container, from the top left (or top right, in RTL languages), horizontally first, and then vertically.
A constraint-based layout with too few constraints can become "unstable", that is: have more than one solution. The behavior of an unstable layout is undefined.
A constraint-based layout with conflicting constraints may be unsolvable,
and lead to an unstable layout. You can use the Gtk.Constraint:strength
property of Constraint
to "nudge" the layout towards a solution.
GtkConstraintLayout as GtkBuildable
GtkConstraintLayout
implements the Buildable
interface and
has a custom "constraints" element which allows describing constraints in
a GtkBuilder
UI file.
An example of a UI definition fragment specifying a constraint:
<object class="GtkConstraintLayout">
<constraints>
<constraint target="button" target-attribute="start"
relation="eq"
source="super" source-attribute="start"
constant="12"
strength="required" />
<constraint target="button" target-attribute="width"
relation="ge"
constant="250"
strength="strong" />
</constraints>
</object>
The definition above will add two constraints to the GtkConstraintLayout:
- a required constraint between the leading edge of "button" and the leading edge of the widget using the constraint layout, plus 12 pixels
- a strong, constant constraint making the width of "button" greater than, or equal to 250 pixels
The "target" and "target-attribute" attributes are required.
The "source" and "source-attribute" attributes of the "constraint" element are optional; if they are not specified, the constraint is assumed to be a constant.
The "relation" attribute is optional; if not specified, the constraint is assumed to be an equality.
The "strength" attribute is optional; if not specified, the constraint is assumed to be required.
The "source" and "target" attributes can be set to "super" to indicate that the constraint target is the widget using the GtkConstraintLayout.
There can be "constant" and "multiplier" attributes.
Additionally, the "constraints" element can also contain a description
of the GtkConstraintGuides
used by the layout:
<constraints>
<guide min-width="100" max-width="500" name="hspace"/>
<guide min-height="64" nat-height="128" name="vspace" strength="strong"/>
</constraints>
The "guide" element has the following optional attributes:
- "min-width", "nat-width", and "max-width", describe the minimum, natural, and maximum width of the guide, respectively
- "min-height", "nat-height", and "max-height", describe the minimum, natural, and maximum height of the guide, respectively
- "strength" describes the strength of the constraint on the natural size of the guide; if not specified, the constraint is assumed to have a medium strength
- "name" describes a name for the guide, useful when debugging
Using the Visual Format Language
Complex constraints can be described using a compact syntax called VFL,
or *Visual Format Language*.
The Visual Format Language describes all the constraints on a row or
column, typically starting from the leading edge towards the trailing
one. Each element of the layout is composed by "views", which identify
a ConstraintTarget
.
For instance:
[button]-[textField]
Describes a constraint that binds the trailing edge of "button" to the leading edge of "textField", leaving a default space between the two.
Using VFL is also possible to specify predicates that describe constraints on attributes like width and height:
// Width must be greater than, or equal to 50
[button(>=50)]
// Width of button1 must be equal to width of button2
[button1(==button2)]
The default orientation for a VFL description is horizontal, unless otherwise specified:
// horizontal orientation, default attribute: width
H:[button(>=150)]
// vertical orientation, default attribute: height
V:[button1(==button2)]
It's also possible to specify multiple predicates, as well as their strength:
// minimum width of button must be 150
// natural width of button can be 250
[button(>=150@required, ==250@medium)]
Finally, it's also possible to use simple arithmetic operators:
// width of button1 must be equal to width of button2
// divided by 2 plus 12
[button1(button2 / 2 + 12)]
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
ConstraintLayout.Builder<B extends ConstraintLayout.Builder<B>>
Inner class implementing a builder pattern to construct a GObject with properties.static class
Nested classes/interfaces inherited from class org.gnome.gtk.LayoutManager
LayoutManager.LayoutManagerClass, LayoutManager.LayoutManagerImpl
Nested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClass
Nested classes/interfaces inherited from interface org.gnome.gtk.Buildable
Buildable.BuildableIface, Buildable.BuildableImpl
-
Constructor Summary
ConstructorDescriptionCreates a newGtkConstraintLayout
layout manager.ConstraintLayout
(MemorySegment address) Create a ConstraintLayout proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionvoid
addConstraint
(Constraint constraint) Adds a constraint to the layout manager.addConstraintsFromDescription
(String[] lines, int hspacing, int vspacing, HashTable<String, ConstraintTarget> views) Creates a list of constraints from a VFL description.void
addGuide
(ConstraintGuide guide) Adds a guide tolayout
.protected ConstraintLayout
asParent()
Returns this instance as if it were its parent type.static ConstraintLayout.Builder
<? extends ConstraintLayout.Builder> builder()
AConstraintLayout.Builder
object constructs aConstraintLayout
with the specified properties.static Type
getType()
Get the GType of the ConstraintLayout classReturns aGListModel
to track the constraints that are part of the layout.Returns aGListModel
to track the guides that are part of the layout.void
Removes all constraints from the layout manager.void
removeConstraint
(Constraint constraint) Removesconstraint
from the layout manager, so that it no longer influences the layout.void
removeGuide
(ConstraintGuide guide) Removesguide
from the layout manager, so that it no longer influences the layout.Methods inherited from class org.gnome.gtk.LayoutManager
allocate, createLayoutChild, getLayoutChild, getMemoryLayout, getRequestMode, getRequestMode, getWidget, layoutChanged, measure, root, unroot
Methods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newInstance, newInstance, newv, notify_, notify_, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withProperties
Methods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, getPrivate, readGClass, writeGClass
Methods inherited from class io.github.jwharm.javagi.base.ProxyInstance
equals, handle, hashCode
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.gnome.gtk.Buildable
getBuildableId
-
Constructor Details
-
ConstraintLayout
Create a ConstraintLayout proxy instance for the provided memory address.- Parameters:
address
- the memory address of the native object
-
ConstraintLayout
public ConstraintLayout()Creates a newGtkConstraintLayout
layout manager.
-
-
Method Details
-
getType
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuper
keyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()
doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName()
. This will call the native function pointer of this virtual method in the typeclass of the parent type.- Overrides:
asParent
in classLayoutManager
-
addConstraint
Adds a constraint to the layout manager.The
Gtk.Constraint:source
andGtk.Constraint:target
properties ofconstraint
can be:- set to
NULL
to indicate that the constraint refers to the widget usinglayout
- set to the
Widget
usinglayout
- set to a child of the
Widget
usinglayout
- set to a
ConstraintGuide
that is part oflayout
The this ConstraintLayout acquires the ownership of
constraint
after calling this function.- Parameters:
constraint
- aConstraint
- set to
-
addConstraintsFromDescription
public List<Constraint> addConstraintsFromDescription(String[] lines, int hspacing, int vspacing, HashTable<String, ConstraintTarget> views) throws GErrorExceptionCreates a list of constraints from a VFL description.The Visual Format Language, VFL, is based on Apple's AutoLayout VFL.
The
views
dictionary is used to matchConstraintTarget
instances to the symbolic view name inside the VFL.The VFL grammar is:
<visualFormatString> = (<orientation>)? (<superview><connection>)? <view>(<connection><view>)* (<connection><superview>)? <orientation> = 'H' | 'V' <superview> = '|' <connection> = '' | '-' <predicateList> '-' | '-' <predicateList> = <simplePredicate> | <predicateListWithParens> <simplePredicate> = <metricName> | <positiveNumber> <predicateListWithParens> = '(' <predicate> (',' <predicate>)* ')' <predicate> = (<relation>)? <objectOfPredicate> (<operatorList>)? ('@' <priority>)? <relation> = '==' | '<=' | '>=' <objectOfPredicate> = <constant> | <viewName> | ('.' <attributeName>)? <priority> = <positiveNumber> | 'required' | 'strong' | 'medium' | 'weak' <constant> = <number> <operatorList> = (<multiplyOperator>)? (<addOperator>)? <multiplyOperator> = [ '*' | '/' ] <positiveNumber> <addOperator> = [ '+' | '-' ] <positiveNumber> <viewName> = [A-Za-z_]([A-Za-z0-9_]*) // A C identifier <metricName> = [A-Za-z_]([A-Za-z0-9_]*) // A C identifier <attributeName> = 'top' | 'bottom' | 'left' | 'right' | 'width' | 'height' | 'start' | 'end' | 'centerX' | 'centerY' | 'baseline' <positiveNumber> // A positive real number parseable by g_ascii_strtod() <number> // A real number parseable by g_ascii_strtod()
**Note**: The VFL grammar used by GTK is slightly different than the one defined by Apple, as it can use symbolic values for the constraint's strength instead of numeric values; additionally, GTK allows adding simple arithmetic operations inside predicates.
Examples of VFL descriptions are:
// Default spacing [button]-[textField] // Width constraint [button(>=50)] // Connection to super view |-50-[purpleBox]-50-| // Vertical layout V:[topField]-10-[bottomField] // Flush views [maroonView][blueView] // Priority [button(100@strong)] // Equal widths [button1(==button2)] // Multiple predicates [flexibleButton(>=70,<=100)] // A complete line of layout |-[find]-[findNext]-[findField(>=20)]-| // Operators [button1(button2 / 3 + 50)] // Named attributes [button1(==button2.height)]
- Parameters:
lines
- an array of Visual Format Language lines defining a set of constraintshspacing
- default horizontal spacing value, or -1 for the fallback valuevspacing
- default vertical spacing value, or -1 for the fallback valueviews
- a dictionary of[ name, target ]
pairs; thename
keys map to the view names in the VFL lines, while thetarget
values map to children of the widget using aGtkConstraintLayout
, or guides- Returns:
- the list of
Constraint
instances that were added to the layout - Throws:
GErrorException
- seeGError
-
addGuide
Adds a guide tolayout
.A guide can be used as the source or target of constraints, like a widget, but it is not visible.
The
layout
acquires the ownership ofguide
after calling this function.- Parameters:
guide
- aConstraintGuide
object
-
observeConstraints
Returns aGListModel
to track the constraints that are part of the layout.Calling this function will enable extra internal bookkeeping to track constraints and emit signals on the returned listmodel. It may slow down operations a lot.
Applications should try hard to avoid calling this function because of the slowdowns.
- Returns:
- a
GListModel
tracking the layout's constraints
-
observeGuides
Returns aGListModel
to track the guides that are part of the layout.Calling this function will enable extra internal bookkeeping to track guides and emit signals on the returned listmodel. It may slow down operations a lot.
Applications should try hard to avoid calling this function because of the slowdowns.
- Returns:
- a
GListModel
tracking the layout's guides
-
removeAllConstraints
public void removeAllConstraints()Removes all constraints from the layout manager. -
removeConstraint
Removesconstraint
from the layout manager, so that it no longer influences the layout.- Parameters:
constraint
- aConstraint
-
removeGuide
Removesguide
from the layout manager, so that it no longer influences the layout.- Parameters:
guide
- aConstraintGuide
object
-
builder
AConstraintLayout.Builder
object constructs aConstraintLayout
with the specified properties. Use the variousset...()
methods to set properties, and finish construction withConstraintLayout.Builder.build()
.
-