3D Perspective (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
Property preview could not load. Select Property preview to retry.

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
Widget container supporting 3D perspective transforms with OpenGL and CPU raster backends. Falls back to a flat 2D vertical layout when perspective is disabled or Tab / Esc is pressed for input and accessibility.
Constructors
Properties
bool spatialEnabledEnables 3D perspective (default true when allowed); disabling switches to a 2D vertical layout.
ReadisSpatialEnabled()WritesetSpatialEnabled()NotifyspatialEnabledChanged()qreal cameraDistancePerspective camera distance in logical pixels [100, 10000]; default 1000.
ReadcameraDistance()WritesetCameraDistance()NotifycameraDistanceChanged()qreal zoomWhole-scene zoom factor [0.1, 4]; default 1.
Readzoom()WritesetZoom()NotifyzoomChanged()bool pointerTrackingEnabledTilts the scene toward the pointer in 3D mode; default true.
ReadisPointerTrackingEnabled()WritesetPointerTrackingEnabled()NotifypointerTrackingEnabledChanged()QPointF maximumTiltMaximum pointer tilt in degrees per axis [0, 45]; default (10, 16).
ReadmaximumTilt()WritesetMaximumTilt()NotifymaximumTiltChanged()int responseTimePointer smoothing time constant in ms [0, 1000]; default 140.
ReadresponseTime()WritesetResponseTime()NotifyresponseTimeChanged()int maximumFrameRatePointer tilt update rate cap [15, 120] fps; default 60.
ReadmaximumFrameRate()WritesetMaximumFrameRate()NotifymaximumFrameRateChanged()bool cacheEnabledEnables item offscreen caching; default true.
ReadisCacheEnabled()WritesetCacheEnabled()NotifycacheEnabledChanged()RenderMode renderModeRender backend: Auto (default), Raster (CPU), or OpenGL (falls back to CPU if hardware is unavailable).
ReadrenderMode()WritesetRenderMode()NotifyrenderModeChanged()Backend activeBackendCurrently active rendering backend (Raster or OpenGL).
ReadactiveBackend()NotifyrendererChanged()QString rendererNameActive OpenGL renderer name, or empty when using CPU raster.
ReadrendererName()NotifyrendererChanged()QString fallbackReasonReason OpenGL fell back to CPU rendering, or empty otherwise.
ReadfallbackReason()NotifyrendererChanged()int itemCountNumber of items currently in the view.
ReaditemCount()NotifyitemCountChanged()
Methods
SpatialItem* addWidget(QWidget* widget, WidgetOwnership ownership = WidgetOwnership::Borrowed)Adds a widget to the 3D view and returns its SpatialItem; ownership controls cleanup on removal.
QWidget* takeWidget(SpatialItem* item)Detaches the widget, deletes item, and returns widget ownership to the caller.
void releaseItem(SpatialItem* item)Removes item and handles its widget using its WidgetOwnership setting.
int itemCount() constNumber of items currently in the view.
bool isSpatialEnabled() constEnables 3D perspective (default true when allowed); disabling switches to a 2D vertical layout.
void setSpatialEnabled(bool enabled)Enables 3D perspective (default true when allowed); disabling switches to a 2D vertical layout.
qreal cameraDistance() constPerspective camera distance in logical pixels [100, 10000]; default 1000.
void setCameraDistance(qreal distance)Perspective camera distance in logical pixels [100, 10000]; default 1000.
qreal zoom() constWhole-scene zoom factor [0.1, 4]; default 1.
void setZoom(qreal zoom)Whole-scene zoom factor [0.1, 4]; default 1.
bool isPointerTrackingEnabled() constTilts the scene toward the pointer in 3D mode; default true.
void setPointerTrackingEnabled(bool enabled)Tilts the scene toward the pointer in 3D mode; default true.
QPointF maximumTilt() constMaximum pointer tilt in degrees per axis [0, 45]; default (10, 16).
void setMaximumTilt(const QPointF& degrees)Maximum pointer tilt in degrees per axis [0, 45]; default (10, 16).
int responseTime() constPointer smoothing time constant in ms [0, 1000]; default 140.
void setResponseTime(int milliseconds)Pointer smoothing time constant in ms [0, 1000]; default 140.
int maximumFrameRate() constPointer tilt update rate cap [15, 120] fps; default 60.
void setMaximumFrameRate(int framesPerSecond)Pointer tilt update rate cap [15, 120] fps; default 60.
bool isCacheEnabled() constEnables item offscreen caching; default true.
void setCacheEnabled(bool enabled)Enables item offscreen caching; default true.
RenderMode renderMode() constRender backend: Auto (default), Raster (CPU), or OpenGL (falls back to CPU if hardware is unavailable).
void setRenderMode(RenderMode mode)Render backend: Auto (default), Raster (CPU), or OpenGL (falls back to CPU if hardware is unavailable).
Backend activeBackend() constCurrently active rendering backend (Raster or OpenGL).
QString rendererName() constActive OpenGL renderer name, or empty when using CPU raster.
QString fallbackReason() constReason OpenGL fell back to CPU rendering, or empty otherwise.
Signals
void spatialEnabledChanged(bool enabled)Enables 3D perspective (default true when allowed); disabling switches to a 2D vertical layout.
void cameraDistanceChanged(qreal distance)Perspective camera distance in logical pixels [100, 10000]; default 1000.
void zoomChanged(qreal zoom)Whole-scene zoom factor [0.1, 4]; default 1.
void pointerTrackingEnabledChanged(bool enabled)Tilts the scene toward the pointer in 3D mode; default true.
void maximumTiltChanged(const QPointF& degrees)Maximum pointer tilt in degrees per axis [0, 45]; default (10, 16).
void responseTimeChanged(int milliseconds)Pointer smoothing time constant in ms [0, 1000]; default 140.
void maximumFrameRateChanged(int framesPerSecond)Pointer tilt update rate cap [15, 120] fps; default 60.
void cacheEnabledChanged(bool enabled)Enables item offscreen caching; default true.
void renderModeChanged(RenderMode mode)Render backend: Auto (default), Raster (CPU), or OpenGL (falls back to CPU if hardware is unavailable).
void rendererChanged()Currently active rendering backend (Raster or OpenGL).
void itemCountChanged(int count)Number of items currently in the view.
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.
Protected members
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)Replaces this element's sparse color, radius, and font token overrides.
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 registered state by name, or restores the default state when @p name is empty. Unknown names are ignored, and existing bindings resume when leaving the state.
void addState(const QMLState& state)Registers or replaces a named state definition; replacing the active state applies it immediately.
void evaluateStates()Reevaluates state conditions in registration order and activates the first match, or the default state if none match. Also runs automatically when dependency properties notify; derived states using extend inherit ancestor changes unless cyclic or missing.
QMLPlusRuntime* runtime()Returns the lazily created state observer owned by this host.
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 @p sourceProp on @p source to @p targetProp on this QWidget host via PropertyBinder::bind().
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 used when @p propertyName is written via writeProperty() or a binding. Explicit StateTransition rules take precedence; direct C++ setter calls are not animated.
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.
Qt base class docs: QWidget