막대 차트와 데이터 모델 사용
참고: 이 내용은 ‘위젯 갤러리를 사용한 차트’ 예제의 일부입니다.

먼저 CustomTableModel 클래스의 인스턴스를 생성해 봅시다. CustomTableModel 클래스는 QAbstractTableModel 을 상속받았으며, 이 예제를 위해 새로 만들어졌습니다. 이 클래스의 생성자는 차트 예제에 필요한 데이터를 모델의 내부 데이터 저장소에 채워 넣습니다.
auto model = new BarModelMapperModel(this);이제 차트와 QTableView 모두에 표시하고자 하는 데이터가 포함된 모델이 준비되었습니다. 먼저, QTableView 를 생성하고 이 모델이 데이터 소스로 사용되도록 지정합니다. 데이터를 보기 좋게 표시하기 위해 테이블 뷰의 최소 너비를 설정하고 헤더의 크기 조정 모드를 ‘stretch’로 변경합니다.
// create table view and add model to it
auto tableView = new QTableView(this);
tableView->setModel(model);
tableView->setMinimumWidth(300);
tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
model->setParent(tableView);이제 차트에 동일한 데이터를 표시할 QChart 인스턴스가 필요합니다. 또한 애니메이션을 활성화합니다. 이렇게 하면 모델 데이터의 변경 사항이 차트에 어떻게 반영되는지 더 쉽게 확인할 수 있습니다.
아래 코드의 첫 번째 줄은 새로운 막대 차트 시리즈를 생성합니다. firstRow 및 rowCount 변수는 사용자 정의 모델 매핑을 정의하는 데 사용됩니다. 사용자 정의 매핑을 사용하면 모델의 데이터 중 일부만 가져올 수 있습니다. 이 경우 인덱스 3인 행부터 시작하는 5개의 행에 해당하는 데이터를 가져옵니다. 다음 세 줄은 QVBarModelMapper 클래스의 인스턴스를 생성하고, 막대 세트의 데이터가 인덱스 1부터 4까지(포함)인 모델의 열에서 가져와야 함을 지정합니다. 시리즈와 모델 간의 연결을 생성하기 위해 이 두 객체를 모두 QVBarModelMapper로 설정합니다.
마지막으로 시리즈를 차트에 추가합니다.
auto series = new QBarSeries;
int first = 3;
int count = 5;
auto mapper = new QVBarModelMapper(this);
mapper->setFirstBarSetColumn(1);
mapper->setLastBarSetColumn(4);
mapper->setFirstRow(first);
mapper->setRowCount(count);
mapper->setSeries(series);
mapper->setModel(model);
chart->addSeries(series);QTableView 에서 어떤 데이터가 어떤 막대 세트에 해당하는지 표시하기 위해, 이 예제에서는 테이블 색상 지정 기능을 사용합니다. 차트에 시리즈가 추가되면 현재 선택된 테마에 따라 색상이 할당됩니다. 아래 코드는 시리즈에서 해당 색상을 추출하여 색상이 지정된 QTableView 를 생성하는 데 사용합니다. 뷰의 색상 지정은 QChart 기능의 일부가 아닙니다.
// for storing color hex from the series
QString seriesColorHex = "#000000";
// get the color of the series and use it for showing the mapped area
QList<QBarSet *> barsets = series->barSets();
for (int i = 0; i < barsets.count(); i++) {
seriesColorHex = "#" + QString::number(barsets.at(i)->brush().color().rgb(), 16).right(6).toUpper();
model->addMapping(seriesColorHex, QRect(1 + i, first, 1, barsets.at(i)->count()));
}데이터의 의미를 설명하는 범주를 차트의 축에 배치하고자 합니다. 다음 코드 조각은 이를 수행하는 방법을 보여줍니다.
QStringList categories {"April", "May", "June", "July", "August"};
auto axisX = new QBarCategoryAxis;
axisX->append(categories);
chart->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
auto axisY = new QValueAxis;
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisY);QGraphicsScene 를 직접 설정하는 번거로움을 피하기 위해, 이를 대신 처리해 주는 QChartView 클래스를 사용합니다. QChart 객체 포인터는 QChartView 생성자의 매개변수로 사용됩니다. 렌더링 결과를 더 깔끔하게 만들기 위해 앤티앨리어싱을 활성화하고 차트 뷰 위젯의 최소 크기를 설정합니다.
auto chartView = new QChartView(chart, this);
chartView->setRenderHint(QPainter::Antialiasing);마지막으로, 두 위젯을 레이아웃에 배치하고 이 레이아웃을 애플리케이션 레이아웃으로 사용합니다.
// create main layout
auto mainLayout = new QGridLayout;
mainLayout->setHorizontalSpacing(10);
mainLayout->addWidget(tableView, 1, 0);
mainLayout->addWidget(chartView, 1, 1);
mainLayout->setColumnStretch(1, 1);
mainLayout->setColumnStretch(0, 0);
setLayout(mainLayout);이제 애플리케이션이 준비되었습니다. 테이블 뷰의 데이터를 수정해 보고 차트에 어떤 변화가 있는지 확인해 보세요.
© 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.