Fluent-Qt

レイアウト

Field フォームフィールド

任意の入力コントロールにラベル、必須マーク、ヘルパーテキスト、検証フィードバックを追加します。

サンプル

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

エディターにラベル、必須マーク、ヘルパーテキスト、検証状態を追加するフォームフィールドラッパー。

コンストラクタ

デストラクタ

列挙型

enum class LabelPosition

キャプションをエディターの上部または横に配置します。

  • Top
  • Leading
enum class ValidationState

検証メッセージの表示状態です(表示専用であり、検証ロジックはアプリケーション側で実装します)。

  • None
  • Error
  • Warning
  • Success
  • Validating

メソッド

int labelWidth() const

Leading モードでの共通キャプション幅。長いラベルは折り返されます。

void setLabelWidth(int width)

Leading モードでの共通キャプション幅。長いラベルは折り返されます。

プロパティ

QString labelText
読み取り labelText()書き込み setLabelText()通知シグナル labelTextChanged()
LabelPosition labelPosition
読み取り labelPosition()書き込み setLabelPosition()通知シグナル labelPositionChanged()
int labelWidth

Leading モードでの共通キャプション幅。長いラベルは折り返されます。

読み取り 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()

シグナル

void labelWidthChanged(int width)

Leading モードでの共通キャプション幅。長いラベルは折り返されます。

PySide6 拡張

setOwnedEditor(widget)

エディターを設定します。Field から取り外すと削除されます。

setBorrowedEditor(widget)

借用するエディターを設定します。解放すると親から切り離されます。

setReparentedEditor(widget)

エディターを設定します。解放すると設定前の親 QWidget に戻ります。

protected メンバー

メソッド

fluent::FluentElement から継承

列挙型

enum Theme

デザイントークン解決時に使用されるグローバルな視覚テーマ。

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

メソッド

static void setTheme(Theme theme)

グローバルテーマを更新し、アクティブな FluentElement インスタンスに通知します。

static void setThemeDeferred(Theme theme)

現在の操作をブロックせずに、可視要素を優先したバッチ処理でテーマの更新をスケジュールします。

static Theme currentTheme()

現在有効なグローバルテーマを返します。

static bool themeUsesDarkAppearance(Theme theme)

テーマがダークベースのクロームおよびマテリアルトークンを使用するかどうかを返します。

static void refreshTheme()

デザイントークンの変更後に再描画するため、現在のテーマを再ブロードキャストします。

static int themeGeneration()

テーマ変更ごとに加算される単調増加カウンターです。鮮度チェックに使用されます。

Theme effectiveTheme() const

継承された QWidget の上書きを尊重し、この要素が使用するテーマを解決します。

bool effectiveThemeUsesDarkAppearance() const

この要素の有効なテーマがダークベースのクロームを使用するかどうかを返します。

bool setThemeOverrides(const QJsonObject& overrides)

この要素のスパースな色、角丸半径、フォントトークンの上書きを置き換えます。

QJsonObject themeOverrides() const

この要素に設定されたオーバーライドを返します。

void clearThemeOverrides()

すべてのトークンフィールドをグローバルテーマの既定値に復元します。

const Colors& themeColorsRef() const

描画のホットパス向けにアクティブなカラーセットへ非コピーでアクセスします。

Material::AcrylicToken themeAcrylic() const

マテリアル、エレベーション、およびアダプティブレイアウトのトークン。

QColor themeBackdrop(bool active) const

指定されたアクティブ状態に対するウィンドウ chrome の背景色。

virtual void onThemeUpdated()

グローバルテーマの変更後に呼び出されます。

型とエイリアス

struct Colors

コンポーネントに返されるデザイントークンのスナップショット。

fluent::QMLPlus から継承

メソッド

AnchorLayout::Anchors* anchors()

QWidget ホストの変更可能なアンカーを返します。

void setState(const QString& name)

登録済みの状態を名前で適用するか、@p name が空の場合はデフォルト状態を復元します。未知の名前は無視され、その状態を離れると既存のバインディングが再開されます。

void addState(const QMLState& state)

名前付き状態定義を登録または置換します。アクティブな状態を置換した場合は即座に適用されます。

void evaluateStates()

登録順に状態条件を再評価し、最初に一致した状態(一致しない場合はデフォルト状態)をアクティブにします。依存プロパティの変更通知時にも自動実行され、extend を使用する派生状態は、循環や欠損がない限り祖先の変更を継承します。

QMLPlusRuntime* runtime()

このホストが所有し、遅延生成される状態オブザーバーを返します。

void setAnchors(const AnchorLayout::Anchors& anchors)

すべてのホストアンカーを置き換え、親レイアウトを無効化します。

void resetAnchors()

ホストのすべてのアンカーをクリアし、親レイアウトを無効化します。

void bind(const char* targetProp, QObject* source, const char* sourceProp, PropertyBinder::Direction dir = PropertyBinder::OneWay)

PropertyBinder::bind() を介して、@p source の @p sourceProp をこの QWidget ホストの @p targetProp にバインドします。

void addTransition(const StateTransition& transition)

優先順位順に状態遷移を登録します。

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

writeProperty() またはバインディング経由で @p propertyName が書き込まれた際に使用されるデフォルトアニメーションを設定します。明示的な StateTransition ルールが優先され、C++ のセッターを直接呼び出した場合はアニメーションしません。

void clearBehavior(const char* propertyName)

今後のマネージド書き込みに使用するデフォルトアニメーションを削除します。

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

バインディングを削除せずに Behavior 経由でホストプロパティに書き込みます。

Qt 基底クラスドキュメント:QWidget