Life Seed

[Pyside6] using Simple Button, Signal and Slots 본문

Python/GUI - Qt for Python(Pyside6)

[Pyside6] using Simple Button, Signal and Slots

lifeseed 2025. 6. 16. 23:43

https://doc.qt.io/qtforpython-6/index.html 사이트의 Tutorial에 대한 내용을 정리입니다.

Tutorials 를 클릭하여 확인할 수 있습니다.

 

https://doc.qt.io/qtforpython-6/tutorials/index.html

 

 

1. Basic Button

버튼을 클릭시 "Button clicked, Hello!" 라는 문구를 터미널에 출력한다.

 

import sys
from PySide6.QtWidgets import QApplication, QPushButton
from PySide6.QtCore import Slot

# Greetings
# The @Slot() is a decorator that identifies a function as a slot. 
# It is not important to understand why for now, 
# but use it always to avoid unexpected behavior.
@Slot()
def say_hello():
    print("Button clicked, Hello!")

# Create the Qt Application
app = QApplication(sys.argv)

# Create a button
button = QPushButton("Click me")

# Connect the button to the function
button.clicked.connect(say_hello)

# Show the button
button.show()
# Run the main Qt loop
app.exec()

 

@Slot()은 함수를 슬롯으로 식별하는 데코레이터이며, 예기치 않은 행동을 피하기 위해 항상 사용하라고 가이드 하고 있네요.

 

 

2. Basic Connection

Button은 시스템에 의해 제공되어진 Signal이라면 사용자가 특정 Signal을 생성하고, 그 Signal에 반응하도록 구현할 수 있습니다.

 

아래 코드는  Overloading Signals and Slots with Different Types 에 대한 예제 입니다.

import sys
from PySide6.QtWidgets import QApplication, QPushButton
from PySide6.QtCore import QObject, Signal, Slot

class Communicate(QObject):
    # create two new signals on the fly: one will handle
    # int type, the other will handle strings
    speak = Signal((int,), (str,))

    def __init__(self, parent=None):
        super().__init__(parent)

        self.speak[int].connect(self.say_something)
        self.speak[str].connect(self.say_something)

    # define a new slot that receives a C 'int' or a 'str'
    # and has 'say_something' as its name
    @Slot(int)
    @Slot(str)
    def say_something(self, arg):
        if isinstance(arg, int):
            print("This is a number:", arg)
        elif isinstance(arg, str):
            print("This is a string:", arg)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    someone = Communicate()

    # emit 'speak' signal with different arguments.
    # we have to specify the str as int is the default
    someone.speak.emit(10)
    someone.speak[str].emit("Hello everybody!")

 

실행시 아래의 두 문구가 출력됩니다.

 

This is a number: 10
This is a string: Hello everybody!

 

 

 

반응형