【Hello,PyQt】PyQt5中的一些对话框

发布于:2024-04-03 ⋅ 阅读:(33) ⋅ 点赞:(0)

QDialog类是一种特殊的窗口,它被设计出来作为和用户进行交换的对话框。QDialog上是可以包含其他的控件的,比如QLineEdit,QPushButton等。QDialog类的子类主要有QMessageBox,QFileDialog,QColorDialog,QFontDialog,QInputDialog等。其中QMessageBox是消息提示对话框,QFileDialog是文件选择对话框,QColorDialog是颜色选择对话框,QFontDialog是字体选择对话框,QInputDialog是输入对话框

普通对话框

创建对话框QDialog

在PyQt中,使用 QDialog 显示一个普通对话框通常需要以下步骤:

  1. 创建一个 QDialog 对象。
  2. 设置窗口模态。
  3. 设置对话框的属性,例如标题、布局和其他组件。
  4. 使用 exec_() 方法来显示对话框。
dialog = QDialog()
# 设置窗口模态
dialog.setModal(True)
dialog.setWindowTitle("Simple Dialog")
# 创建布局和标签
layout = QVBoxLayout()
label = QLabel("This is a simple dialog.")
layout.addWidget(label)
# 设置对话框布局
dialog.setLayout(layout)
# 显示对话框
dialog.exec_()

自定义对话框

class InputDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("InputDialog")

        # 创建布局
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # 添加组件
        self.label = QLabel("Enter your name:")
        self.line_edit = QLineEdit()
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")

        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.addWidget(self.ok_button)
        button_layout.addWidget(self.cancel_button)

        # 添加组件到主布局
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.line_edit)
        self.layout.addLayout(button_layout)

        # 按钮事件绑定
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)

    def get_input_text(self):
        return self.line_edit.text()

关闭对话框的三种方式

关闭对话框最直接的方式就是点击右上角的那个X,但是如果我的对话框是没有边框的,就像下面这样
在这里插入图片描述

或者说就是不通过那个X关闭对话框,想通过单击一个按钮关闭对话框,那么了解对话框关闭的方式就很有必要。

使用accept()和reject()方法

这两个方法可以模拟用户点击对话框窗口的确定和取消按钮

accept() 方法用于接受对话框的内容并关闭对话框。调用 accept() 方法会发出 accepted信号。

reject() 方法用于拒绝对话框的内容并关闭对话框。调用 reject() 方法会发出 rejected信号。

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton

class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 200, 100)

        self.button1 = QPushButton("close", self)
        self.button1.setGeometry(80, 30, 40, 25)
        self.button1.clicked.connect(self.accept)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dialog = MyDialog()
    dialog.show()
    sys.exit(app.exec_())

这里在连接信号的时候需要注意一个问题,这个例子里链接槽函数的时候是直接用的self.accept,但我有个朋友是这样操作的
self.button1.clicked.connect(QDialog.accept)这样写按下按钮就不会正常退出进程已结束,退出代码-1073740791 (0xC0000409)
需要改成self.button1.clicked.connect(lambda :QDialog.accept(self))

使用close()方法

close()方法可以直接关闭对话框窗口,没有模拟按钮的点击事件。

使用done()方法

使用done()方法可以传入一个整型参数表示对话框关闭后的返回值。

输入对话框

QInputDialog提供了一些静态方法可以让用户方便的输入文本、整数等数据。

  • QInputDialog.getItem:提供了选择选项的下拉列表。
  • QInputDialog.getText:获取输入的文本内容。
  • QInputDialog.getInt:提供了获取输入数字的计时器。
    QInputDialog的用法非常简单,通过下面的例子就可以掌握其用法
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QDialog, QInputDialog, QLabel, QLineEdit
import sys

class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.item_label = QLabel("Selected item:")
        layout.addWidget(self.item_label)

        self.text_label = QLabel("Entered text:")
        layout.addWidget(self.text_label)

        self.integer_label = QLabel("Entered integer:")
        layout.addWidget(self.integer_label)

        item_button = QPushButton("Get Item")
        item_button.clicked.connect(self.get_item)
        layout.addWidget(item_button)

        text_button = QPushButton("Get Text")
        text_button.clicked.connect(self.get_text)
        layout.addWidget(text_button)

        int_button = QPushButton("Get Integer")
        int_button.clicked.connect(self.get_integer)
        layout.addWidget(int_button)

    def get_item(self):
        items = ['Apple', 'Banana', 'Orange', 'Grapes']
        item, ok = QInputDialog.getItem(self, "Item Dialog", "选择你最喜欢的水果:", items, 0, False)
        if ok and item:
            self.item_label.setText("Selected item: " + item)

    def get_text(self):
        text, ok = QInputDialog.getText(self, "Text Dialog", "输入你的名字:")
        if ok and text:
            self.text_label.setText("Entered text: " + text)

    def get_integer(self):
        value, ok = QInputDialog.getInt(self, "Integer Dialog", "输入你的年龄:", 18, 0, 100, 1)
        if ok:
            self.integer_label.setText("Entered integer: " + str(value))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dialog = MyDialog()
    dialog.show()
    sys.exit(app.exec_())

运行效果
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

字体颜色对话框

使用QColorDialog.getColor()方法显示一个可以选择字体颜色和背景颜色的对话框。字体的颜色是不能直接设置的,要先创建一个调试板对象,调色板对象设置颜色,然后传递给指定的控件(setPalette()方法)

from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QDialog, QLabel, QColorDialog
from PyQt5.QtGui import QColor, QPalette
import sys

class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.color_label = QLabel("Hello, World!")
        layout.addWidget(self.color_label)

        font_color_button = QPushButton("选择字体颜色")
        font_color_button.clicked.connect(self.choose_font_color)
        layout.addWidget(font_color_button)

        bg_color_button = QPushButton("选择背景颜色")
        bg_color_button.clicked.connect(self.choose_bg_color)
        layout.addWidget(bg_color_button)

    def choose_font_color(self):
        color = QColorDialog.getColor()
        if color.isValid():
            # 设置字体颜色
            p = QPalette()
            p.setColor(QPalette.WindowText, color)
            self.color_label.setPalette(p)

    def choose_bg_color(self):
        color = QColorDialog.getColor()
        if color.isValid():
            # 获取当前标签的字体颜色,防止设置背景时将字体设置成默认颜色
            font_color = self.color_label.palette().color(self.color_label.foregroundRole())

            p = QPalette()
            p.setColor(QPalette.Window, color)
            p.setColor(QPalette.WindowText,font_color)
            self.color_label.setAutoFillBackground(True)
            self.color_label.setPalette(p)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dialog = MyDialog()
    dialog.show()
    sys.exit(app.exec_())

运行效果

  • 设置字体颜色
    在这里插入图片描述

  • 设置背景颜色
    在这里插入图片描述