본문 바로가기

Python

[QT] 버튼 클릭 시 감소

Anaconda3를 제대로 깔았다면,

cmd 창에서 designer를 입력 하면 Qt Designer를 사용할 수 있다.

위지위그(WYSIWYG)란?

What You See Is What You Get의 약자로, 문서 및 문서 작성 방법을 GUI로 구현한 것을 말한다.

쉽게 말해, Qt Designer에서 버튼이나, 텍스트 박스 등을 드래그 해 일일히 코드를 작성하지 않고도 자동으로 원하는 형태의 화면을 만들어 줄 수 있다.

 

위처럼 화면을 만들 때, 각 항목에 id를 줄 수 있다.(jsp와 매우 비슷하다.) 

이제 이 ui 파일을 이클립스로 가져와 python 코드와 함께 사용할 수 있다.

myqt02.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>586</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLineEdit" name="le">
    <property name="geometry">
     <rect>
      <x>100</x>
      <y>80</y>
      <width>113</width>
      <height>20</height>
     </rect>
    </property>
    <property name="text">
     <string>100</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pb">
    <property name="geometry">
     <rect>
      <x>220</x>
      <y>80</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>DECREASE</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

내가 만든 gui에 대한 코드를 알아서 작성해준다.

 

이제 파이썬 코드에서 이 툴을 실행시켜주면 된다.

import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow

form_class = uic.loadUiType("myqt02.ui")[0]


class WindowClass(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pb.clicked.connect(self.btnClick)
        
    def btnClick(self):
        a = int(self.le.text())
        self.le.setText(str(a-1))
            


if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = WindowClass()
    myWindow.show()
    app.exec_()

실행된 화면

나는 버튼(pushButton)의 id값을 pb로 주고, QLineEdit의 id값도 le로 주었는데,

 pb 버튼에 대한 이벤트를 지정해 주고,

self.pb.clicked.connect(self.btnClick)

해당 이벤트를 정의해주었다.

def btnClick(self):
     a = int(self.le.text())
     self.le.setText(str(a-1))

 

'Python' 카테고리의 다른 글

[QT] 구구단 출력하기  (0) 2023.06.28
[QT] 로또 만들기  (0) 2023.06.28
[Python] 홀 짝 게임  (0) 2023.06.28
[Python] 가위 바위 보 게임  (0) 2023.06.28
[Python] 로또 프로그램 만들기  (0) 2023.06.28