Skip to content
toylee blog · 컴퓨터, 프로그램 정보 공유

toylee blog · 컴퓨터, 프로그램 정보 공유

PyQt6 신호 및 슬롯, 이벤트

toylee, 2023년 05월 17일

GUI 프로그래밍에서 이벤트 처리는 매우 중요합니다. 사용자가 애플리케이션에서 어떤 작업을 수행할 때마다, 그 작업은 이벤트로 인식됩니다. 이벤트에는 버튼 클릭, 마우스 이동, 키 입력 등이 포함됩니다. PyQt6는 이벤트 처리에 대한 강력한 지원을 제공합니다. 이번 게시물에서는 PyQt6 신호 및 슬롯 메커니즘에 대해 살펴보고, 이를 사용하여 이벤트 처리를 어떻게 수행할 수 있는지에 대해 자세히 알아보겠습니다.

[목차]

  • 1. PyQt6 신호 및 슬롯?
  • 2. PyQt6 이벤트 처리
  • 3. PyQt6 key 이벤트
  • 4. PyQt6 신호 및 슬롯, 이벤트 – 결론

1. PyQt6 신호 및 슬롯?

PyQt6에서 신호와 슬롯은 이벤트 처리를 위한 메커니즘입니다. 신호는 이벤트가 발생했음을 나타내는 것이고, 슬롯은 이벤트를 처리하는 메서드입니다. 이 메커니즘은 시그널-슬롯 메커니즘이라고도 불립니다.

예를 들어, 버튼을 클릭하면 QPushButton 클래스의 clicked 시그널이 발생합니다. 이 시그널은 사용자가 버튼을 클릭했음을 나타냅니다. QPushButton 클래스에는 clicked 시그널을 처리하는 슬롯인 clicked 메서드가 포함되어 있습니다. 이 메서드는 버튼이 클릭되었을 때 호출됩니다.

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 PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton
 
 
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle(‘Button example’)
 
        # Create a QPushButton widget and set its text label
        btn = QPushButton(‘Click me’, self)
        btn.setGeometry(50, 50, 100, 50)
 
        # Connect the clicked signal of the QPushButton to its built-in clicked slot
        btn.clicked.connect(btn.clicked.emit)
 
        self.show()
 
 
if __name__ == ‘__main__’:
    app = QApplication(sys.argv)
    ex = MyWindow()
    sys.exit(app.exec())
 
Colored by Color Scripter
cs

[실행화면]

pyqt6 신호 및 슬롯 1

PyQt6에서는 다양한 형태의 시그널과 슬롯을 정의할 수 있습니다. 예를 들어, 다음과 같이 정수형과 문자열형 인자를 가지는 시그널과 이를 처리하는 슬롯을 정의할 수 있습니다.

1
2
3
4
5
6
7
8
class MyClass(QObject):
    my_signal = pyqtSignal(int, str)
 
    def __init__(self):
        super().__init__()
 
    def my_slot(self, value1, value2):
        print(value1, value2)
cs

my_signal은 int와 str 두 가지 인수를 가지는 신호입니다. my_slot은 my_signal을 처리하는 슬롯입니다. 이제 my_signal을 발생시키면 my_slot이 호출됩니다.

[전체코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import sys
from PyQt6.QtCore import QObject, pyqtSignal
from PyQt6.QtWidgets import QApplication
 
 
class MyClass(QObject):
    my_signal = pyqtSignal(int, str)
 
    def __init__(self):
        super().__init__()
 
    def my_slot(self, value1, value2):
        print(value1, value2)
 
 
if __name__ == ‘__main__’:
    app = QApplication(sys.argv)
 
    obj = MyClass()
    obj.my_signal.connect(obj.my_slot)
    obj.my_signal.emit(10, ‘Hello World’)
 
    sys.exit(app.exec())
 
Colored by Color Scripter
cs

[실행화면]

pyqt6 신호 및 슬롯 2

2. PyQt6 이벤트 처리

PyQt6에서는 다양한 이벤트를 처리할 수 있습니다. 예를 들어, 버튼을 클릭하거나 마우스를 움직이는 등의 이벤트를 처리할 수 있습니다. 이벤트를 처리하는 방법은 다음과 같습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        button = QPushButton(‘Click me’, self)
        button.move(50, 50)
        button.clicked.connect(self.on_click)
 
    def on_click(self):
        print(‘Clicked’)
 
Colored by Color Scripter
cs

QPushButton을 생성하고 clicked 시그널을 on_click 슬롯에 연결합니다. on_click 메서드는 버튼이 클릭되었을 때 호출됩니다. 이제 버튼을 클릭하면 ‘Clicked’가 출력됩니다.

[전체코드]

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
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton
 
 
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        button = QPushButton(‘Click me’, self)
        button.move(50, 50)
        button.clicked.connect(self.on_click)
 
    def on_click(self):
        print(‘Clicked’)
 
 
if __name__ == ‘__main__’:
    app = QApplication(sys.argv)
    ex = MyWidget()
    ex.show()
    sys.exit(app.exec())
    
 
Colored by Color Scripter
cs

[실행화면]

pyqt6 신호 및 슬롯 3

PyQt6에서는 다양한 이벤트 처리 메커니즘이 있습니다. 예를 들어, QAction 클래스에서는 triggered 시그널과 이를 처리하는 슬롯인 triggered 메서드를 제공합니다. 이 메서드는 사용자가 액션을 선택할 때 호출됩니다.

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
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtGui import QAction
 
 
class MyMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        # Create a QAction instance with label and parent
        action = QAction(‘Say hello’, self)
        # Connect the triggered signal of the QAction to the say_hello slot
        action.triggered.connect(self.say_hello)
        # Add the QAction to the File menu
        file_menu = self.menuBar().addMenu(‘File’)
        file_menu.addAction(action)
 
    def say_hello(self):
        print(‘Hello, world!’)
 
 
if __name__ == ‘__main__’:
    app = QApplication(sys.argv)
    window = MyMainWindow()
    window.show()
    sys.exit(app.exec())
 
Colored by Color Scripter
cs

[실행화면]

pyqt6 say hello

3. PyQt6 key 이벤트

PyQt6에서는 키 이벤트도 처리할 수 있습니다. 예를 들어, 다음과 같이 키보드의 Enter 키를 눌렀을 때 실행되는 이벤트 처리를 구현할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle(‘Key event’)
        self.show()
 
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Return:
            print(‘Enter key pressed’)
 
Colored by Color Scripter
cs

keyPressEvent 메서드를 오버라이드하여 키 이벤트를 처리합니다. 이제 Enter 키를 누르면 ‘Enter key pressed’가 출력됩니다.

[전체코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6.QtCore import Qt
 
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle(‘Key event’)
        self.show()
 
    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_Return:
            print(‘Enter key pressed’)
 
if __name__ == ‘__main__’:
    app = QApplication([])
    widget = MyWidget()
    app.exec()
 
Colored by Color Scripter
cs

[실행화면]

pyqt6 key event

4. PyQt6 신호 및 슬롯, 이벤트 – 결론

PyQt6 신호 및 슬롯 메커니즘은 이벤트 처리를 간단하게 만드는 강력한 도구입니다. 이번 게시물에서는 PyQt6에서 신호와 슬롯을 사용하여 이벤트를 처리하는 방법에 대해 알아보았습니다. 이를 기반으로 PyQt6를 사용하여 다양한 유형의 이벤트를 처리할 수 있을 것입니다. 사용자 정의 pyqt6 Signals and Slots 구현하여 더욱 많은 이벤트 처리 기능을 구현할 수 있습니다.

키 이벤트도 PyQt6에서 처리할 수 있습니다. 이러한 기능들을 이용하면 더욱 다양하고 효과적인 GUI 프로그래밍을 구현할 수 있습니다.

[관련글]

파이썬 GUI PYQT6 란?

python 설치 및 다운로드

파이참 설치 및 세팅(한글, 파이썬 인터프리터)

파이썬 python pyqt6

글 내비게이션

Previous post
Next post

Related Posts

파이썬

파이썬 변수(variable)와 상수(constant)

2023년 06월 29일

변수는 값이 언제든 변할 수 있는 data이며, 상수는 data 값이 변하지 않는다고 보시면 됩니다. 이 글에서는 파이썬 변수(variable)와 상수(constant)에 대해 설명하고 예시를 제공하겠습니다.

Read More
파이썬

python tkinter 디지털 서명 패드 만들기

2023년 07월 09일

디지털 서명은 현대의 디지털 시대에서 중요한 역할을 합니다. 기존의 종이 위에 서명을 하는 방식에서 벗어나, 전자적인 형태로 서명을 생성하고 저장할 수 있는 디지털 서명 패드는 다양한 분야에서 사용되고 있습니다. 이번 글에서는 Python의 Tkinter 라이브러리를 활용하여 간단한 디지털 서명 패드를 만드는 방법에 대해 알아보겠습니다. Tkinter 라이브러리 설치하기 Tkinter는 Python의 표준 GUI…

Read More
파이썬

Qt Designer download

2024년 06월 24일

Qt Designer는 C++와 Python을 포함한 여러 프로그래밍 언어를 사용하는 개발자들에게 필요한 도구입니다. Qt Designer의 특징과 사용법, 설치 방법, 그리고 Qt Designer download 까지 자세히 알아보겠습니다.

Read More

답글 남기기 응답 취소

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

최신 글

  • usb 쓰기금지 해제방법, 어렵지 않아요
  • usb a타입에 대해 알아보자
  • 포토샵 누끼따기 방법
  • vpn 연결방법 쉽게 설명해드립니다.
  • usb 장치 인식 실패시 해결방안

최신 댓글

  1. 윈도우 단축키 모음 Best5의 ace
  2. http https 차이의 챗GPT 란? · Working for you

보관함

  • 2025년 6월
  • 2025년 5월
  • 2025년 4월
  • 2025년 3월
  • 2025년 2월
  • 2025년 1월
  • 2024년 12월
  • 2024년 11월
  • 2024년 8월
  • 2024년 6월
  • 2024년 5월
  • 2024년 3월
  • 2024년 2월
  • 2023년 11월
  • 2023년 9월
  • 2023년 8월
  • 2023년 7월
  • 2023년 6월
  • 2023년 5월
  • 2023년 4월
  • 2023년 3월
  • 2023년 2월

카테고리

  • flutter
  • html
  • linux
  • macbook
  • Pc Useful Tips
  • 미분류
  • 워드프레스
  • 자바(Java)
  • 파이썬
  • 프로그래밍
©2025 toylee blog · 컴퓨터, 프로그램 정보 공유 | WordPress Theme by SuperbThemes