이 페이지에서

Qt 스타일 시트 예제

이제 Qt 스타일 시트 사용을 시작하기 위한 몇 가지 예제를 살펴보겠습니다.

스타일 시트 사용법

전경색 및 배경색 사용자 정의

먼저 애플리케이션 내의 모든 QLineEdit의 배경색을 노란색으로 설정해 보겠습니다. 다음과 같이 구현할 수 있습니다:

qApp->setStyleSheet("QLineEdit { background-color: yellow }");

특정 대화 상자의 자식(또는 손자, 증손자)인 QLineEdit에만 이 속성이 적용되도록 하려면 다음과 같이 작성하면 됩니다:

myDialog->setStyleSheet("QLineEdit { background-color: yellow }");

특정 QLineEdit 하나에만 이 속성을 적용하려면, ` QObject::setObjectName()`를 사용하여 이름을 지정하고 ID 선택자를 통해 참조할 수 있습니다:

myDialog->setStyleSheet("QLineEdit#nameEdit { background-color: yellow }");

또는 선택자를 생략하고 ` QLineEdit`에 ` background-color ` 속성을 직접 설정할 수도 있습니다:

nameEdit->setStyleSheet("background-color: yellow");

충분한 대비를 확보하려면 텍스트에 적합한 색상도 지정해야 합니다:

nameEdit->setStyleSheet("color: blue; background-color: yellow");

선택된 텍스트에 사용되는 색상도 변경하는 것이 좋습니다:

nameEdit->setStyleSheet("color: blue;"
                        "background-color: yellow;"
                        "selection-color: yellow;"
                        "selection-background-color: blue;");

동적 속성을 이용한 사용자 정의

필수 입력란이 포함된 양식을 표시해야 하는 경우가 많습니다. 사용자에게 해당 입력란이 필수임을 알리기 위한 한 가지 효과적인(비록 미적 측면에서는 논란의 여지가 있지만) 해결책은 해당 입력란의 배경색으로 노란색을 사용하는 것입니다. Qt 스타일 시트를 사용하면 이를 매우 쉽게 구현할 수 있습니다. 먼저, 다음과 같은 애플리케이션 전체에 적용되는 스타일 시트를 사용합니다:

*[mandatoryField="true"] { background-color: yellow }

이는 Qt의 ` mandatoryField ` 속성이 true로 설정된 모든 위젯의 배경색이 노란색이 됨을 의미합니다.

그런 다음, 필수 입력 필드 위젯마다 mandatoryField 속성을 동적으로 생성하여 true로 설정하면 됩니다. 예를 들어:

QLineEdit *nameEdit = new QLineEdit(this);
nameEdit->setProperty("mandatoryField", true);

QLineEdit *emailEdit = new QLineEdit(this);
emailEdit->setProperty("mandatoryField", true);

QSpinBox *ageSpinBox = new QSpinBox(this);
ageSpinBox->setProperty("mandatoryField", true);

박스 모델을 사용하여 QPushButton 사용자 정의하기

이번에는 빨간색 ` QPushButton`을 만드는 방법을 보여드리겠습니다. 이 ` QPushButton `은 아마도 매우 파괴적인 코드와 연결되어 있을 것입니다.

먼저, 다음과 같은 스타일 시트를 사용하고 싶은 유혹이 듭니다:

QPushButton#evilButton { background-color: red }

하지만 그 결과 테두리가 없는 지루하고 평면적인 버튼이 만들어집니다:

평평한 빨간색 버튼

무슨 일이 있었는지 설명해 드리겠습니다:

  • 기본 스타일만으로는 충족할 수 없는 요청을 한 것입니다(예를 들어, 기본 Windows 테마 엔진에서는 버튼의 배경색을 지정할 수 없습니다).
  • 따라서 버튼은 스타일시트를 사용하여 렌더링됩니다.
  • border-width와 border-style에 대한 값을 지정하지 않았기 때문에, 기본적으로 너비 0픽셀의 none 스타일 테두리가 적용됩니다.

테두리를 지정하여 상황을 개선해 봅시다:

QPushButton#evilButton {
    background-color: red;
    border-style: outset;
    border-width: 2px;
    border-color: beige;
}

베이지색 테두리가 있는 빨간색 버튼

이미 훨씬 나아 보입니다. 하지만 버튼이 약간 빽빽해 보입니다. 패딩을 사용하여 테두리와 텍스트 사이에 간격을 지정해 봅시다. 또한, 버튼이 더 보기 좋게 보이도록 최소 너비를 지정하고, 모서리를 둥글게 처리하며, 더 큰 글꼴을 지정하겠습니다:

QPushButton#evilButton {
    background-color: red;
    border-style: outset;
    border-width: 2px;
    border-radius: 10px;
    border-color: beige;
    font: bold 14px;
    min-width: 10em;
    padding: 6px;
}

둥근 베이지색 테두리가 둘러진 빨간색 버튼과 크고 굵은 글자

남은 유일한 문제는 버튼을 눌러도 반응이 없다는 점입니다. 배경색을 약간 다르게 지정하고 다른 테두리 스타일을 사용하면 이 문제를 해결할 수 있습니다.

QPushButton#evilButton {
    background-color: red;
    border-style: outset;
    border-width: 2px;
    border-radius: 10px;
    border-color: beige;
    font: bold 14px;
    min-width: 10em;
    padding: 6px;
}
QPushButton#evilButton:pressed {
    background-color: rgb(224, 0, 0);
    border-style: inset;
}

QPushButton의 메뉴 표시기 하위 컨트롤 사용자 정의

QPushButton 서브컨트롤을 사용하면 위젯의 하위 요소에 접근할 수 있습니다. 예를 들어, QPushButton::setMenu()을 사용하여 메뉴와 연결된 QPushButton은 메뉴 표시기를 가지고 있습니다. 빨간색 푸시 버튼의 메뉴 표시기를 사용자 정의해 봅시다:

QPushButton#evilButton::menu-indicator {
    image: url(myindicator.png);
}

기본적으로 메뉴 표시기는 패딩 사각형의 오른쪽 하단 모서리에 위치합니다. subcontrol-position과 subcontrol-origin을 지정하여 표시기의 고정 위치를 다르게 설정함으로써 이를 변경할 수 있습니다. 또한 top과 left를 사용하여 표시기를 몇 픽셀씩 이동시킬 수도 있습니다. 예를 들어:

QPushButton::menu-indicator {
    image: url(myindicator.png);
    subcontrol-position: right center;
    subcontrol-origin: padding;
    left: -2px;
}

이렇게 하면 myindicator.png 가 QPushButton 의 패딩 사각형 오른쪽 중앙에 위치하게 됩니다(자세한 내용은 subcontrol-origin 참조).

복합 선택자 예시

빨간색이 우리가 가장 좋아하는 색인 것 같으니, 다음의 애플리케이션 전체 스타일시트를 설정하여 QLineEdit 의 텍스트를 빨간색으로 만들어 봅시다:

QLineEdit { color: red }

하지만 QLineEdit 가 읽기 전용임을 시각적으로 표시하기 위해 회색으로 보이게 하고 싶습니다:

QLineEdit { color: red }
QLineEdit[readOnly="true"] { color: gray }

어느 순간, 디자인 팀에서 등록 양식( object name registrationDialog ) 내의 모든 QLineEdit를 갈색으로 표시해야 한다는 요구 사항을 제시했습니다:

QLineEdit { color: red }
QLineEdit[readOnly="true"] { color: gray }
#registrationDialog QLineEdit { color: brown }

몇 차례 UI 디자인 회의를 거친 후, 모든 ‘ QDialog’의 ‘ QLineEdit’을 갈색으로 처리하기로 결정했습니다:

QLineEdit { color: red }
QLineEdit[readOnly="true"] { color: gray }
QDialog QLineEdit { color: brown }

퀴즈: QDialog 내에 읽기 전용 QLineEdit 이 있다면 어떻게 될까요? [힌트: 위의 ‘충돌 해결’ 섹션에서 이와 같은 경우에 대해 설명하고 있습니다.]

특정 위젯 사용자 정의

이 섹션에서는 스타일 시트를 사용하여 특정 위젯을 사용자 정의하는 예제를 제공합니다.

QAbstractScrollArea 사용자 정의

모든 QAbstractScrollArea (Item 뷰, QTextEdit 및 QTextBrowser)의 배경은 background 속성을 사용하여 설정할 수 있습니다. 예를 들어, 스크롤 바와 함께 스크롤되는 배경 이미지를 설정하려면:

QTextEdit, QListView {
    background-color: white;
    background-image: url(draft.png);
    background-attachment: scroll;
}

배경 이미지를 뷰포트에 고정하려면:

QTextEdit, QListView {
    background-color: white;
    background-image: url(draft.png);
    background-attachment: fixed;
}

QCheckBox 사용자 정의

QCheckBox 의 스타일 지정은 QRadioButton 의 스타일 지정과 거의 동일합니다. 주요 차이점은 3상태 QCheckBox 에는 ‘불확정’ 상태가 있다는 점입니다.

QCheckBox {
    spacing: 5px;
}

QCheckBox::indicator {
    width: 13px;
    height: 13px;
}

QCheckBox::indicator:unchecked {
    image: url(:/images/checkbox_unchecked.png);
}

QCheckBox::indicator:unchecked:hover {
    image: url(:/images/checkbox_unchecked_hover.png);
}

QCheckBox::indicator:unchecked:pressed {
    image: url(:/images/checkbox_unchecked_pressed.png);
}

QCheckBox::indicator:checked {
    image: url(:/images/checkbox_checked.png);
}

QCheckBox::indicator:checked:hover {
    image: url(:/images/checkbox_checked_hover.png);
}

QCheckBox::indicator:checked:pressed {
    image: url(:/images/checkbox_checked_pressed.png);
}

QCheckBox::indicator:indeterminate:hover {
    image: url(:/images/checkbox_indeterminate_hover.png);
}

QCheckBox::indicator:indeterminate:pressed {
    image: url(:/images/checkbox_indeterminate_pressed.png);
}

QComboBox 사용자 정의

QComboBox 의 드롭다운 버튼이 콤보 박스 프레임과 “합쳐진” 것처럼 표시되는 예제를 살펴보겠습니다.

QComboBox {
    border: 1px solid gray;
    border-radius: 3px;
    padding: 1px 18px 1px 3px;
    min-width: 6em;
}

QComboBox:editable {
    background: white;
}

QComboBox:!editable, QComboBox::drop-down:editable {
     background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                 stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                 stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
}

/* QComboBox gets the "on" state when the popup is open */
QComboBox:!editable:on, QComboBox::drop-down:editable:on {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #D3D3D3, stop: 0.4 #D8D8D8,
                                stop: 0.5 #DDDDDD, stop: 1.0 #E1E1E1);
}

QComboBox:on { /* shift the text when the popup opens */
    padding-top: 3px;
    padding-left: 4px;
}

QComboBox::drop-down {
    subcontrol-origin: padding;
    subcontrol-position: top right;
    width: 15px;

    border-left-width: 1px;
    border-left-color: darkgray;
    border-left-style: solid; /* just a single line */
    border-top-right-radius: 3px; /* same radius as the QComboBox */
    border-bottom-right-radius: 3px;
}

QComboBox::down-arrow {
    image: url(/usr/share/icons/crystalsvg/16x16/actions/1downarrow.png);
}

QComboBox::down-arrow:on { /* shift the arrow when popup is open */
    top: 1px;
    left: 1px;
}

QComboBox 의 팝업은 QAbstractItemView 이며, 후손 선택자를 사용하여 스타일을 지정합니다:

QComboBox QAbstractItemView {
    border: 2px solid darkgray;
    selection-background-color: lightgray;
}

QDockWidget 사용자 정의

QDockWidget 의 제목 표시줄과 버튼은 다음과 같이 사용자 정의할 수 있습니다:

QDockWidget {
    border: 1px solid lightgray;
    titlebar-close-icon: url(close.png);
    titlebar-normal-icon: url(undock.png);
}

QDockWidget::title {
    text-align: left; /* align the text to the left */
    background: lightgray;
    padding-left: 5px;
}

QDockWidget::close-button, QDockWidget::float-button {
    border: 1px solid transparent;
    background: darkgray;
    padding: 0px;
}

QDockWidget::close-button:hover, QDockWidget::float-button:hover {
    background: gray;
}

QDockWidget::close-button:pressed, QDockWidget::float-button:pressed {
    padding: 1px -1px -1px 1px;
}

도크 위젯의 버튼을 왼쪽으로 이동시키고 싶다면 다음 스타일 시트를 사용할 수 있습니다:

QDockWidget {
    border: 1px solid lightgray;
    titlebar-close-icon: url(close.png);
    titlebar-normal-icon: url(float.png);
}

QDockWidget::title {
    text-align: left;
    background: lightgray;
    padding-left: 35px;
}

QDockWidget::close-button, QDockWidget::float-button {
    background: darkgray;
    padding: 0px;
    icon-size: 14px; /* maximum icon size */
}

QDockWidget::close-button:hover, QDockWidget::float-button:hover {
    background: gray;
}

QDockWidget::close-button:pressed, QDockWidget::float-button:pressed {
    padding: 1px -1px -1px 1px;
}

QDockWidget::close-button {
    subcontrol-position: top left;
    subcontrol-origin: margin;
    position: absolute;
    top: 0px; left: 0px; bottom: 0px;
    width: 14px;
}

QDockWidget::float-button {
    subcontrol-position: top left;
    subcontrol-origin: margin;
    position: absolute;
    top: 0px; left: 16px; bottom: 0px;
    width: 14px;
}

참고: QDockWidget 의 구분선(크기 조정 핸들)을 사용자정의하려면 QMainWindow::separator를 사용하십시오.

QFrame 사용자 정의

QFrame 의 스타일은 박스 모델(Box Model)을 사용하여 지정됩니다.

QFrame, QLabel, QToolTip {
    border: 2px solid green;
    border-radius: 4px;
    padding: 2px;
    background-image: url(images/welcome.png);
}

QGroupBox 사용자 정의

QGroupBox 의 제목을 중앙으로 이동시키는 예제를 살펴보겠습니다.

QGroupBox {
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #E0E0E0, stop: 1 #FFFFFF);
    border: 2px solid gray;
    border-radius: 5px;
    margin-top: 1ex; /* leave space at the top for the title */
}

QGroupBox::title {
    subcontrol-origin: margin;
    subcontrol-position: top center; /* position at the top center */
    padding: 0 3px;
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #FF0ECE, stop: 1 #FFFFFF);
}

선택 가능한 QGroupBox 의 경우, {#indicator-sub}{::indicator} 하위 컨트롤을 사용하고 QCheckBox 와 똑같이 스타일을 지정하십시오(예:

QGroupBox::indicator {
    width: 13px;
    height: 13px;
}

QGroupBox::indicator:unchecked {
    image: url(:/images/checkbox_unchecked.png);
}

/* proceed with styling just like QCheckBox */

QHeaderView 사용자 정의

QHeaderView 는 다음과 같이 사용자 정의됩니다:

QHeaderView::section {
    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                      stop:0 #616161, stop: 0.5 #505050,
                                      stop: 0.6 #434343, stop:1 #656565);
    color: white;
    padding-left: 4px;
    border: 1px solid #6c6c6c;
}

QHeaderView::section:checked
{
    background-color: red;
}

/* style the sort indicator */
QHeaderView::down-arrow {
    image: url(down_arrow.png);
}

QHeaderView::up-arrow {
    image: url(up_arrow.png);
}

QLineEdit 사용자 정의

QLineEdit 의 프레임은 박스 모델(Box Model)을 사용하여 스타일을 지정합니다. 모서리가 둥근 라인 에디트를 만들려면 다음과 같이 설정할 수 있습니다:

QLineEdit {
    border: 2px solid gray;
    border-radius: 10px;
    padding: 0 8px;
    background: yellow;
    selection-background-color: darkgray;
}

QLineEdit::Password 의 에코 모드를 사용하는 라인 에디트의 비밀번호 문자는 다음과 같이 설정할 수 있습니다:

QLineEdit[echoMode="2"] {
    lineedit-password-character: 9679;
}

읽기 전용 QLineEdit 의 배경은 다음과 같이 수정할 수 있습니다:

QLineEdit:read-only {
    background: lightblue;
}

QListView 사용자 정의

교대로 배치된 행의 배경색은 다음 스타일 시트를 사용하여 사용자 정의할 수 있습니다:

QListView {
    alternate-background-color: yellow;
}

항목 위에 마우스를 올렸을 때 특별한 배경을 표시하려면 ::item 하위 컨트롤을 사용할 수 있습니다. 예를 들어,

QListView {
    show-decoration-selected: 1; /* make the selection span the entire width of the view */
}

QListView::item:alternate {
    background: #EEEEEE;
}

QListView::item:selected {
    border: 1px solid #6a6ea9;
}

QListView::item:selected:!active {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #ABAFE5, stop: 1 #8588B2);
}

QListView::item:selected:active {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #6a6ea9, stop: 1 #888dd9);
}

QListView::item:hover {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #FAFBFE, stop: 1 #DCDEF1);
}

QListView 사용자 정의

QMainWindow 의 구분선은 다음과 같이 스타일을 지정할 수 있습니다:

QMainWindow::separator {
    background: yellow;
    width: 10px; /* when vertical */
    height: 10px; /* when horizontal */
}

QMainWindow::separator:hover {
    background: red;
}

QListView 사용자 정의

QMenu 의 개별 항목은 다음과 같이 'item' 하위 컨트롤을 사용하여 스타일을 지정할 수 있습니다:

QMenu {
    background-color: #ABABAB; /* sets background of the menu */
    border: 1px solid black;
}

QMenu::item {
    /* sets background of menu item. set this to something non-transparent
        if you want menu color and menu item color to be different */
    background-color: transparent;
}

QMenu::item:selected { /* when user selects item using mouse or keyboard */
    background-color: #654321;
}

더 고급 사용자 지정을 하려면 다음과 같이 스타일 시트를 사용합니다:

QMenu {
    background-color: white;
    margin: 2px; /* some spacing around the menu */
}

QMenu::item {
    padding: 2px 25px 2px 20px;
    border: 1px solid transparent; /* reserve space for selection border */
}

QMenu::item:selected {
    border-color: darkblue;
    background: rgba(100, 100, 100, 150);
}

QMenu::icon:checked { /* appearance of a 'checked' icon */
    background: gray;
    border: 1px inset gray;
    position: absolute;
    top: 1px;
    right: 1px;
    bottom: 1px;
    left: 1px;
}

QMenu::separator {
    height: 2px;
    background: lightblue;
    margin-left: 10px;
    margin-right: 5px;
}

QMenu::indicator {
    width: 13px;
    height: 13px;
}

/* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */
QMenu::indicator:non-exclusive:unchecked {
    image: url(:/images/checkbox_unchecked.png);
}

QMenu::indicator:non-exclusive:unchecked:selected {
    image: url(:/images/checkbox_unchecked_hover.png);
}

QMenu::indicator:non-exclusive:checked {
    image: url(:/images/checkbox_checked.png);
}

QMenu::indicator:non-exclusive:checked:selected {
    image: url(:/images/checkbox_checked_hover.png);
}

/* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */
QMenu::indicator:exclusive:unchecked {
    image: url(:/images/radiobutton_unchecked.png);
}

QMenu::indicator:exclusive:unchecked:selected {
    image: url(:/images/radiobutton_unchecked_hover.png);
}

QMenu::indicator:exclusive:checked {
    image: url(:/images/radiobutton_checked.png);
}

QMenu::indicator:exclusive:checked:selected {
    image: url(:/images/radiobutton_checked_hover.png);
}

QMenuBar 사용자 정의

QMenuBar 스타일 지정은 다음과 같이 수행됩니다:

QMenuBar {
    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                      stop:0 lightgray, stop:1 darkgray);
    spacing: 3px; /* spacing between menu bar items */
}

QMenuBar::item {
    padding: 1px 4px;
    background: transparent;
    border-radius: 4px;
}

QMenuBar::item:selected { /* when selected using mouse or keyboard */
    background: #a8a8a8;
}

QMenuBar::item:pressed {
    background: #888888;
}

QProgressBar 사용자 정의

QProgressBar 의 테두리, 청크 및 텍스트 정렬은 스타일 시트를 사용하여 사용자 정의할 수 있습니다. 그러나 하나의 속성이나 하위 컨트롤을 사용자 정의할 경우, 다른 모든 속성이나 하위 컨트롤도 함께 사용자 정의해야 합니다.

30%를 표시하는 진행률 표시줄

예를 들어, 테두리 색상을 회색으로, 청크 색상을 청록색으로 변경합니다.

QProgressBar {
    border: 2px solid grey;
    border-radius: 5px;
}

QProgressBar::chunk {
    background-color: #05B8CC;
    width: 20px;
}

이제 텍스트 정렬만 남았는데, 이를 진행률 표시줄의 중앙에 텍스트를 배치하여 사용자 정의합니다.

QProgressBar {
    border: 2px solid grey;
    border-radius: 5px;
    text-align: center;
}

청크를 더 잘 보이게 하려면 여백을 추가할 수 있습니다.

홈이 파인 진행률 표시줄

위의 스크린샷에서는 0.5 픽셀의 여백 을 사용했습니다.

QProgressBar::chunk {
    background-color: #CD96CD;
    width: 10px;
    margin: 0.5px;
}

QPushButton 사용자 정의

QPushButton 의 스타일은 다음과 같습니다.

QPushButton {
    border: 2px solid #8f8f91;
    border-radius: 6px;
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #f6f7fa, stop: 1 #dadbde);
    min-width: 80px;
}

QPushButton:pressed {
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #dadbde, stop: 1 #f6f7fa);
}

QPushButton:flat {
    border: none; /* no border for a flat push button */
}

QPushButton:default {
    border-color: navy; /* make the default button prominent */
}

메뉴가 있는 QPushButton 의 경우 ::menu-indicator 하위 컨트롤을 사용합니다.

QPushButton:open { /* when the button has its menu open */
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #dadbde, stop: 1 #f6f7fa);
}

QPushButton::menu-indicator {
    image: url(menu_indicator.png);
    subcontrol-origin: padding;
    subcontrol-position: bottom right;
}

QPushButton::menu-indicator:pressed, QPushButton::menu-indicator:open {
    position: relative;
    top: 2px; left: 2px; /* shift the arrow by 2 px */
}

체크 가능한 QPushButton 에는 :checked 의사 상태가 설정되어 있습니다.

QRadioButton 사용자 정의

QRadioButton 의 표시기는 다음을 사용하여 변경할 수 있습니다:

QRadioButton::indicator {
    width: 13px;
    height: 13px;
}

QRadioButton::indicator::unchecked {
    image: url(:/images/radiobutton_unchecked.png);
}

QRadioButton::indicator:unchecked:hover {
    image: url(:/images/radiobutton_unchecked_hover.png);
}

QRadioButton::indicator:unchecked:pressed {
    image: url(:/images/radiobutton_unchecked_pressed.png);
}

QRadioButton::indicator::checked {
    image: url(:/images/radiobutton_checked.png);
}

QRadioButton::indicator:checked:hover {
    image: url(:/images/radiobutton_checked_hover.png);
}

QRadioButton::indicator:checked:pressed {
    image: url(:/images/radiobutton_checked_pressed.png);
}

QScrollBar 사용자 정의

QScrollBar 은 핸들, 추가 선, 하위 선 등의 하위 컨트롤을 사용하여 스타일을 지정할 수 있습니다. 한 가지 속성이나 하위 컨트롤을 사용자 정의할 경우, 다른 모든 속성이나 하위 컨트롤도 함께 사용자 정의해야 한다는 점에 유의하십시오.

초록색으로 디자인된 스크롤 바

위의 스크롤 바는 아쿠아마린 색상으로 스타일링되었으며, 회색 실선 테두리가 적용되었습니다.

QScrollBar:horizontal {
    border: 2px solid grey;
    background: #32CC99;
    height: 15px;
    margin: 0px 20px 0 20px;
}
QScrollBar::handle:horizontal {
    background: white;
    min-width: 20px;
}
QScrollBar::add-line:horizontal {
    border: 2px solid grey;
    background: #32CC99;
    width: 20px;
    subcontrol-position: right;
    subcontrol-origin: margin;
}

QScrollBar::sub-line:horizontal {
    border: 2px solid grey;
    background: #32CC99;
    width: 20px;
    subcontrol-position: left;
    subcontrol-origin: margin;
}

왼쪽 화살표와 오른쪽 화살표는 흰색 배경에 회색 실선 테두리가 적용되어 있습니다. 또는 화살표 이미지를 삽입할 수도 있습니다.

QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
    border: 2px solid grey;
    width: 3px;
    height: 3px;
    background: white;
}

QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
    background: none;
}

macOS에서와 같이 스크롤 바의 스크롤 버튼을 가장자리 대신 한 곳에 모아서 배치하려면 다음 스타일시트를 사용할 수 있습니다:

QScrollBar:horizontal {
    border: 2px solid green;
    background: cyan;
    height: 15px;
    margin: 0px 40px 0 0px;
}

QScrollBar::handle:horizontal {
    background: gray;
    min-width: 20px;
}

QScrollBar::add-line:horizontal {
    background: blue;
    width: 16px;
    subcontrol-position: right;
    subcontrol-origin: margin;
    border: 2px solid black;
}

QScrollBar::sub-line:horizontal {
    background: magenta;
    width: 16px;
    subcontrol-position: top right;
    subcontrol-origin: margin;
    border: 2px solid black;
    position: absolute;
    right: 20px;
}

QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
    width: 3px;
    height: 3px;
    background: pink;
}

QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
    background: none;
}

위의 스타일시트를 적용한 스크롤 바는 다음과 같습니다:

색상이 적용된 스크롤 바

수직 스크롤바를 사용자 정의하려면 다음과 유사한 스타일시트를 사용하십시오:

 QScrollBar:vertical {
     border: 2px solid grey;
     background: #32CC99;
     width: 15px;
     margin: 22px 0 22px 0;
 }
 QScrollBar::handle:vertical {
     background: white;
     min-height: 20px;
 }
 QScrollBar::add-line:vertical {
     border: 2px solid grey;
     background: #32CC99;
     height: 20px;
     subcontrol-position: bottom;
     subcontrol-origin: margin;
 }

 QScrollBar::sub-line:vertical {
     border: 2px solid grey;
     background: #32CC99;
     height: 20px;
     subcontrol-position: top;
     subcontrol-origin: margin;
 }
 QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
     border: 2px solid grey;
     width: 3px;
     height: 3px;
     background: white;
 }

 QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
     background: none;
 }

QSizeGrip 사용자 정의

QSizeGrip 는 일반적으로 이미지를 설정하는 것만으로도 스타일을 지정할 수 있습니다.

QSizeGrip {
    image: url(:/images/sizegrip.png);
    width: 16px;
    height: 16px;
}

QSlider 사용자 정의

수평 슬라이더는 다음과 같이 스타일을 지정할 수 있습니다:

QSlider::groove:horizontal {
    border: 1px solid #999999;
    height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);
    margin: 2px 0;
}

QSlider::handle:horizontal {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);
    border: 1px solid #5c5c5c;
    width: 18px;
    margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
    border-radius: 3px;
}

핸들 앞뒤의 슬라이더 부분 색상을 변경하려면 add-page 및 sub-page 하위 컨트롤을 사용할 수 있습니다. 예를 들어, 수직 슬라이더의 경우:

QSlider::groove:vertical {
    background: red;
    position: absolute; /* absolutely position 4px from the left and right of the widget. setting margins on the widget should work too... */
    left: 4px; right: 4px;
}

QSlider::handle:vertical {
    height: 10px;
    background: green;
    margin: 0 -4px; /* expand outside the groove */
}

QSlider::add-page:vertical {
    background: white;
}

QSlider::sub-page:vertical {
    background: pink;
}

QSpinBox 사용자 정의

QSpinBox 아래와 같이 완전히 사용자 정의할 수 있습니다(스타일 시트에는 인라인 주석이 포함되어 있습니다):

QSpinBox {
    padding-right: 15px; /* make room for the arrows */
    border-image: url(:/images/frame.png) 4;
    border-width: 3;
}

QSpinBox::up-button {
    subcontrol-origin: border;
    subcontrol-position: top right; /* position at the top right corner */

    width: 16px; /* 16 + 2*1px border-width = 15px padding + 3px parent border */
    border-image: url(:/images/spinup.png) 1;
    border-width: 1px;
}

QSpinBox::up-button:hover {
    border-image: url(:/images/spinup_hover.png) 1;
}

QSpinBox::up-button:pressed {
    border-image: url(:/images/spinup_pressed.png) 1;
}

QSpinBox::up-arrow {
    image: url(:/images/up_arrow.png);
    width: 7px;
    height: 7px;
}

QSpinBox::up-arrow:disabled, QSpinBox::up-arrow:off { /* off state when value is max */
   image: url(:/images/up_arrow_disabled.png);
}

QSpinBox::down-button {
    subcontrol-origin: border;
    subcontrol-position: bottom right; /* position at bottom right corner */

    width: 16px;
    border-image: url(:/images/spindown.png) 1;
    border-width: 1px;
    border-top-width: 0;
}

QSpinBox::down-button:hover {
    border-image: url(:/images/spindown_hover.png) 1;
}

QSpinBox::down-button:pressed {
    border-image: url(:/images/spindown_pressed.png) 1;
}

QSpinBox::down-arrow {
    image: url(:/images/down_arrow.png);
    width: 7px;
    height: 7px;
}

QSpinBox::down-arrow:disabled,
QSpinBox::down-arrow:off { /* off state when value in min */
   image: url(:/images/down_arrow_disabled.png);
}

QSplitter 사용자 정의

QSplitter 는 QFrame 를 상속하므로 QFrame 와 같은 방식으로 스타일을 지정할 수 있습니다. 그립 또는 핸들은 ::handle 서브컨트롤을 사용하여 사용자 정의합니다.

QSplitter::handle {
    image: url(images/splitter.png);
}

QSplitter::handle:horizontal {
    width: 2px;
}

QSplitter::handle:vertical {
    height: 2px;
}

QSplitter::handle:pressed {
    url(images/splitter_pressed.png);
}

QStatusBar 사용자 정의

다음과 같이 상태 표시줄의 배경과 상태 표시줄 내 항목의 테두리를 설정할 수 있습니다:

QStatusBar {
    background: brown;
}

QStatusBar::item {
    border: 1px solid red;
    border-radius: 3px;
}

QStatusBar 에 추가된 위젯은 하위 클래스 선언(즉)을 사용하여 스타일을 지정할 수 있습니다.

QStatusBar QLabel {
    border: 3px solid white;
}

QTabWidget 및 QTabBar 사용자 정의

여러 개의 탭이 표시된 이미지

위의 스크린샷을 구현하려면 다음과 같은 스타일시트가 필요합니다:

QTabWidget::pane { /* The tab widget frame */
    border-top: 2px solid #C2C7CB;
}

QTabWidget::tab-bar {
    left: 5px; /* move to the right by 5px */
}

/* Style the tab using the tab sub-control. Note that
    it reads QTabBar _not_ QTabWidget */
QTabBar::tab {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
    border: 2px solid #C4C4C3;
    border-bottom-color: #C2C7CB; /* same as the pane color */
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    min-width: 8ex;
    padding: 2px;
}

QTabBar::tab:selected, QTabBar::tab:hover {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #fafafa, stop: 0.4 #f4f4f4,
                                stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);
}

QTabBar::tab:selected {
    border-color: #9B9B9B;
    border-bottom-color: #C2C7CB; /* same as pane color */
}

QTabBar::tab:!selected {
    margin-top: 2px; /* make non-selected tabs look smaller */
}

종종 아래와 같이 탭이 겹치도록 표시해야 할 때가 있습니다:

겹쳐진 탭 이미지

위와 같은 모양의 탭 위젯을 만들려면 음수 여백을 사용합니다. 음수 값을 사용하면 요소가 기본값보다 인접한 요소와 더 가깝게 배치됩니다. 결과적인 스타일시트는 다음과 같습니다:

QTabWidget::pane { /* The tab widget frame */
    border-top: 2px solid #C2C7CB;
}

QTabWidget::tab-bar {
    left: 5px; /* move to the right by 5px */
}

/* Style the tab using the tab sub-control. Note that
    it reads QTabBar _not_ QTabWidget */
QTabBar::tab {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
    border: 2px solid #C4C4C3;
    border-bottom-color: #C2C7CB; /* same as the pane color */
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    min-width: 8ex;
    padding: 2px;
}

QTabBar::tab:selected, QTabBar::tab:hover {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #fafafa, stop: 0.4 #f4f4f4,
                                stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);
}

QTabBar::tab:selected {
    border-color: #9B9B9B;
    border-bottom-color: #C2C7CB; /* same as pane color */
}

QTabBar::tab:!selected {
    margin-top: 2px; /* make non-selected tabs look smaller */
}

/* make use of negative margins for overlapping tabs */
QTabBar::tab:selected {
    /* expand/overlap to the left and right by 4px */
    margin-left: -4px;
    margin-right: -4px;
}

QTabBar::tab:first:selected {
    margin-left: 0; /* the first selected tab has nothing to overlap with on the left */
}

QTabBar::tab:last:selected {
    margin-right: 0; /* the last selected tab has nothing to overlap with on the right */
}

QTabBar::tab:only-one {
    margin: 0; /* if there is only one tab, we don't want overlapping margins */
}

탭 바를 중앙으로 이동시키려면(아래와 같이) 다음과 같은 스타일시트가 필요합니다:

위젯 중앙에 여러 개의 탭 배치

QTabWidget::pane { /* The tab widget frame */
    border-top: 2px solid #C2C7CB;
    position: absolute;
    top: -0.5em;
}

QTabWidget::tab-bar {
    alignment: center;
}

/* Style the tab using the tab sub-control. Note that
    it reads QTabBar _not_ QTabWidget */
QTabBar::tab {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
    border: 2px solid #C4C4C3;
    border-bottom-color: #C2C7CB; /* same as the pane color */
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    min-width: 8ex;
    padding: 2px;
}

QTabBar::tab:selected, QTabBar::tab:hover {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #fafafa, stop: 0.4 #f4f4f4,
                                stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);
}

QTabBar::tab:selected {
    border-color: #9B9B9B;
    border-bottom-color: #C2C7CB; /* same as pane color */
}

찢어진 표시기와 스크롤 버튼은 다음과 같이 추가로 사용자 정의할 수 있습니다:

QTabBar::tear {
    image: url(tear_indicator.png);
}

QTabBar::scroller { /* the width of the scroll buttons */
    width: 20px;
}

QTabBar QToolButton { /* the scroll buttons are tool buttons */
    border-image: url(scrollbutton.png) 2;
    border-width: 2px;
}

QTabBar QToolButton::right-arrow { /* the arrow mark in the tool buttons */
    image: url(rightarrow.png);
}

QTabBar QToolButton::left-arrow {
    image: url(leftarrow.png);
}

닫기 버튼은 다음과 같이 사용자 정의할 수 있습니다:

QTabBar::close-button {
    image: url(close.png)
    subcontrol-position: left;
}
QTabBar::close-button:hover {
    image: url(close-hover.png)
}

QTableView 사용자 정의

QTableView 에서 선택된 항목의 배경을 버블검 핑크에서 흰색으로 서서히 변하는 효과로 설정하고 싶다고 가정해 봅시다.

사용자 정의 스타일이 적용된 테이블 보기

이는 selection-background-color 속성을 사용하여 가능하며, 필요한 구문은 다음과 같습니다:

QTableView {
    selection-background-color: qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,
                                stop: 0 #FF92BB, stop: 1 white);
}

코너 위젯은 다음 스타일 시트를 사용하여 사용자 정의할 수 있습니다.

QTableView QTableCornerButton::section {
    background: red;
    border: 2px outset red;
}

QTableView 의 체크박스 표시기도 사용자 정의할 수 있습니다. 다음 코드 조각에서는 선택 해제 상태의 표시기 background-color 를 사용자 정의하고 있습니다:

QTableView::indicator:unchecked {
    background-color: #d7d6d5
}

QToolBar 사용자 정의

QToolBar 의 배경색과 핸들은 다음과 같이 사용자 정의할 수 있습니다:

QToolBar {
    background: red;
    spacing: 3px; /* spacing between items in the tool bar */
}

QToolBar::handle {
    image: url(handle.png);
}

QToolBox 사용자 정의

QToolBox 의 탭은 'tab' 하위 컨트롤을 사용하여 사용자 정의할 수 있습니다.

QToolBox::tab {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
    border-radius: 5px;
    color: darkgray;
}

QToolBox::tab:selected { /* italicize selected tabs */
    font: italic;
    color: white;
}

QToolButton 사용자 정의

QToolButton에는 세 가지 유형이 있습니다.

QToolButton { /* all types of tool button */
    border: 2px solid #8f8f91;
    border-radius: 6px;
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #f6f7fa, stop: 1 #dadbde);
}

QToolButton[popupMode="1"] { /* only for MenuButtonPopup */
    padding-right: 20px; /* make way for the popup button */
}

QToolButton:pressed {
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #dadbde, stop: 1 #f6f7fa);
}

/* the subcontrols below are used only in the MenuButtonPopup mode */
QToolButton::menu-button {
    border: 2px solid gray;
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
    /* 16px width + 4px for border = 20px allocated above */
    width: 16px;
}

QToolButton::menu-arrow {
    image: url(downarrow.png);
}

QToolButton::menu-arrow:open {
    top: 1px; left: 1px; /* shift it a bit */
}

QToolTip 사용자 정의

QToolTip QLabel 과 똑같은 방식으로 사용자 정의됩니다. 또한, 이를 지원하는 플랫폼의 경우 opacity 속성을 설정하여 투명도를 조절할 수 있습니다.

예를 들어,

QToolTip {
    border: 2px solid darkkhaki;
    padding: 5px;
    border-radius: 3px;
    opacity: 200;
}

QTreeView 사용자 정의

교대로 배치된 행의 배경색은 다음 스타일 시트를 사용하여 사용자 정의할 수 있습니다:

QTreeView {
    alternate-background-color: yellow;
}

항목 위에 마우스를 올렸을 때 특별한 배경을 제공하려면 ::item 하위 컨트롤을 사용할 수 있습니다. 예를 들어,

QTreeView {
    show-decoration-selected: 1;
}

QTreeView::item {
     border: 1px solid #d9d9d9;
    border-top-color: transparent;
    border-bottom-color: transparent;
}

QTreeView::item:hover {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
    border: 1px solid #bfcde4;
}

QTreeView::item:selected {
    border: 1px solid #567dbc;
}

QTreeView::item:selected:active{
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc);
}

QTreeView::item:selected:!active {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6b9be8, stop: 1 #577fbf);
}

QTreeView 의 브랜치는 ::branch 하위 컨트롤을 사용하여 스타일이 지정됩니다. 다음 스타일시트는 브랜치를 그릴 때 다양한 상태에 색상을 지정합니다.

QTreeView::branch {
        background: palette(base);
}

QTreeView::branch:has-siblings:!adjoins-item {
        background: cyan;
}

QTreeView::branch:has-siblings:adjoins-item {
        background: red;
}

QTreeView::branch:!has-children:!has-siblings:adjoins-item {
        background: blue;
}

QTreeView::branch:closed:has-children:has-siblings {
        background: pink;
}

QTreeView::branch:has-children:!has-siblings:closed {
        background: gray;
}

QTreeView::branch:open:has-children:has-siblings {
        background: magenta;
}

QTreeView::branch:open:has-children:!has-siblings {
        background: green;
}

비록 색상이 화려하긴 하지만, 다음 이미지를 사용하면 더 유용한 예제를 만들 수 있습니다:

수직선리스트용 연결선목록을 끝내는 줄오른쪽을 가리키는 화살표아래를 가리키는 화살표
vline.pngbranch-more.pngbranch-end.pngbranch-closed.pngbranch-open.png
QTreeView::branch:has-siblings:!adjoins-item {
    border-image: url(vline.png) 0;
}

QTreeView::branch:has-siblings:adjoins-item {
    border-image: url(branch-more.png) 0;
}

QTreeView::branch:!has-children:!has-siblings:adjoins-item {
    border-image: url(branch-end.png) 0;
}

QTreeView::branch:has-children:!has-siblings:closed,
QTreeView::branch:closed:has-children:has-siblings {
        border-image: none;
        image: url(branch-closed.png);
}

QTreeView::branch:open:has-children:!has-siblings,
QTreeView::branch:open:has-children:has-siblings  {
        border-image: none;
        image: url(branch-open.png);
}

결과적인 트리 뷰는 다음과 같습니다:

스타일이 적용된 가지가 있는 트리 뷰

흔히 저지르는 실수

이 섹션에서는 스타일시트를 사용할 때 흔히 발생하는 실수 몇 가지를 나열합니다.

QPushButton과 이미지

QPushButton 에 스타일을 적용할 때, 버튼 그래픽으로 이미지를 사용하고 싶은 경우가 많습니다. background-image 속성을 사용하는 것이 일반적이지만, 여기에는 몇 가지 단점이 있습니다. 예를 들어, 배경은 배경으로 간주되지 않기 때문에 버튼 장식 뒤에 숨겨져 보이지 않는 경우가 많습니다. 또한, 버튼의 크기가 조정되면 배경 전체가 늘어나거나 반복되어 표시되는데, 이는 항상 보기 좋은 결과를 내지는 않습니다.

border-image 속성을 사용하는 것이 더 낫습니다. 이 속성은 배경과 관계없이 항상 이미지를 표시하며(이미지에 알파 값이 포함되어 있다면 배경과 결합할 수도 있음), 버튼 크기 조정에 대응하는 특별한 설정도 갖추고 있기 때문입니다.

다음 코드 조각을 살펴보세요:

        QPushButton {
            color: grey;
            border-image: url(/home/kamlie/code/button.png) 3 10 3 10;
            border-top: 3px transparent;
            border-bottom: 3px transparent;
            border-right: 10px transparent;
            border-left: 10px transparent;
        }

이렇게 하면 다음과 같은 모양의 버튼이 생성됩니다:

배경이 있는 버튼

URL 뒤의 숫자는 각각 상단, 우측, 하단, 좌측의 픽셀 수를 나타냅니다. 이 숫자들은 테두리에 해당하며, 크기가 변경되어도 늘어나지 않아야 합니다. 버튼 크기를 조정할 때마다 이미지의 중앙 부분은 양방향으로 늘어나지만, 스타일시트에 지정된 픽셀 값은 늘어나지 않습니다. 이를 통해 버튼의 테두리가 다음과 같이 더 자연스럽게 보입니다:

테두리 크기가 지정된 버튼

테두리가 있는 경우

테두리 크기가 지정되지 않은 버튼

테두리 없음

관련 항목: ` Qt Widgets ` 스타일링 기법, 지원되는 HTML 하위 집합, ` QStyle`.

© 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.