캔들스틱 차트 만들기
참고: 이 내용은 '위젯이 포함된 차트 갤러리' 예제의 일부입니다.

캔들스틱 차트를 표시하려면, 먼저 일별 데이터를 처리할 `QCandlestickSeries`를 생성합니다. 또한 상승 및 하락 시 캔들 본문의 색상을 사용자 정의로 지정합니다.
auto acmeSeries = new QCandlestickSeries;
acmeSeries->setName("Acme Ltd");
acmeSeries->setIncreasingColor(QColor(Qt::green));
acmeSeries->setDecreasingColor(QColor(Qt::red));QFile 는 비연속 데이터가 저장된 텍스트 파일에 접근하는 데 사용됩니다. ` CandlestickDataReader `는 텍스트 파일을 읽고 데이터에서 시가, 고가, 저가, 종가 및 타임스탬프 값을 찾아내는 보조 클래스입니다. ` CandlestickDataReader `에 대해서는 나중에 더 자세히 설명하겠습니다. readCandlestickSet() 메서드는 값을 읽어와 호출자에게 반환하는 QCandlestickSet 항목에 설정합니다. 반환된 QCandlestickSet 항목은 시리즈에 추가됩니다. 또한 나중에 사용할 수 있도록 사용자 정의 범주 목록을 저장하고 있습니다.
QFile acmeData(":candlestick");
if (!acmeData.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_loadError = QStringLiteral("Failed to load '%1' file.").arg(acmeData.fileName());
return false;
}
QStringList categories;
CandlestickDataReader dataReader(&acmeData);
while (!dataReader.atEnd()) {
QCandlestickSet *set = dataReader.readCandlestickSet();
if (set) {
acmeSeries->append(set);
categories << QDateTime::fromMSecsSinceEpoch(set->timestamp()).toString("dd");
}
}아래에서는 새로운 QChart 인스턴스를 생성하고, 앞서 생성한 시리즈 객체를 여기에 추가합니다. 또한 제목을 정의하고, 애니메이션을 ` QChart::SeriesAnimation`로 설정합니다.
auto chart = new QChart;
chart->addSeries(acmeSeries);
chart->setTitle("Acme Ltd. Historical Data (July 2015)");
chart->setAnimationOptions(QChart::SeriesAnimations);여기서는 차트에 프레젠테이션을 위한 기본 축을 생성하도록 요청합니다. 그런 다음 차트에서 축 포인터를 조회하고, 이전에 저장해 둔 사용자 정의 범주 목록에서 범주를 설정하여 가로축에 사용자 정의 범주를 지정합니다. 또한 차트에서 축 포인터를 조회한 후 해당 축의 최소 및 최대 값을 설정하여 수직 축의 범위를 지정합니다.
chart->createDefaultAxes();
auto axisX = qobject_cast<QBarCategoryAxis *>(chart->axes(Qt::Horizontal).at(0));
axisX->setCategories(categories);
auto axisY = qobject_cast<QValueAxis *>(chart->axes(Qt::Vertical).at(0));
axisY->setMax(axisY->max() * 1.01);
axisY->setMin(axisY->min() * 0.99);아래에서는 범례를 표시하도록 설정하고 차트 하단에 배치합니다.
chart->legend()->setVisible(true);
chart->legend()->setAlignment(Qt::AlignBottom);마지막으로, 차트를 뷰에 추가합니다.
createDefaultChartView(chart);이제 차트를 표시할 준비가 되었습니다.
여기서는 ` readCandlestickSet() ` 메서드를 자세히 설명합니다. 먼저 파일에서 한 줄을 읽으며, #으로 시작하는 줄은 주석 줄로 간주하여 건너뜁니다.
QString line = m_textStream.readLine();
if (line.startsWith("#") || line.isEmpty())
return nullptr;파일 내의 데이터는 공백으로 구분된 일련의 숫자 형태로 구성되어 있습니다. 이 코드 조각에서는 각 줄을 단일 숫자 문자열로 분할하여 ` QStringList`에 저장합니다.
QStringList strList = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
if (strList.count() != 5)
return nullptr;연속 데이터에서 값을 추출하기 위해 다음 코드가 사용됩니다. strList 에 저장된 값은 타임스탬프, 시가, 고가, 저가, 종가의 순서로 저장됩니다.
const qreal timestamp = strList.at(0).toDouble();
const qreal open = strList.at(1).toDouble();
const qreal high = strList.at(2).toDouble();
const qreal low = strList.at(3).toDouble();
const qreal close = strList.at(4).toDouble();마지막으로, 다음 코드 조각은 새로운 QCandlestickSet을 생성하고 필요한 모든 값을 전달하는 방법을 보여줍니다.
auto candlestickSet = new QCandlestickSet(timestamp);
candlestickSet->setOpen(open);
candlestickSet->setHigh(high);
candlestickSet->setLow(low);
candlestickSet->setClose(close);© 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.