본문 바로가기
PYTHON(파이썬)/PYSIDE6(GUI)

PYSIDE6 대화상자

by eplus 2024. 10. 24.

대화 상자는 사용자와 상호 작용하는 데 사용되는 작은 창입니다. 대화 상자는 정보를 제공하거나 사용자 입력을 받기 위해 사용됩니다. PySide6에서는 다양한 유형의 대화 상자를 제공하며, 필요에 따라 사용자 정의 대화 상자를 만들 수도 있습니다.

 

#### 표준 대화 상자

PySide6는 파일 선택, 색상 선택, 경고 메시지 등 여러 표준 대화 상자를 제공합니다. 이러한 대화 상자는 QDialog 클래스를 기반으로 하며, 사용하기 쉽게 되어 있습니다.

 

**QMessageBox**

QMessageBox는 간단한 메시지를 사용자에게 표시하는 데 사용됩니다.

 

```python

import sys

from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox, QPushButton

 

class MainWindow(QMainWindow):

    def __init__(self):

        super().__init__()

        self.setWindowTitle("QMessageBox Example")

 

        button = QPushButton("Show Message")

        button.clicked.connect(self.show_message)

        self.setCentralWidget(button)

 

    def show_message(self):

        msg_box = QMessageBox()

        msg_box.setWindowTitle("Information")

        msg_box.setText("This is a message box")

        msg_box.setIcon(QMessageBox.Information)

        msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

        msg_box.setDefaultButton(QMessageBox.Ok)

        result = msg_box.exec()

 

        if result == QMessageBox.Ok:

            print("OK clicked")

        else:

            print("Cancel clicked")

 

app = QApplication(sys.argv)

window = MainWindow()

window.show()

app.exec()

```

이 예제는 "Show Message" 버튼을 클릭하면 정보 메시지 상자를 표시합니다.

 

**QFileDialog**

QFileDialog는 파일을 열거나 저장할 파일을 선택하는 데 사용됩니다.

 

```python

import sys

from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QPushButton

 

class MainWindow(QMainWindow):

    def __init__(self):

        super().__init__()

        self.setWindowTitle("QFileDialog Example")

 

        button = QPushButton("Open File")

        button.clicked.connect(self.open_file)

        self.setCentralWidget(button)

 

    def open_file(self):

        file_name, _ = QFileDialog.getOpenFileName(self, "Open File", "", "All Files (*.*);;Text Files (*.txt)")

        if file_name:

            print(f"Selected file: {file_name}")

 

app = QApplication(sys.argv)

window = MainWindow()

window.show()

app.exec()

```

이 예제는 "Open File" 버튼을 클릭하면 파일 선택 대화 상자를 표시합니다.

 

**QColorDialog**

QColorDialog는 색상을 선택하는 데 사용됩니다.

 

```python

import sys

from PySide6.QtWidgets import QApplication, QMainWindow, QColorDialog, QPushButton

 

class MainWindow(QMainWindow):

    def __init__(self):

        super().__init__()

        self.setWindowTitle("QColorDialog Example")

 

        button = QPushButton("Choose Color")

        button.clicked.connect(self.choose_color)

        self.setCentralWidget(button)

 

    def choose_color(self):

        color = QColorDialog.getColor()

        if color.isValid():

            print(f"Selected color: {color.name()}")

 

app = QApplication(sys.argv)

window = MainWindow()

window.show()

app.exec()

```

이 예제는 "Choose Color" 버튼을 클릭하면 색상 선택 대화 상자를 표시합니다.

 

#### 사용자 정의 대화 상자

표준 대화 상자 외에도 사용자 정의 대화 상자를 만들 수 있습니다. 사용자 정의 대화 상자는 QDialog 클래스를 상속하여 만들 수 있습니다.

 

```python

import sys

from PySide6.QtWidgets import QApplication, QMainWindow, QDialog, QVBoxLayout, QPushButton, QLabel, QLineEdit, QDialogButtonBox

 

class CustomDialog(QDialog):

    def __init__(self):

        super().__init__()

        self.setWindowTitle("Custom Dialog")

 

        layout = QVBoxLayout()

       

        self.label = QLabel("Enter your name:")

        layout.addWidget(self.label)

 

        self.line_edit = QLineEdit()

        layout.addWidget(self.line_edit)

 

        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        self.buttons.accepted.connect(self.accept)

        self.buttons.rejected.connect(self.reject)

        layout.addWidget(self.buttons)

 

        self.setLayout(layout)

 

class MainWindow(QMainWindow):

    def __init__(self):

        super().__init__()

        self.setWindowTitle("Custom Dialog Example")

 

        button = QPushButton("Open Dialog")

        button.clicked.connect(self.open_dialog)

        self.setCentralWidget(button)

 

    def open_dialog(self):

        dialog = CustomDialog()

        if dialog.exec():

            print(f"Name entered: {dialog.line_edit.text()}")

        else:

            print("Dialog cancelled")

 

app = QApplication(sys.argv)

window = MainWindow()

window.show()

app.exec()

```

이 예제는 사용자 정의 대화 상자를 생성하고 "Open Dialog" 버튼을 클릭하여 대화 상자를 엽니다. 사용자가 대화 상자에서 이름을 입력하고 확인 버튼을 클릭하면 입력된 이름을 출력하고, 취소 버튼을 클릭하면 대화 상자가 취소됩니다.

 

#### 결론

이 장에서는 PySide6에서 표준 대화 상자와 사용자 정의 대화 상자를 사용하는 방법을 살펴보았습니다. 대화 상자는 사용자와 상호 작용하고 정보를 제공하는 데 중요한 역할을 합니다. 다음 장에서는 다양한 창을 사용하여 애플리케이션을 구성하는 방법을 알아보겠습니다.

import sys

from PySide6.QtWidgets import(
    QApplication,
    QMainWindow,
    QPushButton
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("My App")
       
        button = QPushButton("Press me for a dialog")
        button.clicked.connect(self.button_clicked)
        self.setCentralWidget(button)
       
    def button_clicked(self, is_checked):
        print("click", is_checked)
       
app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()
import sys
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QDialog,
    QPushButton,
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("My App")
       
        button = QPushButton("Press me for a dialog")
        button.clicked.connect(self.button_clicked)
        self.setCentralWidget(button)
       
    def button_clicked(self, is_checked):
        print("click", is_checked)
       
        dlg = QDialog(self)
        dlg.setWindowTitle("?")
        dlg.exec()
       
app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()
import sys

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QDialog,
    QLabel,
    QDialogButtonBox,
    QPushButton,
    QVBoxLayout,
)

class CustomDialog(QDialog):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("HELLO")
       
        buttons = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
       
        self.buttonBox = QDialogButtonBox(buttons)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
       
        self.layout = QVBoxLayout()
       
        message = QLabel("Something happened, is that OK?")
        self.layout.addWidget(message)
        self.layout.addWidget(self.buttonBox)
        self.setLayout(self.layout)
       
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("My App")
       
        button = QPushButton("Press me for a dialog")
        button.clicked.connect(self.button_clicked)
        self.setCentralWidget(button)
       
    def button_clicked(self, is_checked):
        print("click", is_checked)
       
        dlg = CustomDialog()
        if dlg.exec():
            print("Success")
        else:
            print("Cancel")
       
app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()
import sys

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QMessageBox,
    QPushButton,
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("My App")
       
        button = QPushButton("Press me for a dialog")
        button.clicked.connect(self.button_clicked)
        self.setCentralWidget(button)
       
    def button_clicked(self):
        dlg = QMessageBox(self)
        dlg.setWindowTitle("I have a question")
        dlg.setText("This is a simple dialog")
        button = dlg.exec()
       
        if button == QMessageBox.Ok:
            print("OK")
           
app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()
import sys

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QFileDialog,
    QPushButton,
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("My App")
       
        button1 = QPushButton("Open file")
        button1.clicked.connect(self.get_filename)
       
        self.setCentralWidget(button1)
       
    def get_filename(self):
        filters ="Grapics files (*.jpg);;CSV files (*.csv);;Python files (*.py)"
        filename, selected_filter = QFileDialog.getOpenFileName(
            self,
            filter=filters)
        print("Result:", filename, selected_filter)
       
app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()
import sys

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QInputDialog,
    QPushButton,
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
       
        self.setWindowTitle("My App")
       
        button1 = QPushButton("Integer")
        button1.clicked.connect(self.get_an_int)
       
        self.setCentralWidget(button1)
       
    def get_an_int(self):
        my_int_value, ok = QInputDialog.getInt(
            self, "Get an integer", "Enter number"
        )
        print("Result:", ok, my_int_value)
       
app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

 

728x90
반응형

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

PYSIDE6 이벤트  (0) 2024.10.24
PYSIDE6 창  (1) 2024.10.24
PYSIDE6 액션, 도구 모음, 메뉴  (0) 2024.10.23
PYSIDE6 레이아웃  (0) 2024.10.22
PYSIDE6 위젯  (0) 2024.10.21