Fluent-Qt

布局

Field 表单字段

为输入控件加上标签、必填标记、说明和校验提示。

示例

表单字段的真实 Gallery 示例

用法

连接设置表单

示例把输入框放进 Field,并用 FormController 管理修改、异步校验和保存。

#include <FluentQt/Layout.h>
using namespace fluent::layout;

#ifndef GALLERY_CONNECTIONFORM_H
#define GALLERY_CONNECTIONFORM_H

#include <FluentQt/FluentQt.h>

#include <QBoxLayout>
#include <QMap>
#include <QResizeEvent>
#include <QTimer>
#include <QUrl>

namespace fluent::gallery {

// A deterministic connection demo: the application owns values and async work.
// zh_CN: 可重复的连接演示;应用负责字段值与异步操作。
class ConnectionForm final : public layout::Card {
public:
    explicit ConnectionForm(QWidget* parent = nullptr) : Card(parent)
    {
        setObjectName(QStringLiteral("connectionForm"));
        setMaximumWidth(560);
        setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
        m_layout = new QVBoxLayout(this);
        m_layout->setContentsMargins(32, 32, 32, 32);
        m_layout->setSpacing(24);
        m_layout->setAlignment(Qt::AlignTop);

        auto* heading = new QWidget(this);
        auto* headerLayout = new QVBoxLayout(heading);
        headerLayout->setContentsMargins(0, 0, 0, 0);
        headerLayout->setSpacing(8);
        headerLayout->addWidget(label(QStringLiteral("Connection settings"), Typography::FontRole::Subtitle));
        headerLayout->addWidget(
            label(QStringLiteral("Configure the endpoint used by this workspace."), Typography::FontRole::Body, true));
        m_layout->addWidget(heading);

        m_form = new FormController(this);
        m_form->setObjectName(QStringLiteral("connectionFormController"));
        addField(QStringLiteral("name"), QStringLiteral("Connection name"),
            QStringLiteral("A name to identify this connection."), QStringLiteral("Production API"));
        addField(QStringLiteral("address"), QStringLiteral("Server address"),
            QStringLiteral("Use HTTPS. Try offline.example to see a connection error."),
            QStringLiteral("https://api.example.com/v1"));
        addField(QStringLiteral("token"), QStringLiteral("API token"),
            QStringLiteral("Use any 8 characters in this demo."), QString(), true);

        m_status = label(QStringLiteral("No unsaved changes"), Typography::FontRole::Caption, true);
        m_status->setObjectName(QStringLiteral("connectionStatus"));
        m_status->setMinimumHeight(Typography::LineHeight::Caption);
        m_layout->addWidget(m_status);

        auto* actions = new QWidget(this);
        m_actions = new QBoxLayout(QBoxLayout::LeftToRight, actions);
        m_actions->setContentsMargins(0, 0, 0, 0);
        m_actions->setSpacing(8);
        m_test = new basicinput::Button(QStringLiteral("Test connection"), actions);
        m_test->setObjectName(QStringLiteral("connectionTest"));
        m_save = new basicinput::Button(QStringLiteral("Save connection"), actions);
        m_save->setObjectName(QStringLiteral("connectionSave"));
        m_save->setFluentStyle(basicinput::Button::Accent);
        m_actions->addWidget(m_test);
        m_actions->addWidget(m_save);
        m_layout->addWidget(actions);
        m_layout->addWidget(label(QStringLiteral("Local demo · no credentials are sent or stored."),
            Typography::FontRole::Caption, true));

        connect(m_form, &FormController::validationRequested, this, [this](const QString& key, quint64 token) {
            validate(key, token);
        });
        connect(m_form, &FormController::submitRequested, this, [this](quint64 token) {
            QTimer::singleShot(450, m_form, [form = m_form, token]() { form->completeSubmit(token, true); });
        });
        connect(m_form, &FormController::stateChanged, this, [this]() { updateStatus(); });
        connect(m_form, &FormController::submissionFinished, this, [this](bool success) {
            if (success)
                status_info::Toast::showOrUpdateToast(this, QStringLiteral("gallery.action-feedback"),
                    QStringLiteral("Connection saved for this demo"), status_info::Toast::Success, 2200,
                    status_info::Toast::Top, QMargins(16, 50, 16, 16));
        });
        connect(m_test, &basicinput::Button::clicked, m_form, &FormController::validate);
        connect(m_save, &basicinput::Button::clicked, m_form, &FormController::submit);
    }

protected:
    void resizeEvent(QResizeEvent* event) override
    {
        Card::resizeEvent(event);
        const bool narrow = width() < 400;
        const int padding = narrow ? 16 : 32;
        m_layout->setContentsMargins(padding, padding, padding, padding);
        m_actions->setDirection(narrow ? QBoxLayout::TopToBottom : QBoxLayout::LeftToRight);
    }

private:
    textfields::Label* label(const QString& text, Typography::FontRole role, bool secondary = false)
    {
        auto* result = new textfields::Label(text, this);
        result->setFluentTypography(role);
        result->setTextColorRole(
            secondary ? textfields::Label::TextColorRole::Secondary : textfields::Label::TextColorRole::Primary);
        result->setWordWrap(true);
        return result;
    }

    void
    addField(const QString& key, const QString& title, const QString& helper, const QString& value, bool secret = false)
    {
        auto* field = new layout::Field(this);
        field->setObjectName(QStringLiteral("connectionField_") + key);
        field->setLabelText(title);
        field->setHelperText(helper);
        textfields::LineEdit* editor = secret ? new textfields::PasswordBox : new textfields::LineEdit;
        editor->setObjectName(QStringLiteral("connectionInput_") + key);
        editor->setText(value);
        editor->setMinimumHeight(::Spacing::ControlHeight::Standard);
        if (secret)
            editor->setPlaceholderText(QStringLiteral("Enter a demo token"));
        field->setEditor(editor, WidgetOwnership::Owned);
        m_layout->addWidget(field);
        m_editors.insert(key, editor);
        m_form->addField(key, field);
        connect(editor, &textfields::LineEdit::textChanged, m_form, [form = m_form, key]() {
            form->markFieldChanged(key);
        });
        connect(editor, &textfields::LineEdit::editingFinished, m_form, [form = m_form, key]() {
            form->setFieldTouched(key);
        });
    }

    void validate(const QString& key, quint64 token)
    {
        const QString value = m_editors.value(key)->text().trimmed();
        if (key == QStringLiteral("name")) {
            m_form->completeValidation(key, token, !value.isEmpty(),
                value.isEmpty() ? QStringLiteral("Enter a connection name.") : QString());
        } else if (key == QStringLiteral("token")) {
            m_form->completeValidation(key, token, value.size() >= 8,
                value.size() < 8 ? QStringLiteral("Enter at least 8 characters.") : QString());
        } else {
            const QUrl url(value, QUrl::StrictMode);
            if (!url.isValid() || url.scheme() != QStringLiteral("https") || url.host().isEmpty()) {
                m_form->completeValidation(key, token, false, QStringLiteral("Enter a valid HTTPS address."));
                return;
            }
            // Context-owned timer is cancelled on teardown; the token rejects stale results.
            // zh_CN: 上下文计时器随对象销毁取消,token 拒绝过期结果。
            QTimer::singleShot(650, m_form, [form = m_form, key, token, value]() {
                const bool reachable = !value.contains(QStringLiteral("offline"), Qt::CaseInsensitive);
                form->completeValidation(key, token, reachable,
                    reachable ? QStringLiteral("Connection verified.")
                              : QStringLiteral("Server unavailable. Try another address."));
            });
        }
    }

    void updateStatus()
    {
        const bool busy = m_form->isValidating() || m_form->isSubmitting();
        m_test->setEnabled(!busy);
        m_save->setEnabled(!busy);
        m_save->setText(m_form->isSubmitting() ? QStringLiteral("Saving…") : QStringLiteral("Save connection"));
        if (m_form->isValidating())
            m_status->setText(QStringLiteral("Checking connection…"));
        else if (m_form->isSubmitting())
            m_status->setText(QStringLiteral("Saving connection…"));
        else if (!m_form->errorMessages().isEmpty())
            m_status->setText(m_form->errorMessages().join(QLatin1Char('\n')));
        else if (!m_form->submissionError().isEmpty())
            m_status->setText(m_form->submissionError());
        else if (m_form->isValid())
            m_status->setText(m_form->isDirty()
                    ? QStringLiteral("Ready to save · unsaved changes")
                    : QStringLiteral("Connection verified."));
        else
            m_status->setText(
                m_form->isDirty() ? QStringLiteral("Unsaved changes") : QStringLiteral("No unsaved changes"));
    }

    FormController* m_form = nullptr;
    QMap<QString, textfields::LineEdit*> m_editors;
    QVBoxLayout* m_layout = nullptr;
    QBoxLayout* m_actions = nullptr;
    textfields::Label* m_status = nullptr;
    basicinput::Button* m_test = nullptr;
    basicinput::Button* m_save = nullptr;
};

} // namespace fluent::gallery

#endif // GALLERY_CONNECTIONFORM_H

fluent::layout::Field

继承自 QWidget · FluentElement · QMLPlus

为已有编辑器提供标签、帮助/校验展示的组合外壳,不接管编辑器的值。

构造函数

属性

QString labelText
读取 labelText()设置 setLabelText()通知 labelTextChanged()
LabelPosition labelPosition
读取 labelPosition()设置 setLabelPosition()通知 labelPositionChanged()
int labelWidth

前侧标签的统一宽度,长标签自动换行。

读取 labelWidth()设置 setLabelWidth()通知 labelWidthChanged()
bool required
读取 isRequired()设置 setRequired()通知 requiredChanged()
QString helperText
读取 helperText()设置 setHelperText()通知 helperTextChanged()
QString validationMessage
读取 validationMessage()设置 setValidationMessage()通知 validationMessageChanged()
ValidationState validationState
读取 validationState()设置 setValidationState()通知 validationStateChanged()
QWidget* editor
读取 editor()设置 setEditor()通知 editorChanged()

方法

int labelWidth() const

前侧标签的统一宽度,长标签自动换行。

void setLabelWidth(int width)

前侧标签的统一宽度,长标签自动换行。

信号

void labelWidthChanged(int width)

前侧标签的统一宽度,长标签自动换行。

枚举

enum class LabelPosition

标签置于编辑器上方或前侧。

  • Top
  • Leading
enum class ValidationState

当前校验文案的展示状态。

  • None
  • Error
  • Warning
  • Success
  • Validating

析构函数

PySide6 扩展

setOwnedEditor(widget)

Install an editor that is deleted when it leaves the Field.

setBorrowedEditor(widget)

Install an editor that becomes parentless when released.

setReparentedEditor(widget)

Install an editor that returns to its current QWidget parent.

继承自 fluent::FluentElement

方法

static void setTheme(Theme theme)

更新全局主题,并通知所有活跃的 FluentElement 实例。

static void setThemeDeferred(Theme theme)

以可见元素优先的批次调度主题刷新,避免阻塞当前交互。

static Theme currentTheme()

返回当前生效的全局主题。

static bool themeUsesDarkAppearance(Theme theme)

返回指定主题是否使用暗色底的 chrome 与材质 token。

static void refreshTheme()

在设计 token 变化后重新广播当前主题以触发重绘。

static int themeGeneration()

每次主题变化自增的单调计数器,用于过期判断。

Theme effectiveTheme() const

解析此元素实际使用的主题,会优先读取 QWidget 父链上的局部主题覆盖。

bool effectiveThemeUsesDarkAppearance() const

返回此元素的实际主题是否使用暗色底 chrome。

bool setThemeOverrides(const QJsonObject& overrides)

供组件侧访问的设计 token 接口。

QJsonObject themeOverrides() const

返回当前元素的覆盖配置。

void clearThemeOverrides()

恢复全部 token 跟随全局主题。

const Colors& themeColorsRef() const

对当前色板的零拷贝访问(用于绘制热路径)。

Material::AcrylicToken themeAcrylic() const

材质、阴影和自适应布局 token。

QColor themeBackdrop(bool active) const

给定激活状态下的窗口 chrome 背景色。

virtual void onThemeUpdated()

全局主题变化后调用。

枚举

enum Theme

解析设计 token 时使用的全局视觉主题。

  • Light = 0
  • Dark = 1
  • HighContrast = 2

类型与别名

struct Colors

返回给组件使用的设计 token 快照。

继承自 fluent::QMLPlus

方法

AnchorLayout::Anchors* anchors()

返回 QWidget 宿主的可变锚点配置。

void setState(const QString& name)

应用具名 state;名称为空时恢复默认状态。

void addState(const QMLState& state)

注册或替换一个具名 state 定义。

void evaluateStates()

重新计算条件;按注册顺序选择首个成立的条件。

QMLPlusRuntime* runtime()

返回按需创建、由宿主持有的状态观察对象。

void setAnchors(const AnchorLayout::Anchors& anchors)

替换宿主的全部锚点,并使父布局失效。

void resetAnchors()

清除宿主全部锚点,并使父布局失效。

void addTransition(const StateTransition& transition)

按优先顺序注册状态过渡。

void setBehavior(const char* propertyName, const PropertyAnimation& animation)

设置宿主受管理属性写入时使用的默认动画。

void clearBehavior(const char* propertyName)

移除后续受管理写入使用的默认动画。

bool writeProperty(const char* propertyName, const QVariant& value)

通过 Behavior 写入宿主属性,且不移除该属性的绑定。

Qt 基类完整成员:QWidget