본문으로 바로가기
반응형

QComboBox 는 사용자가 여러 개의 값들 중에서 하나를 선택할 수 있게 제공하는 컨트롤입니다. QComboBox 의 이벤트를 받아 현재 선택한 값을 표현하거나 콤보박스 안에 값을 추가/삭제 하는 기능을 구현해 보겠습니다.

 

1. QComboBox 에 선택한 값 QLable 에 표시하기

 

먼저 QComboBox 를 추가합니다. 클래스는 QtWidgets 패키지에 있습니다. 콤보박스의 선택 시그널은 currentTextChanged 입니다. 여기에 combobox_select() 슬롯을 연결했습니다.

from PyQt5.QtWidgets import QComboBox

# QComboBox 위젯 생성
self.combo = QComboBox(self)
self.combo.currentTextChanged.connect(self.combobox_select)
self.combo.setGeometry(10, 10, 100, 30)

 

다음은 콤보박스에서 선택한 값을 화면에 표시할 QLabel 위젯의 객체를 생성합니다.

from PyQt5.QtWidgets import QLabel

# QLabel 에서 선택한 값 표시
self.combo_label = QLabel(self)
self.combo_label.setGeometry(150, 10, 50, 30)

 

QComboBox 에 연결한 combobox_select() 의 구현 내용은 다음과 같습니다. QComboBox 객체에서 currentText() 함수를 이용해 값을 가져옵니다. 그리고 QLabel 객체인 combo_label 에 콤보박스의 값을 표현합니다. 사용한 함수는 setText() 입니다.

# ComboBox 선택 이벤트
@pyqtSlot()
def combobox_select(self):
    # QLabel 에 표시
    self.combo_label.setText(self.combo.currentText())
    print(self.combo.currentText())
    print(self.combo.currentIndex())

 

2. QComboBox 에 값 추가하기

 

QComboBox 에 값을 추가하는 기능을 구현하기 위해서는 두 개의 위젯이 필요합니다. QLineEdit QPushButton 입니다. QLineEdit 에 값을 입력받아 QPushButton 버튼으로 QComboBox 에 값을 추가할 것입니다. 먼저 데이터를 입력 받을 QLineEdit 위젯의 객체를 만듭니다. QLineEdit QtWidgets 에 포함되어 있습니다.

from PyQt5.QtWidgets import QLineEdit

# 콤보박스에 추가할 데이터 입력
self.input_text = QLineEdit(self)
self.input_text.setGeometry(10, 60, 100, 30)

 

다음은 QComboBox 에 값을 추가할 버튼을 생성합니다. 버튼의 clicked 에는 add_data_combobox() 슬롯을 연결했습니다. 해당 슬롯에는 QLineEdit 에 입력한 값을 가져와서 QComboBox 에 추가하는 기능이 들어가 있습니다.

from PyQt5.QtWidgets import QPushButton

# 콤보박스에 데이터 추가
self.add_button = QPushButton('Add', self)
self.add_button.clicked.connect(self.add_data_combobox)
self.add_button.setGeometry(120, 60, 100, 30)

 

add_data_combobox() 은 다음과 같습니다. QLineEdit 객체인 input_text text() 함수를 이용해서 값을 가져옵니다. 그리고 가져온 값을 QComboBox addItem() 을 이용해서 추가합니다. 값은 목록 제일 하단에 들어갑니다. 값 입력이 끝나면 QLineEdit clear() 함수를 이용해서 이전 입력한 값은 삭제합니다.

# 버튼 클릭하면 ComboBox 에 값 추가
@pyqtSlot()
def add_data_combobox(self):
    self.combo.addItem(self.input_text.text())
    print(self.input_text.text())
    self.input_text.clear()

 

3. 2. QComboBox 에 값 삭제하기

 

콤보박스에 값을 추가하는 것처럼 값을 삭제하기 위한 버튼을 추가합니다. QPushButton 버튼의 이름을 “Remove” 로 하고 객체를 생성합니다. QPushButton clicked 시그널에 연결한 슬롯은 remove_data_combobox() 입니다.

# 삭제 버튼
self.add_button = QPushButton('Remove', self)
self.add_button.clicked.connect(self.remove_data_combobox)
self.add_button.setGeometry(230, 60, 100, 30)

 

remove_data_combobox() 에서는 콤보박스의 값을 삭제합니다. 사용함수는 removeItem() 입니다. 파라미터에는 삭제할 값의 위치에 해당하는 숫자값을 넘깁니다. 이것을 인덱스 값이라고 하는데, 현재 콤보박스에서 보고 있는 값의 인덱스는 currentIndex() 함수로 알 수 있습니다.

@pyqtSlot()
def remove_data_combobox(self):
    self.combo.removeItem(self.combo.currentIndex())

 

선택한 A 값을 삭제한 결과는 다음과 같습니다. 콤보박스를 열어 보면 A 데이터가 보이지 않습니다.

반응형