ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • PYSIDE6 이벤트
    PYTHON(파이썬)/PYSIDE6(GUI) 2024. 10. 24. 06:29
    728x90
    반응형

    이벤트는 사용자와 애플리케이션 간의 상호작용을 처리하는 데 중요한 역할을 합니다. PySide6에서는 다양한 이벤트를 처리할 수 있는 메커니즘을 제공합니다. 이 장에서는 이벤트의 기본 개념과 이벤트를 처리하는 방법에 대해 알아보겠습니다.

     

    #### 이벤트의 기본 개념

    이벤트는 사용자가 애플리케이션과 상호작용할 때 발생하는 다양한 동작을 나타냅니다. 예를 들어, 버튼 클릭, 키보드 입력, 마우스 이동 등이 있습니다. 이러한 이벤트는 Qt의 이벤트 루프를 통해 처리됩니다.

     

    #### 이벤트 핸들러

    이벤트 핸들러는 특정 이벤트가 발생할 때 호출되는 함수입니다. PySide6에서는 다양한 이벤트를 처리하기 위해 여러 이벤트 핸들러를 제공합니다. 이벤트 핸들러를 재정의하여 원하는 동작을 구현할 수 있습니다.

     

    **마우스 이벤트**

    마우스 이벤트는 사용자가 마우스를 클릭하거나 이동할 때 발생합니다. 마우스 이벤트를 처리하려면 `mousePressEvent`, `mouseReleaseEvent`, `mouseMoveEvent` 등의 이벤트 핸들러를 재정의합니다.

     

    ```python

    import sys

    from PySide6.QtWidgets import QApplication, QMainWindow

     

    class MainWindow(QMainWindow):

        def __init__(self):

            super().__init__()

            self.setWindowTitle("Mouse Event Example")

     

        def mousePressEvent(self, event):

            print(f"Mouse pressed at {event.position()}")

     

        def mouseReleaseEvent(self, event):

            print(f"Mouse released at {event.position()}")

     

        def mouseMoveEvent(self, event):

            print(f"Mouse moved to {event.position()}")

     

    app = QApplication(sys.argv)

    window = MainWindow()

    window.show()

    app.exec()

    ```

    이 예제에서는 마우스 버튼을 누르거나, 놓거나, 이동할 때마다 해당 위치를 출력합니다.

     

    **키보드 이벤트**

    키보드 이벤트는 사용자가 키보드를 눌렀을 때 발생합니다. 키보드 이벤트를 처리하려면 `keyPressEvent`, `keyReleaseEvent` 등의 이벤트 핸들러를 재정의합니다.

     

    ```python

    import sys

    from PySide6.QtWidgets import QApplication, QMainWindow

     

    class MainWindow(QMainWindow):

        def __init__(self):

            super().__init__()

            self.setWindowTitle("Keyboard Event Example")

     

        def keyPressEvent(self, event):

            print(f"Key pressed: {event.key()}")

     

        def keyReleaseEvent(self, event):

            print(f"Key released: {event.key()}")

     

    app = QApplication(sys.argv)

    window = MainWindow()

    window.show()

    app.exec()

    ```

    이 예제에서는 키를 누르거나 놓을 때마다 해당 키 코드를 출력합니다.

     

    **타이머 이벤트**

    타이머 이벤트는 일정한 간격으로 발생합니다. 타이머 이벤트를 처리하려면 `QTimer` 클래스를 사용하여 타이머를 설정하고, `timerEvent` 이벤트 핸들러를 재정의합니다.

     

    ```python

    import sys

    from PySide6.QtCore import QTimer, QEvent

    from PySide6.QtWidgets import QApplication, QMainWindow

     

    class MainWindow(QMainWindow):

        def __init__(self):

            super().__init__()

            self.setWindowTitle("Timer Event Example")

     

            self.timer = QTimer(self)

            self.timer.timeout.connect(self.handle_timeout)

            self.timer.start(1000)  # 1초 간격으로 타이머 설정

     

        def handle_timeout(self):

            print("Timer timeout")

     

    app = QApplication(sys.argv)

    window = MainWindow()

    window.show()

    app.exec()

    ```

    이 예제에서는 1초 간격으로 타이머가 타임아웃될 때마다 "Timer timeout" 메시지를 출력합니다.

     

    **이벤트 필터**

    이벤트 필터는 특정 객체에 대해 발생하는 이벤트를 가로채는 메커니즘입니다. 이벤트 필터를 사용하려면 `installEventFilter` 메서드를 사용하여 필터를 설치하고, `eventFilter` 메서드를 재정의합니다.

     

    ```python

    import sys

    from PySide6.QtCore import QObject, QEvent

    from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton

     

    class Filter(QObject):

        def eventFilter(self, watched, event):

            if event.type() == QEvent.MouseButtonPress:

                print("Mouse button pressed in filtered object")

                return True  # 이벤트를 필터링하여 처리된 것으로 표시

            return super().eventFilter(watched, event)

     

    class MainWindow(QMainWindow):

        def __init__(self):

            super().__init__()

            self.setWindowTitle("Event Filter Example")

     

            self.button = QPushButton("Click me")

            self.setCentralWidget(self.button)

     

            self.filter = Filter()

            self.button.installEventFilter(self.filter)

     

    app = QApplication(sys.argv)

    window = MainWindow()

    window.show()

    app.exec()

    ```

    이 예제에서는 버튼에 이벤트 필터를 설치하여 마우스 버튼이 눌렸을 때 메시지를 출력하고 이벤트를 필터링합니다.

     

    ### 결론

    이 장에서는 PySide6에서 다양한 이벤트를 처리하는 방법에 대해 알아보았습니다. 마우스 이벤트, 키보드 이벤트, 타이머 이벤트, 이벤트 필터 등을 사용하여 사용자와의 상호작용을 효율적으로 처리할 수 있습니다. 다음 장에서는 Qt 디자이너를 사용하여 그래픽 사용자 인터페이스를 디자인하는 방법을 알아보겠습니다.

    import sys

    from PySide6.QtCore import Qt
    from PySide6.QtWidgets import (
        QApplication,
        QMainWindow,
        QLabel,
    )

    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.label = QLabel("Click in this window")
            self.setCentralWidget(self.label)
            #self.setMouseTracking(True)
            #self.label.setMouseTracking(True)
           
        def mouseMoveEvent(self, e):
            self.label.setText("mouseMoveEvent")
           
        def mousePressEvent(self, e):
            self.label.setText("mousePressEvent")
            if e.button() == Qt.LeftButton:
                self.label.setText("Left")
            elif e.button() == Qt.MiddleButton:
                self.label.setText("Middle")
            elif e.button() == Qt.RightButton:
                self.label.setText("Right")
           
        def mouseReleaseEvent(self, e):
            self.label.setText("mouseReleaseEvent")
           
        def mouseDoubleClickEvent(self, e):
            self.label.setText("mouseDoubleClickEvent")
           
           
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    app.exec()
    import sys

    from PySide6.QtCore import Qt
    from PySide6.QtGui import QAction
    from PySide6.QtWidgets import (
        QApplication,
        QMainWindow,
        QMenu,
    )

    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
           
            self.setContextMenuPolicy(Qt.CustomContextMenu)
            self.customContextMenuRequested.connect(self.on_context_menu)
           
        def on_context_menu(self, pos):
            context = QMenu(self)
            context.addAction(QAction("test1", self))
            context.addAction(QAction("test2", self))
            context.addAction(QAction("test3", self))
            context.exec(self.mapToGlobal(pos))        
           
        def contextMenuEvent(self, e):
            context = QMenu(self)
            context.addAction(QAction("t1", self))
            context.addAction(QAction("t2", self))
            context.addAction(QAction("t3", self))
            context.exec(e.globalPos())
           
           
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    app.exec()
    728x90

    'PYTHON(파이썬) > PYSIDE6(GUI)' 카테고리의 다른 글

    PYSIDE6 QT디자이너 사용하기  (0) 2024.10.24
    PYSIDE6 QT디자이너 설치  (3) 2024.10.24
    PYSIDE6 창  (0) 2024.10.24
    PYSIDE6 대화상자  (1) 2024.10.24
    PYSIDE6 액션, 도구 모음, 메뉴  (0) 2024.10.23
Designed by Tistory.