스핀 박스 예제
스핀 박스 예제는 간단한 QSpinBox 위젯부터 QDateTimeEdit 위젯과 같은 복잡한 편집기에 이르기까지 Qt에서 사용할 수 있는 다양한 유형의 스핀 박스를 사용하는 방법을 보여줍니다.
이 예제는 Qt에서 사용할 수 있는 다양한 스핀 박스 기반 위젯을 표시하는 데 사용되는 단일 Window
클래스로 구성됩니다.
창 클래스 정의
Window
클래스는 QWidget 을 상속하며 대화형 기능을 제공하는 데 사용되는 두 개의 슬롯을 포함합니다:
class Window : public QWidget { Q_OBJECT public: Window(QWidget *parent = nullptr); public slots: void changePrecision(int decimals); void setFormatString(const QString &formatString); private: void createSpinBoxes(); void createDateTimeEdits(); void createDoubleSpinBoxes(); QDateTimeEdit *meetingEdit; QDoubleSpinBox *doubleSpinBox; QDoubleSpinBox *priceSpinBox; QDoubleSpinBox *scaleSpinBox; QGroupBox *spinBoxesGroup; QGroupBox *editsGroup; QGroupBox *doubleSpinBoxesGroup; QLabel *meetingLabel; QSpinBox *groupSeparatorSpinBox; QDoubleSpinBox *groupSeparatorSpinBox_d; };
개인 함수는 창에서 각 유형의 스핀 박스를 설정하는 데 사용됩니다. 멤버 변수를 사용하여 다양한 위젯을 추적하여 필요할 때 재구성할 수 있도록 합니다.
창 클래스 구현
생성자는 단순히 프라이빗 함수를 호출하여 예제에서 사용된 다양한 유형의 스핀 박스를 설정하고 각 그룹을 레이아웃에 배치합니다:
Window::Window(QWidget *parent) : QWidget(parent) { createSpinBoxes(); createDateTimeEdits(); createDoubleSpinBoxes(); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(spinBoxesGroup); layout->addWidget(editsGroup); layout->addWidget(doubleSpinBoxesGroup); setLayout(layout); setWindowTitle(tr("Spin Boxes")); }
레이아웃을 사용하여 창의 자식 위젯의 배열을 관리하고 창 제목을 변경합니다.
createSpinBoxes()
함수는 QGroupBox 을 만들고 그 안에 예상되는 입력 유형을 나타내는 설명 레이블이 있는 QSpinBox 위젯 3개를 배치합니다.
void Window::createSpinBoxes() { spinBoxesGroup = new QGroupBox(tr("Spinboxes")); QLabel *integerLabel = new QLabel(tr("Enter a value between " "%1 and %2:").arg(-20).arg(20)); QSpinBox *integerSpinBox = new QSpinBox; integerSpinBox->setRange(-20, 20); integerSpinBox->setSingleStep(1); integerSpinBox->setValue(0);
첫 번째 스핀 박스는 QSpinBox 을 사용하는 가장 간단한 방법을 보여줍니다. 이 상자는 -20에서 20까지의 값을 허용하며, 화살표 버튼이나 Up 및 Down 키를 사용하여 현재 값을 1씩 늘리거나 줄일 수 있으며 기본값은 0입니다.
두 번째 스핀 상자는 더 큰 단계 크기를 사용하며 숫자가 나타내는 데이터 유형에 대한 자세한 정보를 제공하는 접미사를 표시합니다:
QLabel *zoomLabel = new QLabel(tr("Enter a zoom value between " "%1 and %2:").arg(0).arg(1000)); QSpinBox *zoomSpinBox = new QSpinBox; zoomSpinBox->setRange(0, 1000); zoomSpinBox->setSingleStep(10); zoomSpinBox->setSuffix("%"); zoomSpinBox->setSpecialValueText(tr("Automatic")); zoomSpinBox->setValue(100);
이 회전 상자는 또한 정의된 최소값 대신 special value 을 표시합니다. 즉, 0% 이 표시되지 않고 최소값을 선택하면 Automatic 이 표시됩니다.
세 번째 회전 상자는 접두사를 사용할 수 있는 방법을 보여줍니다:
QLabel *priceLabel = new QLabel(tr("Enter a price between " "%1 and %2:").arg(0).arg(999)); QSpinBox *priceSpinBox = new QSpinBox; priceSpinBox->setRange(0, 999); priceSpinBox->setSingleStep(1); priceSpinBox->setPrefix("$"); priceSpinBox->setValue(99);
간단하게 하기 위해 접두사만 있고 접미사가 없는 스핀 상자를 표시합니다. 두 가지를 동시에 사용할 수도 있습니다.
groupSeparatorSpinBox = new QSpinBox; groupSeparatorSpinBox->setRange(-99999999, 99999999); groupSeparatorSpinBox->setValue(1000); groupSeparatorSpinBox->setGroupSeparatorShown(true); QCheckBox *groupSeparatorChkBox = new QCheckBox; groupSeparatorChkBox->setText(tr("Show group separator")); groupSeparatorChkBox->setChecked(true); connect(groupSeparatorChkBox, &QCheckBox::toggled, groupSeparatorSpinBox, &QSpinBox::setGroupSeparatorShown); QLabel *hexLabel = new QLabel(tr("Enter a value between " "%1 and %2:").arg('-' + QString::number(31, 16)).arg(QString::number(31, 16))); QSpinBox *hexSpinBox = new QSpinBox; hexSpinBox->setRange(-31, 31); hexSpinBox->setSingleStep(1); hexSpinBox->setValue(0); hexSpinBox->setDisplayIntegerBase(16); QVBoxLayout *spinBoxLayout = new QVBoxLayout; spinBoxLayout->addWidget(integerLabel); spinBoxLayout->addWidget(integerSpinBox); spinBoxLayout->addWidget(zoomLabel); spinBoxLayout->addWidget(zoomSpinBox); spinBoxLayout->addWidget(priceLabel); spinBoxLayout->addWidget(priceSpinBox); spinBoxLayout->addWidget(hexLabel); spinBoxLayout->addWidget(hexSpinBox); spinBoxLayout->addWidget(groupSeparatorChkBox); spinBoxLayout->addWidget(groupSeparatorSpinBox); spinBoxesGroup->setLayout(spinBoxLayout); }
나머지 함수는 그룹 상자의 레이아웃을 설정하고 그 안에 각 위젯을 배치합니다.
createDateTimeEdits()
함수는 날짜와 시간을 편집하는 데 사용되는 스핀 박스를 선택하여 또 다른 그룹 상자를 만듭니다.
void Window::createDateTimeEdits() { editsGroup = new QGroupBox(tr("Date and time spin boxes")); QLabel *dateLabel = new QLabel; QDateEdit *dateEdit = new QDateEdit(QDate::currentDate()); dateEdit->setDateRange(QDate(2005, 1, 1), QDate(2010, 12, 31)); dateLabel->setText(tr("Appointment date (between %0 and %1):") .arg(dateEdit->minimumDate().toString(Qt::ISODate)) .arg(dateEdit->maximumDate().toString(Qt::ISODate)));
첫 번째 회전 상자는 QDate 값을 사용하여 지정된 범위 내의 날짜를 허용할 수 있는 QDateEdit 위젯입니다. 화살표 버튼과 Up 및 Down 키를 사용하여 커서가 해당 섹션에 있을 때 연도, 월, 일의 값을 늘리거나 줄일 수 있습니다.
두 번째 회전 상자는 QTimeEdit 위젯입니다:
QLabel *timeLabel = new QLabel; QTimeEdit *timeEdit = new QTimeEdit(QTime::currentTime()); timeEdit->setTimeRange(QTime(9, 0, 0, 0), QTime(16, 30, 0, 0)); timeLabel->setText(tr("Appointment time (between %0 and %1):") .arg(timeEdit->minimumTime().toString(Qt::ISODate)) .arg(timeEdit->maximumTime().toString(Qt::ISODate)));
시간에 허용되는 값은 QTime 값을 사용하여 정의됩니다.
세 번째 회전 상자는 QDateTimeEdit 위젯으로 날짜와 시간 값을 모두 표시할 수 있으며, 그 위에 라벨을 배치하여 미팅에 허용되는 시간 범위를 표시합니다. 이 위젯은 사용자가 서식 문자열을 변경할 때 업데이트됩니다.
meetingLabel = new QLabel; meetingEdit = new QDateTimeEdit(QDateTime::currentDateTime());
날짜 시간 편집기에 사용되는 서식 문자열은 레이블로 표시되는 문자열에도 표시되며 콤보박스의 문자열 집합에서 선택됩니다:
QLabel *formatLabel = new QLabel(tr("Format string for the meeting date " "and time:")); QComboBox *formatComboBox = new QComboBox; formatComboBox->addItem("yyyy-MM-dd hh:mm:ss (zzz 'ms')"); formatComboBox->addItem("hh:mm:ss MM/dd/yyyy"); formatComboBox->addItem("hh:mm:ss dd/MM/yyyy"); formatComboBox->addItem("hh:mm:ss"); formatComboBox->addItem("hh:mm ap"); connect(formatComboBox, &QComboBox::textActivated, this, &Window::setFormatString);
이 콤보박스의 신호는 Window
클래스의 슬롯에 연결됩니다(나중에 표시됨).
QVBoxLayout *editsLayout = new QVBoxLayout; editsLayout->addWidget(dateLabel); editsLayout->addWidget(dateEdit); editsLayout->addWidget(timeLabel); editsLayout->addWidget(timeEdit); editsLayout->addWidget(meetingLabel); editsLayout->addWidget(meetingEdit); editsLayout->addWidget(formatLabel); editsLayout->addWidget(formatComboBox); editsGroup->setLayout(editsLayout); }
그룹 상자의 각 자식 위젯은 레이아웃에 배치됩니다.
setFormatString()
슬롯은 사용자가 콤보박스에서 새 형식 문자열을 선택할 때마다 호출됩니다. QDateTimeEdit 위젯의 표시 형식은 신호에 의해 전달된 원시 문자열을 사용하여 설정됩니다:
void Window::setFormatString(const QString &formatString) { meetingEdit->setDisplayFormat(formatString);
위젯에서 표시되는 섹션에 따라 새 날짜 또는 시간 범위를 설정하고 관련 레이블을 업데이트하여 사용자에게 관련 정보를 제공합니다:
if (meetingEdit->displayedSections() & QDateTimeEdit::DateSections_Mask) { meetingEdit->setDateRange(QDate(2004, 11, 1), QDate(2005, 11, 30)); meetingLabel->setText(tr("Meeting date (between %0 and %1):") .arg(meetingEdit->minimumDate().toString(Qt::ISODate)) .arg(meetingEdit->maximumDate().toString(Qt::ISODate))); } else { meetingEdit->setTimeRange(QTime(0, 7, 20, 0), QTime(21, 0, 0, 0)); meetingLabel->setText(tr("Meeting time (between %0 and %1):") .arg(meetingEdit->minimumTime().toString(Qt::ISODate)) .arg(meetingEdit->maximumTime().toString(Qt::ISODate))); } }
형식 문자열이 변경되면 날짜, 시간 또는 두 가지 유형의 입력에 대해 적절한 레이블과 입력 위젯이 표시됩니다.
createDoubleSpinBoxes()
함수는 배정밀도 부동 소수점 숫자를 입력하는 데 사용되는 세 개의 스핀 박스를 구성합니다:
void Window::createDoubleSpinBoxes() { doubleSpinBoxesGroup = new QGroupBox(tr("Double precision spinboxes")); QLabel *precisionLabel = new QLabel(tr("Number of decimal places " "to show:")); QSpinBox *precisionSpinBox = new QSpinBox; precisionSpinBox->setRange(0, 100); precisionSpinBox->setValue(2);
QDoubleSpinBox 위젯을 만들기 전에 소수점 이하 자릿수를 표시하는 스핀 박스를 생성하여 소수점 이하 자릿수를 제어합니다. 기본적으로 다음 스핀 박스에는 소수점 이하 두 자리만 표시되며, 각 스핀 박스는 createSpinBoxes()
함수에 의해 생성된 그룹에 있는 스핀 박스와 동일합니다.
첫 번째 더블 스핀 상자는 createSpinBoxes()
함수의 첫 번째 스핀 상자와 범위, 단계 크기 및 기본값이 동일한 기본 배정밀도 스핀 상자를 표시합니다:
QLabel *doubleLabel = new QLabel(tr("Enter a value between " "%1 and %2:").arg(-20).arg(20)); doubleSpinBox = new QDoubleSpinBox; doubleSpinBox->setRange(-20.0, 20.0); doubleSpinBox->setSingleStep(1.0); doubleSpinBox->setValue(0.0);
그러나 이 스핀 상자를 사용하면 정수가 아닌 값도 입력할 수 있습니다.
두 번째 스핀 상자는 접미사를 표시하고 최소값 대신 특수 값을 표시합니다:
QLabel *scaleLabel = new QLabel(tr("Enter a scale factor between " "%1 and %2:").arg(0).arg(1000.0)); scaleSpinBox = new QDoubleSpinBox; scaleSpinBox->setRange(0.0, 1000.0); scaleSpinBox->setSingleStep(10.0); scaleSpinBox->setSuffix("%"); scaleSpinBox->setSpecialValueText(tr("No scaling")); scaleSpinBox->setValue(100.0);
세 번째 스핀 상자는 접미사 대신 접두사를 표시합니다:
QLabel *priceLabel = new QLabel(tr("Enter a price between " "%1 and %2:").arg(0).arg(1000)); priceSpinBox = new QDoubleSpinBox; priceSpinBox->setRange(0.0, 1000.0); priceSpinBox->setSingleStep(1.0); priceSpinBox->setPrefix("$"); priceSpinBox->setValue(99.99); connect(precisionSpinBox, &QSpinBox::valueChanged,
Window
클래스의 슬롯에 정밀도를 지정하는 QSpinBox 위젯을 연결합니다.
QVBoxLayout *spinBoxLayout = new QVBoxLayout; spinBoxLayout->addWidget(precisionLabel); spinBoxLayout->addWidget(precisionSpinBox); spinBoxLayout->addWidget(doubleLabel); spinBoxLayout->addWidget(doubleSpinBox); spinBoxLayout->addWidget(scaleLabel); spinBoxLayout->addWidget(scaleSpinBox); spinBoxLayout->addWidget(priceLabel); spinBoxLayout->addWidget(priceSpinBox); spinBoxLayout->addWidget(groupSeparatorChkBox); spinBoxLayout->addWidget(groupSeparatorSpinBox_d); doubleSpinBoxesGroup->setLayout(spinBoxLayout); }
나머지 함수는 각 위젯을 그룹 상자의 레이아웃에 배치합니다.
changePrecision()
슬롯은 사용자가 정밀도 스핀 상자의 값을 변경할 때 호출됩니다:
void Window::changePrecision(int decimals) { doubleSpinBox->setDecimals(decimals); scaleSpinBox->setDecimals(decimals); priceSpinBox->setDecimals(decimals); }
이 함수는 신호에 의해 제공된 정수를 사용하여 각 QDoubleSpinBox 위젯의 소수점 이하 자릿수를 지정하기만 하면 됩니다. 각 위젯은 decimals 속성이 변경되면 자동으로 업데이트됩니다.
© 2025 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.