版面配置
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_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 父元件。
繼承自 fluent::FluentElement
列舉
enum Theme解析設計 token 時使用的全域視覺佈景主題。
Light = 0Dark = 1HighContrast = 2
方法
static void setTheme(Theme theme)更新全域主題,並通知使用中的 FluentElement 執行個體。
static void setThemeDeferred(Theme theme)排程以可見元素優先的批次主題重新整理,避免阻斷目前的互動。
static Theme currentTheme()傳回目前生效的全域主題。
static bool themeUsesDarkAppearance(Theme theme)傳回主題是否使用深色底的視窗框架與材質 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()在全域主題變更後呼叫。
型別與別名
struct Colors傳回給元件使用的設計 token 快照。
繼承自 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 setBehavior(const char* propertyName, const PropertyAnimation& animation)設定透過 writeProperty() 或繫結寫入 @p propertyName 時使用的預設動畫。明確的 StateTransition 規則優先;直接呼叫 C++ setter 不會有動畫。
void clearBehavior(const char* propertyName)移除後續受管理寫入所使用的預設動畫。
bool writeProperty(const char* propertyName, const QVariant& value)透過 Behavior 寫入宿主屬性,且不移除該屬性的繫結。
Qt 基底類別文件:QWidget