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으로 돌아갑니다.

보호된 멤버

메서드

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

재질, 고도 (elevation) 및 적응형 레이아웃 토큰.

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++ setter 호출에는 애니메이션이 적용되지 않습니다.

void clearBehavior(const char* propertyName)

이후 관리되는 쓰기 작업의 기본 애니메이션을 제거합니다.

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

바인딩을 제거하지 않고 Behavior를 통해 호스트 속성을 씁니다.

Qt 기본 클래스 문서: QWidget