PyQt5 Tutorial - 파이썬으로 만드는 나만의 GUI 프로그램
https://wikidocs.net/book/2165
초보자를 위한 Python GUI 프로그래밍 - PyQt5
https://study-code.gitbook.io/python-basic/
Real Python
https://realpython.com/qt-designer-python/#getting-started-with-qt-designer
사용자 정의 시그널(Custom Signal)과 Emit 사용법
https://ybworld.tistory.com/110
QPushButton
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
btn1 = QPushButton("닫기", self)
btn1.move(20, 20)
btn1.clicked.connect(QCoreApplication.instance().quit) # 위젯 닫기 = app.quit
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
QLabel
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 400, 300, 150)
textLabel = QLabel("Message: ", self)
textLabel.move(20, 20)
self.label = QLabel("", self)
self.label.move(80, 20)
self.label.resize(150, 30)
btn1 = QPushButton("Click", self)
btn1.move(20, 60)
btn1.clicked.connect(self.btn1_clicked)
btn2 = QPushButton("Clear", self)
btn2.move(140, 60)
btn2.clicked.connect(self.btn2_clicked)
def btn1_clicked(self):
self.label.setText("버튼이 클릭되었습니다.")
def btn2_clicked(self):
self.label.clear()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
app.exec_()
QLineEdit 와 QStatusBar
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 400, 300, 150)
label = QLabel("종목코드 : ", self)
label.move(20, 20)
# textChanged() : QLineEdit 객체에서 텍스트가 변경될 때 발생
# returnPressed() : QLineEdit 객체를 통해 사용자가 엔터키를 눌렀을 때
self.lineEdit = QLineEdit('',self)
self.lineEdit.move(80, 20)
self.lineEdit.textChanged.connect(self.lineEditChanged)
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar) # 상태바 위치 고정
def lineEditChanged(self):
self.statusBar.showMessage(self.lineEdit.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
app.exec_()
QRadioButton과 QGroupBox
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 400, 300, 300)
groupBox = QGroupBox("시간 단위",self)
groupBox.move(10, 10)
groupBox.resize(280, 80)
self.radio1 = QRadioButton("일봉", self)
self.radio1.move(20, 20)
self.radio1.setChecked(True)
self.radio1.clicked.connect(self.radioButtonClicked)
self.radio2 = QRadioButton("주봉", self)
self.radio2.move(20, 40)
self.radio2.clicked.connect(self.radioButtonClicked)
self.radio3 = QRadioButton("월봉", self)
self.radio3.move(20, 60)
self.radio3.clicked.connect(self.radioButtonClicked)
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar)
def radioButtonClicked(self):
msg = ""
if self.radio1.isChecked():
msg = "일봉"
elif self.radio2.isChecked():
msg = "주봉"
else:
msg = "월봉"
self.statusBar.showMessage(msg + "선택 됨")
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
app.exec_()
QCheckBox
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 400, 300, 300)
groupBox = QGroupBox('이동평균선', self)
groupBox.move(10, 10)
groupBox.resize(280, 80)
self.checkBox1 = QCheckBox("5일 이동평균선", self)
self.checkBox1.move(10, 20)
self.checkBox1.resize(150, 30)
self.checkBox1.stateChanged.connect(self.checkBoxState)
self.checkBox2 = QCheckBox("20일 이동평균선", self)
self.checkBox2.move(10, 50)
self.checkBox2.resize(150, 30)
self.checkBox2.stateChanged.connect(self.checkBoxState)
self.checkBox3 = QCheckBox("60일 이동평균선", self)
self.checkBox3.move(10, 80)
self.checkBox3.resize(150, 30)
self.checkBox3.stateChanged.connect(self.checkBoxState)
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar)
def checkBoxState(self):
msg = ""
if self.checkBox1.isChecked():
msg += "5일 "
if self.checkBox2.isChecked():
msg += "20일 "
if self.checkBox3.isChecked():
msg += "60일 "
self.statusBar.showMessage(msg)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
QSpinBox
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 400, 300, 300)
label = QLabel("매도수량: ", self)
label.move(10, 20)
self.spinBox = QSpinBox(self)
self.spinBox.move(70, 25)
self.spinBox.resize(80, 22)
self.spinBox.setValue(10)
self.spinBox.setSingleStep(10)
self.spinBox.setMinimum(1)
self.spinBox.setMaximum(10000)
self.spinBox.valueChanged.connect(self.spinBoxChanged)
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar)
def spinBoxChanged(self):
val = self.spinBox.value()
msg = '%d 주를 매도합니다.' %val
self.statusBar.showMessage(msg)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
QTableWidget
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
kospi_top5 = {
'code': ['005930', '015760', '005380', '090430', '012330'],
'name': ['삼성전자', '한국전력', '현대차', '아모레퍼시픽', '현대모비스'],
'cprice': ['1,269,000', '60,100', '132,000', '414,500', '243,500']
}
column_idx_lookup = {'code': 0, 'name': 1, 'cprice': 2}
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 300)
self.tableWidget = QTableWidget(self)
self.tableWidget.resize(290, 290)
self.tableWidget.setRowCount(5)
self.tableWidget.setColumnCount(3)
self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 아이템 항목 수정 불가 설정
self.setTableWidgetData()
def setTableWidgetData(self):
column_headers = ['종목코드', '종목명', '종가']
self.tableWidget.setHorizontalHeaderLabels(column_headers)
for k, v in kospi_top5.items():
col = column_idx_lookup[k]
for row, val in enumerate(v):
item = QTableWidgetItem(val)
self.tableWidget.setItem(row, col, item)
if col != 2:
item.setTextAlignment(Qt.AlignHCenter + Qt.AlignVCenter) # 우측 정렬, vertical 가운데 정렬
else:
item.setTextAlignment(Qt.AlignRight + Qt.AlignVCenter) # 우측 정렬, vertical 가운데 정렬
# 행과 열 크기를 각 위치에 저장된 아이템 길이에 맞춰 조정
self.tableWidget.resizeColumnsToContents()
self.tableWidget.resizeRowsToContents()
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
Layout
위젯의 크기를 변경 : resize 메서드
위젯의 위치를 설정 : move 메서드
위젯의 출력 크기 , 위치를 설정 : setGeometry 메서드
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget): #QWidget을 상속함
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 300)
self.textEdit = QTextEdit(self)
self.textEdit.resize(280, 250)
self.textEdit.move(10, 10)
self.pushButton= QPushButton('저장', self)
self.pushButton.resize(280, 25)
self.pushButton.move(10, 270)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
레이아웃 매니저 : 윈도우의 크기를 자유롭게 변경해도 내부 위젯이 일정한 비율을 가지며 크기가 자동으로 바뀜 QVBoxLayout, QHBoxLayout, QBoxLayout, QGridLayout, QLayout
# 레이아웃 매니저에 추가되는 위젯을 생성할 때는 부모 위젯을 지정할 필요가 없으며,
위젯의 크기나 위치를 명시적으로 설정하지 않아야 한다는 점입니다.
[ 작업순서]
1) 추가될 위젯 만들기
2) 레이아웃 매니저 만들기
3) addWidget 메서드를 이용한 위젯 등록
4) 레이아웃 매니저 등록
QVBoxLayout
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 300)
self.textEdit = QTextEdit()
self.pushButton= QPushButton('저장')
layout = QVBoxLayout()
layout.addWidget(self.textEdit)
layout.addWidget(self.pushButton)
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
QHBoxLayout
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 100)
self.pushButton1= QPushButton("Button1")
self.pushButton2= QPushButton("Button2")
self.pushButton3= QPushButton("Button3")
layout = QHBoxLayout()
layout.addWidget(self.pushButton1)
layout.addWidget(self.pushButton2)
layout.addWidget(self.pushButton3)
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
QGridLayout
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 100)
self.label1 = QLabel("ID: ")
self.label2 = QLabel("Password: ")
self.lineEdit1 = QLineEdit()
self.lineEdit2 = QLineEdit()
self.pushButton1= QPushButton("Sign In")
layout = QGridLayout()
layout.addWidget(self.label1, 0, 0)
layout.addWidget(self.lineEdit1, 0, 1)
layout.addWidget(self.pushButton1, 0, 2)
layout.addWidget(self.label2, 1, 0)
layout.addWidget(self.lineEdit2, 1, 1)
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
레이아웃 중첩
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 500, 300)
groupBox = QGroupBox("검색옵션")
checkBox1 = QCheckBox("상한가")
checkBox2 = QCheckBox("하한가")
checkBox3 = QCheckBox("시가총액 상위")
checkBox4 = QCheckBox("시가총액 하위")
checkBox5 = QCheckBox("회전율 상위")
checkBox6 = QCheckBox("대량거래상위")
checkBox7 = QCheckBox("환산주가상위")
checkBox8 = QCheckBox("외국인한도소진상위")
checkBox9 = QCheckBox("투자자별순위")
tableWidget = QTableWidget(10, 5)
tableWidget.setHorizontalHeaderLabels(["종목코드", "종목명", "현재가", "등락률", "거래량"])
tableWidget.resizeColumnsToContents()
tableWidget.resizeRowsToContents()
leftInnerLayOut = QVBoxLayout()
leftInnerLayOut.addWidget(checkBox1)
leftInnerLayOut.addWidget(checkBox2)
leftInnerLayOut.addWidget(checkBox3)
leftInnerLayOut.addWidget(checkBox4)
leftInnerLayOut.addWidget(checkBox5)
leftInnerLayOut.addWidget(checkBox6)
leftInnerLayOut.addWidget(checkBox7)
leftInnerLayOut.addWidget(checkBox8)
leftInnerLayOut.addWidget(checkBox9)
groupBox.setLayout(leftInnerLayOut)
leftLayOut = QVBoxLayout()
leftLayOut.addWidget(groupBox)
rightLayOut = QVBoxLayout()
rightLayOut.addWidget(tableWidget)
layout = QHBoxLayout()
layout.addLayout(leftLayOut)
layout.addLayout(rightLayOut)
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
다이얼로그
QFileDialog
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 300)
self.setWindowTitle("PyStock v0.1")
self.pushButton = QPushButton("File Open")
self.pushButton.clicked.connect(self.pushButtonClicked)
self.label = QLabel()
layout = QVBoxLayout()
layout.addWidget(self.pushButton)
layout.addWidget(self.label)
self.setLayout(layout)
def pushButtonClicked(self):
fname = QFileDialog.getOpenFileName(self)
self.label.setText(fname[0])
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
QInputDialog
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 300)
self.setWindowTitle("PyStock v0.1")
self.pushButton = QPushButton("Input number")
self.pushButton.clicked.connect(self.pushButtonClicked)
self.label = QLabel()
self.pushButton1 = QPushButton("Input number")
self.pushButton1.clicked.connect(self.pushButtonClicked1)
self.label1 = QLabel()
layout = QVBoxLayout()
layout.addWidget(self.pushButton)
layout.addWidget(self.pushButton1)
layout.addWidget(self.label)
layout.addWidget(self.label1)
self.setLayout(layout)
def pushButtonClicked(self):
# 입력한 값,OK 버튼을 누른 경우에 True
# =QInputDialog.getInt(부모 위젯, 제목 텍스트, 창 내부에 출력될 텍스트)
text, ok = QInputDialog.getInt(self, '매수 수량', '매수 수량을 입력하세요.') #getDouble,getText,getItem
if ok:
self.label.setText(str(text))
def pushButtonClicked1(self):
items = ("KOSPI", "KOSDAK", "KONEX")
# 입력한 값,OK 버튼을 누른 경우에 True
# =QInputDialog.getItem(부모 위젯, 제목 텍스트, 창 내부에 출력될 텍스트,초기 item index,item 수정가능 여부)
item, ok = QInputDialog.getItem(self, "시장선택", "시장을 선택하세요.", items, 0, False)
if ok and item:
self.label.setText(item)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
메인 윈도우와 다이얼로그의 상호 작용
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class LogInDialog(QDialog):
def __init__(self):
super().__init__()
self.setupUI()
self.id = None
self.password = None
def setupUI(self):
self.setGeometry(1100, 200, 300, 100)
self.setWindowTitle("Sign In")
# self.setWindowIcon(QIcon('icon.png'))
label1 = QLabel("ID: ")
label2 = QLabel("Password: ")
self.lineEdit1 = QLineEdit()
self.lineEdit2 = QLineEdit()
self.pushButton1= QPushButton("Sign In")
self.pushButton1.clicked.connect(self.pushButtonClicked)
layout = QGridLayout()
layout.addWidget(label1, 0, 0)
layout.addWidget(self.lineEdit1, 0, 1)
layout.addWidget(self.pushButton1, 0, 2)
layout.addWidget(label2, 1, 0)
layout.addWidget(self.lineEdit2, 1, 1)
self.setLayout(layout)
def pushButtonClicked(self):
self.id = self.lineEdit1.text()
self.password = self.lineEdit2.text()
self.close()
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(800, 200, 300, 300)
self.setWindowTitle("PyStock v0.1")
# self.setWindowIcon(QIcon('icon.png'))
self.pushButton = QPushButton("Sign In")
self.pushButton.clicked.connect(self.pushButtonClicked)
self.label = QLabel()
layout = QVBoxLayout()
layout.addWidget(self.pushButton)
layout.addWidget(self.label)
self.setLayout(layout)
def pushButtonClicked(self):
dlg = LogInDialog()
dlg.exec_()
id = dlg.id
password = dlg.password
self.label.setText("id: %s \npassword: %s" % (id, password))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
'PyQt5' 카테고리의 다른 글
사용자 정의 Signal (0) | 2022.04.30 |
---|---|
Qt5 예제 (0) | 2022.03.21 |
[PyQt] PyQt Designer (0) | 2022.02.21 |
댓글