Python/PyQt5
PyQt5: QComboBox 사용하기
editor752
2019. 11. 20. 08:15
이 글은 Codetorial의 PyQt5, 초보자를 위한 Python GUI 프로그래밍-PyQt5 등을 학습하는 과정을 기록한 것이다. 강좌 자체는 해당 사이트를 참고하기 바란다.
QComboBox는 공간 절약의 미학을 갖춘 위젯일까? 이 위젯은 작은 공간을 차지하면서, 여러 옵션들을 제공하고(팝업되고) 그 중 하나의 옵션을 선택할 수 있도록 해준다.
옵션 가운데 하나가 선택되면 activaed(const QString &text)
시그널이 발생한다. 이 시그널은 옵션의 문자열을 인자로 전달한다. 아래의 코드에서는 activated[str]
방식으로 사용되었다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import sys from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QComboBox class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # QLabel을 초기화할 때 반드시 self를 붙여야 한다. self.lbl = QLabel("Option", self) self.lbl.move(50, 150) # QComboBox 인스턴스를 생성하고 옵션을 4개 추가한다. cb = QComboBox(self) cb.addItem('Option1') cb.addItem('Option2') cb.addItem('Option3') cb.addItem('Option4') cb.move(50, 50) # activated[str]은 QComboBox의 옵션의 문자열을 받아 전달한다. cb.activated[str].connect(self.onActivated) # 하나의 시그널에 두 개의 슬롯을 연결할 수 있다. cb.activated[str].connect(self.printed) self.setWindowTitle('QComboBox') self.setGeometry(300, 300, 300, 200) self.show() # QComboBox에서 선택된 옵션의 문자열이 인자 text를 통해 전달됨. def onActivated(self, text): # QLabel의 문자열을 text로 설정한다. self.lbl.setText(text) # text의 길이에 맞춰 QLabel의 크기를 자동으로 조정한다. self.lbl.adjustSize() def printed(self, text): print(text) if __name__ == '__main__': app = QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_()) | cs |
실행화면
이 코드를 QtDesigner를 이용하여 ui와 코드를 분리하연 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import sys from PyQt5.QtWidgets import * from PyQt5 import uic form_class = uic.loadUiType('QComboBox01.ui')[0] class MyWindow(QWidget, form_class): def __init__(self): super().__init__() self.setupUi(self) def onActivated(self, text): self.lbl.setText(text) self.lbl.adjustSize() def printed(self, text): print(text) if __name__ == '__main__': app = QApplication(sys.argv) ex = MyWindow() ex.show() sys.exit(app.exec_()) | cs |
사용한 ui 파일은 아래에 첨부하였다.QComboBox01.ui
2.0 kB