Spatial
SpatialView
Give existing widgets perspective and pointer tilt. Keep text editing and popups in the normal layout; native-window and OpenGL children cannot be embedded.
Example

Usage
Scene perspective
Adjust the camera and zoom, then move the pointer over the cards.
#include <FluentQt/Spatial.h>
using namespace fluent::spatial;
using namespace fluent;
// The two cards keep their own poses while the view changes the whole scene.
class SceneView final : public spatial::SpatialView {
public:
using SpatialView::SpatialView;
void arrange()
{
if (itemCount() != 2)
return;
const float spread = width() < 650 ? 24 : 100;
items().first()->setPosition(QVector3D(-spread, -44, -160));
items().last()->setPosition(QVector3D(spread, 44, 160));
}
protected:
void resizeEvent(QResizeEvent* event) override
{
SpatialView::resizeEvent(event);
arrange();
}
};
auto* panel = new SpatialPreviewPanel(parent);
auto* column = new QVBoxLayout(panel);
column->setContentsMargins(0, 0, 0, 0);
column->setSpacing(16);
auto* session = new spatial::SpatialSession(panel, panel);
const bool active = session->activate();
auto* view = new SceneView(panel);
if (!active || !session->attachView(view)) {
view->setSpatialEnabled(false);
view->setRenderMode(spatial::SpatialView::RenderMode::Raster);
}
view->setObjectName("spatialPreviewView");
view->setFixedHeight(400);
view->setCameraDistance(1200);
view->setZoom(0.9);
view->setMaximumTilt(QPointF(6, 12));
// Response time (140 ms), animation limit (60 fps), cache and Auto renderer use UILib defaults.
// See SpatialView.h for the full parameter contract.
// Both layers use the same size and data, making perspective easy to compare.
const auto makeLayer = [](const QString& title, const QString& caption) {
auto* card = new layout::Card;
card->setFixedSize(220, 150);
auto* content = new QVBoxLayout(card);
content->setContentsMargins(16, 12, 16, 12);
content->setSpacing(6);
auto* heading = new textfields::Label(title, card);
heading->setFluentTypography(Typography::FontRole::Subtitle);
heading->setTextColorRole(textfields::Label::TextColorRole::Primary);
content->addWidget(heading);
auto* chart = new charts::Sparkline(card);
chart->setAccessibleName(title + " sample chart");
auto* model = new charts::ChartModel(card);
model->setPoints({{0, 12}, {1, 24}, {2, 18}, {3, 38}, {4, 32}, {5, 54}});
chart->setModel(model);
content->addWidget(chart, 1);
auto* note = new textfields::Label(caption, card);
note->setTextColorRole(textfields::Label::TextColorRole::Secondary);
content->addWidget(note);
return card;
};
spatial::SpatialItem* back = view->addWidget(
makeLayer("Back layer", "Z -160 · sample data"), WidgetOwnership::Owned);
spatial::SpatialItem* front = view->addWidget(
makeLayer("Front layer", "Z +160 · sample data"), WidgetOwnership::Owned);
back->setRotation(QVector3D(6, 16, 0));
front->setRotation(QVector3D(-6, -16, 0));
back->setSurfaceIntensity(0.75);
front->setSurfaceIntensity(0.75);
view->arrange();
auto* toolbar = new QHBoxLayout;
auto* follow = new basicinput::ToggleSwitch(panel);
follow->setObjectName("spatialViewFollow");
follow->setAccessibleName("Follow pointer");
follow->setOnContent("Follow pointer");
follow->setOffContent("Follow pointer");
follow->setIsOn(true);
toolbar->addWidget(follow);
toolbar->addStretch();
column->addLayout(toolbar);
column->addWidget(view);
// Keep view-wide controls outside the projection so their drag targets stay still.
auto* controls = new QWidget(panel);
controls->setObjectName("spatialViewControls");
auto* grid = new QGridLayout(controls);
grid->setContentsMargins(0, 0, 0, 0);
grid->setHorizontalSpacing(24);
grid->setVerticalSpacing(12);
grid->setColumnStretch(0, 1);
grid->setColumnStretch(1, 1);
const auto addSlider = [controls, grid](const QString& name, const QString& label,
const QString& unit, int minimum, int maximum,
int initial, int row, int col) {
auto* group = new QWidget(controls);
auto* layout = new QVBoxLayout(group);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(4);
auto* text = new textfields::Label(group);
text->setTextColorRole(textfields::Label::TextColorRole::Primary);
auto* slider = new basicinput::Slider(group);
slider->setObjectName(name);
slider->setAccessibleName(label);
slider->setRange(minimum, maximum);
slider->setValue(initial);
const auto updateText = [text, label, unit](int value) {
text->setText(QString("%1: %2%3").arg(label).arg(value).arg(unit));
};
updateText(initial);
QObject::connect(slider, &basicinput::Slider::valueChanged, text, updateText);
layout->addWidget(text);
layout->addWidget(slider);
grid->addWidget(group, row, col);
return slider;
};
auto* distance = addSlider("spatialViewDistance", "Camera distance", " px",
650, 2400, 1200, 0, 0);
auto* zoom = addSlider("spatialViewZoom", "Scene zoom", "%", 50, 110, 90, 0, 1);
QObject::connect(distance, &basicinput::Slider::valueChanged, view,
[view](int value) { view->setCameraDistance(value); });
QObject::connect(zoom, &basicinput::Slider::valueChanged, view,
[view](int value) { view->setZoom(value / 100.0); });
column->addWidget(controls);
QObject::connect(follow, &basicinput::ToggleSwitch::toggled,
view, &spatial::SpatialView::setPointerTrackingEnabled);
QObject::connect(view, &spatial::SpatialView::pointerTrackingEnabledChanged,
follow, &basicinput::ToggleSwitch::setIsOn);
const auto updateAvailability = [view, controls, follow] {
controls->setEnabled(view->isSpatialEnabled());
follow->setEnabled(view->isSpatialEnabled());
};
QObject::connect(view, &spatial::SpatialView::spatialEnabledChanged, controls, updateAvailability);
updateAvailability();import fluentqt
from PySide6.QtCore import QEvent, QPointF
from PySide6.QtGui import QVector3D
from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QVBoxLayout, QWidget
from fluentqt.spatial import SpatialSession, SpatialView
class SpatialPreviewPanel(QWidget):
def stop_spatial(self):
session = self.findChild(SpatialSession)
if session is not None:
session.deactivate()
def event(self, event):
# Stop before deleteLater dismantles this panel's widgets.
# Also call stop_spatial before disposing an enclosing window.
if event.type() == QEvent.DeferredDelete:
self.stop_spatial()
return super().event(event)
class SceneView(SpatialView):
def arrange(self):
if self.itemCount() == 2:
spread = 24 if self.width() < 650 else 100
self.items()[0].setPosition(QVector3D(-spread, -44, -160))
self.items()[-1].setPosition(QVector3D(spread, 44, 160))
def resizeEvent(self, event):
super().resizeEvent(event)
self.arrange()
panel = SpatialPreviewPanel()
column = QVBoxLayout(panel)
column.setContentsMargins(0, 0, 0, 0)
column.setSpacing(12)
session = SpatialSession(panel, panel)
spatial_attached = session.activate()
view = SceneView(panel)
spatial_attached = spatial_attached and session.attachView(view)
if not spatial_attached:
view.setRenderMode(SpatialView.RenderMode.Raster)
view.setSpatialEnabled(False)
view.setObjectName("spatialPreviewView")
view.setFixedHeight(400)
view.setCameraDistance(1200)
view.setMaximumTilt(QPointF(4, 6))
column.addWidget(view)
def add_slider(parent, layout, name, label, unit, minimum, maximum, initial):
in_grid = isinstance(layout, QGridLayout)
group = QWidget(parent) if in_grid else parent
column = QVBoxLayout(group) if in_grid else QVBoxLayout()
column.setContentsMargins(0, 0, 0, 0)
column.setSpacing(4)
text = fluentqt.Label(f"{label}: {initial}{unit}", group)
slider = fluentqt.Slider(group)
slider.setObjectName(name)
slider.setAccessibleName(label)
slider.setRange(minimum, maximum)
slider.setValue(initial)
slider.valueChanged.connect(
lambda value: text.setText(f"{label}: {value}{unit}")
)
column.addWidget(text)
column.addWidget(slider)
if isinstance(layout, QGridLayout):
layout.addWidget(group, 0, layout.count())
else:
layout.addLayout(column)
return slider
column.setSpacing(16)
view.setZoom(0.9)
view.setMaximumTilt(QPointF(6, 12))
def make_layer(title, caption):
card = fluentqt.Card()
card.setFixedSize(220, 150)
content = QVBoxLayout(card)
content.setContentsMargins(16, 12, 16, 12)
content.setSpacing(6)
heading = fluentqt.Label(title, card)
heading.setFluentTypography(fluentqt.FontRole.Subtitle)
content.addWidget(heading)
chart = fluentqt.Sparkline(card)
chart.setAccessibleName(title + " sample chart")
model = fluentqt.ChartModel(card)
model.setPoints([QPointF(x, y) for x, y in enumerate([12, 24, 18, 38, 32, 54])])
chart.setModel(model)
content.addWidget(chart, 1)
note = fluentqt.Label(caption, card)
note.setTextColorRole(fluentqt.Label.TextColorRole.Secondary)
content.addWidget(note)
card._model = model
return card
back = view.addOwnedWidget(make_layer("Back layer", "Z -160 · sample data"))
front = view.addOwnedWidget(make_layer("Front layer", "Z +160 · sample data"))
back.setRotation(QVector3D(6, 16, 0))
front.setRotation(QVector3D(-6, -16, 0))
back.setSurfaceIntensity(0.75)
front.setSurfaceIntensity(0.75)
view.arrange()
toolbar = QHBoxLayout()
follow = fluentqt.ToggleSwitch(panel)
follow.setObjectName("spatialViewFollow")
follow.setAccessibleName("Follow pointer")
follow.setOnContent("Follow pointer")
follow.setOffContent("Follow pointer")
follow.setIsOn(True)
toolbar.addWidget(follow)
toolbar.addStretch()
column.removeWidget(view)
column.addLayout(toolbar)
column.addWidget(view)
controls = QWidget(panel)
controls.setObjectName("spatialViewControls")
sliders = QGridLayout(controls)
sliders.setContentsMargins(0, 0, 0, 0)
sliders.setHorizontalSpacing(24)
sliders.setVerticalSpacing(12)
sliders.setColumnStretch(0, 1)
sliders.setColumnStretch(1, 1)
distance = add_slider(
controls,
sliders,
"spatialViewDistance",
"Camera distance",
" px",
650,
2400,
1200
)
zoom = add_slider(
controls,
sliders,
"spatialViewZoom",
"Scene zoom",
"%",
50,
110,
90
)
distance.valueChanged.connect(view.setCameraDistance)
zoom.valueChanged.connect(lambda value: view.setZoom(value / 100.0))
column.addWidget(controls)
follow.toggled.connect(view.setPointerTrackingEnabled)
view.pointerTrackingEnabledChanged.connect(follow.setIsOn)
def update_availability():
controls.setEnabled(view.isSpatialEnabled())
follow.setEnabled(view.isSpatialEnabled())
view.spatialEnabledChanged.connect(update_availability)
update_availability()API
DeclarationNo matching API members.
fluent::spatial::SpatialView
Inherits QWidget · FluentElement · QMLPlus
OpenGL-backed host for a small number of perspective-transformed live widgets.
Constructors
Properties
bool spatialEnabledEnables perspective; default true when motion/theme policy permits it. False restores the same widgets in a native vertical layout with their state intact.
ReadisSpatialEnabled()WritesetSpatialEnabled()NotifyspatialEnabledChanged()qreal cameraDistancePerspective distance in logical pixels [100, 10000]; default 1000. A shorter distance increases the apparent size difference between near and far surfaces.
ReadcameraDistance()WritesetCameraDistance()NotifycameraDistanceChanged()qreal zoomWhole-scene magnification [0.1, 4]; default 1. Item poses stay unchanged.
Readzoom()WritesetZoom()NotifyzoomChanged()bool pointerTrackingEnabledTilts the whole scene toward the pointer; default true, active in 3D only.
ReadisPointerTrackingEnabled()WritesetPointerTrackingEnabled()NotifypointerTrackingEnabledChanged()QPointF maximumTiltMaximum pointer pitch/yaw, each [0, 45] degrees; default (10, 16).
ReadmaximumTilt()WritesetMaximumTilt()NotifymaximumTiltChanged()int responseTimeExponential pointer response time [0, 1000] ms; default 140, zero is immediate. Larger values soften the response; this is a time constant, not an animation duration.
ReadresponseTime()WritesetResponseTime()NotifyresponseTimeChanged()int maximumFrameRatePointer animation update cap [15, 120] fps; default 60, not measured display FPS.
ReadmaximumFrameRate()WritesetMaximumFrameRate()NotifymaximumFrameRateChanged()bool cacheEnabledCaches widget surfaces; default true. Changed content still repaints.
ReadisCacheEnabled()WritesetCacheEnabled()NotifycacheEnabledChanged()RenderMode renderModeRequested renderer: Auto (default), Raster or OpenGL; OpenGL may fall back. Switching waits until active pointer input finishes; inspect activeBackend for the result. Clipped/hidden views release their GPU viewport. Ancestor graphics effects use Raster so the outer compositor can capture the scene; the requested mode remains unchanged.
ReadrenderMode()WritesetRenderMode()NotifyrenderModeChanged()Backend activeBackendActual renderer, Raster or OpenGL; read-only, initially Raster until exposed.
ReadactiveBackend()NotifyrendererChanged()QString rendererNameActive OpenGL device name; read-only, empty for Raster or before initialization.
ReadrendererName()NotifyrendererChanged()QString fallbackReasonExplanation of automatic renderer fallback; read-only, empty when none applies.
ReadfallbackReason()NotifyrendererChanged()int itemCountNumber of hosted surfaces, including hidden ones; read-only, initially 0. Externally destroyed content is removed immediately; its notification is coalesced until widget teardown finishes, so handlers may destroy the host.
ReaditemCount()NotifyitemCountChanged()
Methods
SpatialItem* addWidget(QWidget* widget, WidgetOwnership ownership = WidgetOwnership::Borrowed)Hosts a supported widget; null/unsupported/already-hosted content is rejected.
QWidget* takeWidget(SpatialItem* item)Detaches content and deletes the item, transferring ownership to the caller.
void releaseItem(SpatialItem* item)Deletes the item and applies its recorded widget ownership policy.
int itemCount() constNumber of hosted surfaces, including hidden ones; read-only, initially 0. Externally destroyed content is removed immediately; its notification is coalesced until widget teardown finishes, so handlers may destroy the host.
bool isSpatialEnabled() constEnables perspective; default true when motion/theme policy permits it. False restores the same widgets in a native vertical layout with their state intact.
void setSpatialEnabled(bool enabled)Enables perspective; default true when motion/theme policy permits it. False restores the same widgets in a native vertical layout with their state intact.
qreal cameraDistance() constPerspective distance in logical pixels [100, 10000]; default 1000. A shorter distance increases the apparent size difference between near and far surfaces.
void setCameraDistance(qreal distance)Perspective distance in logical pixels [100, 10000]; default 1000. A shorter distance increases the apparent size difference between near and far surfaces.
qreal zoom() constWhole-scene magnification [0.1, 4]; default 1. Item poses stay unchanged.
void setZoom(qreal zoom)Whole-scene magnification [0.1, 4]; default 1. Item poses stay unchanged.
bool isPointerTrackingEnabled() constTilts the whole scene toward the pointer; default true, active in 3D only.
void setPointerTrackingEnabled(bool enabled)Tilts the whole scene toward the pointer; default true, active in 3D only.
QPointF maximumTilt() constMaximum pointer pitch/yaw, each [0, 45] degrees; default (10, 16).
void setMaximumTilt(const QPointF& degrees)Maximum pointer pitch/yaw, each [0, 45] degrees; default (10, 16).
int responseTime() constExponential pointer response time [0, 1000] ms; default 140, zero is immediate. Larger values soften the response; this is a time constant, not an animation duration.
void setResponseTime(int milliseconds)Exponential pointer response time [0, 1000] ms; default 140, zero is immediate. Larger values soften the response; this is a time constant, not an animation duration.
int maximumFrameRate() constPointer animation update cap [15, 120] fps; default 60, not measured display FPS.
void setMaximumFrameRate(int framesPerSecond)Pointer animation update cap [15, 120] fps; default 60, not measured display FPS.
bool isCacheEnabled() constCaches widget surfaces; default true. Changed content still repaints.
void setCacheEnabled(bool enabled)Caches widget surfaces; default true. Changed content still repaints.
RenderMode renderMode() constRequested renderer: Auto (default), Raster or OpenGL; OpenGL may fall back. Switching waits until active pointer input finishes; inspect activeBackend for the result. Clipped/hidden views release their GPU viewport. Ancestor graphics effects use Raster so the outer compositor can capture the scene; the requested mode remains unchanged.
void setRenderMode(RenderMode mode)Requested renderer: Auto (default), Raster or OpenGL; OpenGL may fall back. Switching waits until active pointer input finishes; inspect activeBackend for the result. Clipped/hidden views release their GPU viewport. Ancestor graphics effects use Raster so the outer compositor can capture the scene; the requested mode remains unchanged.
Backend activeBackend() constActual renderer, Raster or OpenGL; read-only, initially Raster until exposed.
QString rendererName() constActive OpenGL device name; read-only, empty for Raster or before initialization.
QString fallbackReason() constExplanation of automatic renderer fallback; read-only, empty when none applies.
Signals
void spatialEnabledChanged(bool enabled)Enables perspective; default true when motion/theme policy permits it. False restores the same widgets in a native vertical layout with their state intact.
void cameraDistanceChanged(qreal distance)Perspective distance in logical pixels [100, 10000]; default 1000. A shorter distance increases the apparent size difference between near and far surfaces.
void zoomChanged(qreal zoom)Whole-scene magnification [0.1, 4]; default 1. Item poses stay unchanged.
void pointerTrackingEnabledChanged(bool enabled)Tilts the whole scene toward the pointer; default true, active in 3D only.
void maximumTiltChanged(const QPointF& degrees)Maximum pointer pitch/yaw, each [0, 45] degrees; default (10, 16).
void responseTimeChanged(int milliseconds)Exponential pointer response time [0, 1000] ms; default 140, zero is immediate. Larger values soften the response; this is a time constant, not an animation duration.
void maximumFrameRateChanged(int framesPerSecond)Pointer animation update cap [15, 120] fps; default 60, not measured display FPS.
void cacheEnabledChanged(bool enabled)Caches widget surfaces; default true. Changed content still repaints.
void renderModeChanged(RenderMode mode)Requested renderer: Auto (default), Raster or OpenGL; OpenGL may fall back. Switching waits until active pointer input finishes; inspect activeBackend for the result. Clipped/hidden views release their GPU viewport. Ancestor graphics effects use Raster so the outer compositor can capture the scene; the requested mode remains unchanged.
void rendererChanged()Actual renderer, Raster or OpenGL; read-only, initially Raster until exposed.
void itemCountChanged(int count)Number of hosted surfaces, including hidden ones; read-only, initially 0. Externally destroyed content is removed immediately; its notification is coalesced until widget teardown finishes, so handlers may destroy the host.
Enumerations
enum class RenderModeAutoRasterOpenGL
enum class BackendRasterOpenGL
Destructors
PySide6 additions
addOwnedWidget(widget)Transfer content to the view; releasing its item destroys it.
addReparentedWidget(widget)Restore content to its original QWidget parent on release.
Subclass interfaces
Methods
Inherited from fluent::FluentElement
Methods
static void setTheme(Theme theme)Updates the global theme and notifies active FluentElement instances.
static void setThemeDeferred(Theme theme)Schedules a visible-first batched theme refresh without blocking the current interaction.
static Theme currentTheme()Returns the currently active global theme.
static bool themeUsesDarkAppearance(Theme theme)Returns whether a theme uses dark-backed chrome and material tokens.
static void refreshTheme()Re-broadcasts the current theme to repaint after a design-token change.
static int themeGeneration()Monotonic counter bumped on every theme change, for staleness checks.
Theme effectiveTheme() constResolves the theme used by this element, honoring an inherited QWidget override.
bool effectiveThemeUsesDarkAppearance() constReturns whether this element's effective theme uses dark-backed chrome.
bool setThemeOverrides(const QJsonObject& overrides)Component-facing token accessors.
QJsonObject themeOverrides() constReturns this element's authored overrides.
void clearThemeOverrides()Restores all token fields to global theme defaults.
const Colors& themeColorsRef() constNon-copying access to the active color set (for hot paint paths).
Material::AcrylicToken themeAcrylic() constMaterial, elevation, and adaptive layout tokens.
QColor themeBackdrop(bool active) constWindow-chrome backdrop color for the given activation state.
virtual void onThemeUpdated()Called after the global theme changes.
Enumerations
enum ThemeGlobal visual theme used when resolving design tokens.
Light = 0Dark = 1HighContrast = 2
Types and aliases
struct ColorsDesign token snapshots returned to components.
Inherited from fluent::QMLPlus
Methods
AnchorLayout::Anchors* anchors()Returns mutable anchors for the QWidget host.
void setState(const QString& name)Applies a named state, or clears state when name is empty.
void addState(const QMLState& state)Registers or replaces a named state definition.
void evaluateStates()Reevaluates conditions; the first registered true condition wins.
QMLPlusRuntime* runtime()Returns the lazy host-owned state observation object.
void setAnchors(const AnchorLayout::Anchors& anchors)Replaces all host anchors and invalidates the parent layout.
void resetAnchors()Clears all host anchors and invalidates the parent layout.
void bind(const char* targetProp, QObject* source, const char* sourceProp, PropertyBinder::Direction dir = PropertyBinder::OneWay)Binds a source property to a property on the QWidget host.
BindingHandle bindManaged(const char* targetProp, QObject* source, const char* sourceProp, PropertyBinder::Direction direction = PropertyBinder::OneWay, BindingOptions options = {})Installs a managed direct binding on this QWidget host.
BindingHandle bindComputed(const char* targetProp, const QVector<BindingDependency>& dependencies, std::function<QVariant()> evaluate, BindingOptions options = {})Installs an explicit-dependency C++ expression on this QWidget host.
void addTransition(const StateTransition& transition)Registers a state transition in precedence order.
void setBehavior(const char* propertyName, const PropertyAnimation& animation)Sets the default animation for this host's managed property writes.
void clearBehavior(const char* propertyName)Removes the default animation for future managed writes.
bool writeProperty(const char* propertyName, const QVariant& value)Writes a host property through Behavior without removing its binding.
All inherited Qt members:QWidget