이 페이지에서

콤보 위젯 매퍼 예제

콤보 위젯 매퍼 예제는 QDataWidgetMapper 를 사용하여 모델의 정보를 양식의 특정 위젯에 매핑하는 방법을 보여줍니다.

이름, 주소, 유형 등 다양한 입력란이 포함된 신청서

사용자 인터페이스는 거의 동일하지만, 각 사람의 나이를 입력할 수 있는 스핀 박스 대신 주소를 "집", "직장" 또는 "기타"로 분류할 수 있는 콤보 박스를 제공하는 점을 제외하면, Window 클래스를 생성합니다.

Person 클래스 정의

모델 데이터를 나타내기 위해 이름, 주소 및 주소 유형을 포함하는 ` Person ` 구조체를 정의합니다:

struct Person
{
private:
    Q_GADGET
    Q_PROPERTY(QString name MEMBER name)
    Q_PROPERTY(QString address MEMBER address)
    Q_PROPERTY(QString type MEMBER type)
public:

    QString name;
    QString address;
    QString type;
};

QRangeModel 에 편리하게 데이터를 채울 수 있도록, 멤버 변수들이 동일한 이름의 속성이 되도록 선언된 ` Q_GADGET ` 구조체입니다.

Window 클래스 정의

이 클래스는 생성자와 버튼을 최신 상태로 유지하기 위한 슬롯을 제공합니다:

class Window : public QWidget
{
    Q_OBJECT

public:
    Window(QWidget *parent = nullptr);

private slots:
    void updateButtons(int row);

private:
    QLineEdit *nameEdit;
    QTextEdit *addressEdit;
    QComboBox *typeComboBox;
    QPushButton *nextButton;
    QPushButton *previousButton;
    QList<Person> data;
    QRangeModel *model;
    QDataWidgetMapper *mapper;
};

QDataWidgetMapper 객체와 사용자 인터페이스를 구성하는 컨트롤 외에도, 데이터를 저장하기 위해 QList<Person>을 사용하고, 이를 처리하기 위한 QRangeModel 을 사용합니다.

Window 클래스 구현

Window 클래스의 생성자는 여러 부분으로 나누어 설명할 수 있습니다. 첫 번째 부분에서는 사용자 인터페이스에 사용되는 위젯을 설정합니다:

Window::Window(QWidget *parent)
    : QWidget(parent),
      nameEdit(new QLineEdit),
      addressEdit(new QTextEdit),
      typeComboBox(new QComboBox),
      nextButton(new QPushButton(tr("&Next"))),
      previousButton(new QPushButton(tr("&Previous"))),

인물 목록은 초기화 목록을 사용하여 채워지며, 이 목록은 이후 QRangeModel 에 전달됩니다:

      data{Person{u"Alice"_s,  u"<qt>123 Main Street<br/>Market Town</qt>"_s,                      u"0"_s},
           Person{u"Bob"_s,    u"<qt>PO Box 32<br/>Mail Handling Service<br/>Service City</qt>"_s, u"1"_s},
           Person{u"Carol"_s,  u"<qt>The Lighthouse<br/>Remote Island</qt>"_s,                     u"2"_s},
           Person{u"Donald"_s, u"<qt>47338 Park Avenue<br/>Big City</qt>"_s,                       u"0"_s},
           Person{u"Emma"_s,   u"<qt>Research Station<br/>Base Camp<br/>Big Mountain</qt>"_s,      u"2"_s}},
      model(new QRangeModel(data, this)),
      mapper(new QDataWidgetMapper(this))

다른 위젯과 동일한 방식으로 콤보 박스의 매핑을 설정하지만, 각 사람의 데이터가 포함된 모델의 데이터 대신 주소 유형 문자열이 표시되도록 주소 유형에 대한 정보를 포함하는 자체 모델을 적용한다는 점에 유의하십시오:

    typeComboBox->setModel(new QStringListModel({ tr("Home"), tr("Work"), tr("Other") }, this));

다음으로, 위젯 매퍼를 설정하여 각 입력 위젯을 ` setModel()` 호출로 지정된 모델의 열과 연결합니다:

    mapper->setModel(model);
    mapper->addMapping(nameEdit, 0);
    mapper->addMapping(addressEdit, 1);
    mapper->addMapping(typeComboBox, 2, "currentIndex");

콤보 박스의 경우, 위젯 매퍼에 모델의 값과 연결할 속성을 지정하기 위해 추가 인수를 전달합니다. 그 결과, 사용자가 콤보 박스에서 항목을 선택하면 위젯의 ` currentIndex ` 속성에 저장된 해당 값이 모델에 저장됩니다.

컨스트럭터의 나머지 부분에서는 연결과 레이아웃을 설정합니다:

    connect(previousButton, &QAbstractButton::clicked,
            mapper, &QDataWidgetMapper::toPrevious);
    connect(nextButton, &QAbstractButton::clicked,
            mapper, &QDataWidgetMapper::toNext);
    connect(mapper, &QDataWidgetMapper::currentIndexChanged,
            this, &Window::updateButtons);

    auto *formLayout = new QFormLayout;
    formLayout->addRow(tr("Na&me:"), nameEdit);
    formLayout->addRow(tr("&Address:"), addressEdit);
    formLayout->addRow(tr("&Type:"), typeComboBox);

    auto *buttonLayout = new QVBoxLayout;
    buttonLayout->addWidget(previousButton);
    buttonLayout->addWidget(nextButton);
    buttonLayout->addStretch();

    auto *mainLayout = new QHBoxLayout(this);
    mainLayout->addLayout(formLayout);
    mainLayout->addLayout(buttonLayout);

    setWindowTitle(tr("Delegate Widget Mapper"));
    mapper->toFirst();
}

델리게이트를 사용하여 모델을 뷰에 매핑하기

완전성을 위해 ` updateButtons() ` 슬롯의 구현을 보여드립니다:

void Window::updateButtons(int row)
{
    previousButton->setEnabled(row > 0);
    nextButton->setEnabled(row < model->rowCount() - 1);
}

요약 및 추가 참고 자료

콤보 박스에 별도의 모델을 사용하면 메인 모델에 저장된 데이터와는 별개의 선택 항목 메뉴를 제공할 수 있습니다. 콤보 박스의 ` currentIndex ` 속성을 모델의 특정 열과 연결하는 명명된 매핑을 사용하면, 모델에 조회 값을 효과적으로 저장할 수 있습니다.

그러나 위젯 매퍼의 맥락 밖에서 모델을 읽을 때는, 이러한 조회 값의 의미를 파악하기 위해 ` typeModel `에 대한 정보를 알아야 합니다. ` typeModel `가 보유한 데이터와 선택 항목을 한 곳에 모두 저장할 수 있다면 유용할 것입니다. 이에 대해서는 ` SQL 위젯 매퍼 예제`에서 다루고 있습니다.

예제 프로젝트 @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.