レイアウト
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_Himport fluentqt
# Fields and asynchronous handlers are in Full example.
form = fluentqt.FormController(self)
form.addField("address", address_field)
address_editor.textChanged.connect(lambda _text: form.markFieldChanged("address"))
# Complete validationRequested(key, token) with completeValidation().
# Complete submitRequested(token) with completeSubmit().
form.submit()API
宣言を表示一致する API メンバーはありません。
fluent::layout::Field
継承元 QWidget · FluentElement · QMLPlus
エディターにラベル、必須マーク、ヘルパーテキスト、検証状態を追加するフォームフィールドラッパー。
コンストラクタ
デストラクタ
列挙型
enum class LabelPositionキャプションをエディターの上部または横に配置します。
TopLeading
enum class ValidationState検証メッセージの表示状態です(表示専用であり、検証ロジックはアプリケーション側で実装します)。
NoneErrorWarningSuccessValidating
メソッド
int labelWidth() constLeading モードでの共通キャプション幅。長いラベルは折り返されます。
void setLabelWidth(int width)Leading モードでの共通キャプション幅。長いラベルは折り返されます。
プロパティ
QString labelText- 読み取り
labelText()書き込みsetLabelText()通知シグナルlabelTextChanged() LabelPosition labelPosition- 読み取り
labelPosition()書き込みsetLabelPosition()通知シグナルlabelPositionChanged() int labelWidthLeading モードでの共通キャプション幅。長いラベルは折り返されます。
読み取り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 = 0Dark = 1HighContrast = 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 にバインドします。
BindingHandle bindManaged(const char* targetProp, QObject* source, const char* sourceProp, PropertyBinder::Direction direction = PropertyBinder::OneWay, BindingOptions options = {})この QWidget ホストに管理された直接バインディングを設定します。
BindingHandle bindComputed(const char* targetProp, const QVector<BindingDependency>& dependencies, std::function<QVariant()> evaluate, BindingOptions options = {})この QWidget ホストに明示的依存関係を持つ C++ 式を設定します。
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