ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Day 4. PyQt5 (QCheckBox, QComboBox)
    <개인공부> - IT/[Python] 2021. 3. 5. 22:35
    반응형

    QCheckBox는 이름에서도 알 수 있듯이 체크가 가능한 박스가 있는 위젯을 말한다.

    가장 간단한 예로 체크가 되어있는 것과 체크가 되어있지 않은 것 이분법적으로 접근할 경우 사용가능한 위젯이다.

    import sys
    
    from PyQt5.QtCore import Qt
    from PyQt5.QtWidgets import QApplication, QMainWindow, QCheckBox
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("My App")
    
            widget = QCheckBox("This is a checkbox")
            widget.setCheckState(Qt.Checked)
            #widget.setCheckState(Qt.PartiallyChecked)
            widget.stateChanged.connect(self.show_state)
            
            self.setCentralWidget(widget)
    
        def show_state(self, s):
            print(s == Qt.Checked)
            print(s)
    
    app = QApplication(sys.argv)
    
    window = MainWindow()
    window.show()
    
    app.exec_()

    해당 코드를 실행하게 되면 아래와 같이 체크 또는 언체크 할 수 있는 위젯이 표시된다. 또는 Qt.PartiallyChecked flag를 이용하면 아래 그림과 같이 세 가지 상태를 같은 체크박스 위젯을 확인할 수 있다.

     

    왼쪽. 두 가지 상태를 갖는 체크박스, 오른쪽 세 가지 상태를 갖는 체크박스

    그리고 체크, 언체크를 반복하다 보면 재미있는 것을 발견할 수 있다. 체크가 된 경우 2, 언체크가 되면 0으로 표현된다. C언어처럼 False는 0이고 True면 1 아니었나라는 궁금증이 생길 수 있는데 그 이유는 Tri-state이 존재하기 때문이다. 위의 코드에서 주석처리한 라인을 확인하면 Qt.PartiallyChecked라는 값을 전달하고 있다.  개인적으로는 엑셀 사용중 종종 본 Tri-state의 체크박스인데 이 것은 True/False 또는 On/Off 가 아닌 Greyed out된 형태로 표시된다. 

     


     

    QComboBox는 드랍다운 리스트이다. 이 것을 펼치려면 화살표 버튼을 눌러 전체 리스트를 확인이 가능하고 그 리스트 중에 한 아이템을 선택할 수 있는 위젯이다. 그리고 선택한 아이템은 이 콤보박스 위젯에 표현된다. 엑셀이나 워드를 사용할 때 폰트나 글자의 크기를 고를 때 우리가 사용하는 위젯이 그 예이다.

    import sys
    
    from PyQt5.QtCore import Qt
    from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("My App")
    
            widget = QComboBox()
            widget.addItems(["One", "Two", "Three"])
            widget.currentIndexChanged.connect(self.index_changed)
            widget.currentTextChanged.connect(self.text_changed)
            
            self.setCentralWidget(widget)
    
        def index_changed(self, i):
            print(i)
        def text_changed(self, s):
            print(s)
    
    app = QApplication(sys.argv)
    
    window = MainWindow()
    window.show()
    
    app.exec_()

    현재 선택된 (보이는) 아이템이 변경되면 currentIndexChanged와 currentTextChanged라는 시그널이 트리거되며 선택된 아이템의 index가 전달된다. QComboBox는 사용자에게 수정이 가능할 수 있도록 만드는 옵션도 존재한다.

    widget.setEditable(True) 라는 옵션을 통해서 현재 리스트에 없는 아이템을 추가할 수 있다. 이와 함께 사용될 수 있는 policy를 지정해주어야 하는데 7가지의 flag가 아래와 같이 존재한다.

     

    Flag 동작
    QComboBox.NoInsert 추가기능 off
    QComboBox.InsertAtTop 리스트의 가장 처음에 삽입
    QComboBox.InsertAtCurrent 현재 선택된 값을 입력값으로 변경
    QComboBox.InsertAtBottom 리스트의 가장 마지막에 삽입
    QComboBox.InsertAfterCurrent 현재 선택된 값의 바로 뒤에 삽입
    QComboBox.InsertBeforeCurrent 현재 선택된 값의 바로 앞에 삽입
    QComboBox.InsertAlphabetically 알파벳 순서로 삽입

     

    위에서 설명한 flag 적용을 위해서는

    widget.setInsertPolicy(QComboBox.InsertAlphabetically) 와 같이 사용하면 된다.

     

    1. Reference book: "Create GUI Applications with Python & Qt5: The hands-on guide to making apps with Python"

    반응형
Designed by Tistory.