Fluent-Qt

Diseño

Field Campo de formulario

Agrega una etiqueta, indicador de campo obligatorio, texto de ayuda y comentarios de validación a cualquier control de entrada.

Ejemplo

Field Campo de formulario: Configuración de conexión

Uso

Configuración de conexión

Coordina ediciones, validación asíncrona y guardado con FormController. La demostración usa una simulación local; ninguna credencial sale de esta página.

#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

Hereda de QWidget · FluentElement · QMLPlus

Contenedor de campo de formulario que agrega una etiqueta, marca de obligatorio, texto de ayuda y estado de validación a un editor.

Constructores

Destructores

Enumeraciones

enum class LabelPosition

Coloca la etiqueta encima o junto a su editor.

  • Top
  • Leading
enum class ValidationState

Estado visual del mensaje de validación (solo visualización; la lógica de validación permanece en la aplicación).

  • None
  • Error
  • Warning
  • Success
  • Validating

Métodos

int labelWidth() const

Ancho compartido de etiqueta en modo Leading; las etiquetas largas hacen salto de línea.

void setLabelWidth(int width)

Ancho compartido de etiqueta en modo Leading; las etiquetas largas hacen salto de línea.

Propiedades

QString labelText
Lectura labelText()Escritura setLabelText()Notificación labelTextChanged()
LabelPosition labelPosition
Lectura labelPosition()Escritura setLabelPosition()Notificación labelPositionChanged()
int labelWidth

Ancho compartido de etiqueta en modo Leading; las etiquetas largas hacen salto de línea.

Lectura labelWidth()Escritura setLabelWidth()Notificación labelWidthChanged()
bool required
Lectura isRequired()Escritura setRequired()Notificación requiredChanged()
QString helperText
Lectura helperText()Escritura setHelperText()Notificación helperTextChanged()
QString validationMessage
Lectura validationMessage()Escritura setValidationMessage()Notificación validationMessageChanged()
ValidationState validationState
Lectura validationState()Escritura setValidationState()Notificación validationStateChanged()
QWidget* editor
Lectura editor()Escritura setEditor()Notificación editorChanged()

Señales

void labelWidthChanged(int width)

Ancho compartido de etiqueta en modo Leading; las etiquetas largas hacen salto de línea.

Adiciones de PySide6

setOwnedEditor(widget)

Establece un editor que se elimina al retirarlo de Field.

setBorrowedEditor(widget)

Establece un editor que queda sin padre al liberarlo.

setReparentedEditor(widget)

Establece un editor que, al liberarse, vuelve a su QWidget padre anterior.

Miembros protegidos

Métodos

Heredado de fluent::FluentElement

Enumeraciones

enum Theme

Tema visual global usado al resolver los tokens de diseño.

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

Métodos

static void setTheme(Theme theme)

Actualiza el tema global y notifica a las instancias activas de FluentElement.

static void setThemeDeferred(Theme theme)

Programa una actualización de tema por lotes dando prioridad a lo visible sin bloquear la interacción actual.

static Theme currentTheme()

Devuelve el tema global activo actualmente.

static bool themeUsesDarkAppearance(Theme theme)

Devuelve si un tema utiliza cromo sobre fondo oscuro y tokens de material.

static void refreshTheme()

Vuelve a difundir el tema actual para repintar tras un cambio de token de diseño.

static int themeGeneration()

Contador monótono incrementado en cada cambio de tema para comprobaciones de obsolescencia.

Theme effectiveTheme() const

Resuelve el tema usado por este elemento, respetando una invalidación heredada de QWidget.

bool effectiveThemeUsesDarkAppearance() const

Devuelve si el tema efectivo de este elemento usa cromo sobre fondo oscuro.

bool setThemeOverrides(const QJsonObject& overrides)

Reemplaza las invalidaciones dispersas de tokens de color, radio y fuente de este elemento.

QJsonObject themeOverrides() const

Devuelve las anulaciones definidas en este elemento.

void clearThemeOverrides()

Restaura todos los campos de token a los valores predeterminados del tema global.

const Colors& themeColorsRef() const

Acceso sin copia al conjunto de colores activo para rutas críticas de pintado.

Material::AcrylicToken themeAcrylic() const

Tokens de material, elevación y diseño adaptable.

QColor themeBackdrop(bool active) const

Color de fondo del chrome de la ventana para el estado de activación indicado.

virtual void onThemeUpdated()

Se llama después de que cambia el tema global.

Tipos y alias

struct Colors

Instantáneas de tokens de diseño devueltas a los componentes.

Heredado de fluent::QMLPlus

Métodos

AnchorLayout::Anchors* anchors()

Devuelve los anclajes mutables del host QWidget.

void setState(const QString& name)

Aplica un estado registrado por nombre o restaura el estado predeterminado cuando @p name está vacío. Los nombres desconocidos se ignoran y los enlaces existentes se reanudan al salir del estado.

void addState(const QMLState& state)

Registra o reemplaza una definición de estado con nombre; reemplazar el estado activo lo aplica de inmediato.

void evaluateStates()

Reevalúa las condiciones de estado en orden de registro y activa la primera coincidencia, o el estado predeterminado si ninguna coincide. También se ejecuta automáticamente cuando notifican las propiedades dependientes; los estados derivados que usan extend heredan cambios de ancestros salvo que sean cíclicos o falten.

QMLPlusRuntime* runtime()

Devuelve el observador de estado creado de forma diferida y propiedad de este host.

void setAnchors(const AnchorLayout::Anchors& anchors)

Reemplaza todos los anclajes del host e invalida el diseño padre.

void resetAnchors()

Limpia todos los anclajes del host e invalida el diseño padre.

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

Vincula @p sourceProp en @p source con @p targetProp en este host QWidget mediante PropertyBinder::bind().

void addTransition(const StateTransition& transition)

Registra una transición de estado por orden de precedencia.

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

Establece la animación por defecto usada al escribir @p propertyName mediante writeProperty() o un enlace. Las reglas StateTransition explícitas tienen prioridad; las llamadas directas a setters de C++ no se animan.

void clearBehavior(const char* propertyName)

Quita la animación predeterminada para futuras escrituras administradas.

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

Escribe una propiedad del host mediante Behavior sin eliminar su enlace.

Documentación de la clase base de Qt: QWidget