当前位置:   article > 正文

Python学习笔记-PyQt6对话框_pyqt6中做一个返回数据展示的窗口

pyqt6中做一个返回数据展示的窗口

对话框是界面编程中重要的窗体,一般用于提示或者一些其他特定操作。

一、使用QDialog显示通用消息框

直接使用QDialog类,可以及通过对话框进行通用对话框显示,亦可以通过自定义设置自己需要的对话框。

  1. # _*_ coding:utf-8 _*_
  2. import sys
  3. from PyQt6.QtWidgets import QWidget
  4. from PyQt6.QtWidgets import QApplication
  5. from PyQt6.QtWidgets import QMainWindow
  6. from PyQt6.QtWidgets import QVBoxLayout
  7. from PyQt6.QtWidgets import QHBoxLayout
  8. from PyQt6.QtWidgets import QPushButton
  9. from PyQt6.QtWidgets import QDialog
  10. from PyQt6.QtGui import QIcon
  11. from PyQt6.QtCore import Qt
  12. class MainWindowView(QMainWindow):
  13. """主窗体界面"""
  14. def __init__(self):
  15. """构造函数"""
  16. super().__init__()
  17. self.setWindowTitle("MainWindow")
  18. self.setWindowIcon(QIcon(r"./res/folder_pictures.ico"))
  19. self.resize(300, 200)
  20. self.setMinimumSize(600, 400)
  21. self.center()
  22. self.initui()
  23. def initui(self):
  24. """初始函数"""
  25. self.vboxlayout = QVBoxLayout(self)
  26. self.main_widget = QWidget()
  27. self.main_widget.setLayout(self.vboxlayout)
  28. self.setCentralWidget(self.main_widget)
  29. self.hboxlayout = QHBoxLayout(self)
  30. self.btn = QPushButton(self)
  31. self.btn.setText("弹出对话框")
  32. self.btn.move(100,100)
  33. self.btn.clicked.connect(self.show_dialog)
  34. def center(self):
  35. """居中显示"""
  36. win_rect = self.frameGeometry() # 获取窗口矩形
  37. screen_center = self.screen().availableGeometry().center() # 屏幕中心
  38. win_rect.moveCenter(screen_center) # 移动窗口矩形到屏幕中心
  39. self.move(win_rect.center()) # 移动窗口与窗口矩形重合
  40. def show_dialog(self):
  41. dialog = QDialog()
  42. button = QPushButton("确定", dialog)
  43. button.clicked.connect(dialog.close)
  44. button.move(50,50)
  45. dialog.setWindowTitle("QDialog")
  46. dialog.setWindowModality(Qt.WindowModality.ApplicationModal)
  47. dialog.exec()
  48. if __name__ == "__main__":
  49. app = QApplication(sys.argv)
  50. view = MainWindowView()
  51. view.show()
  52. sys.exit(app.exec())

结果:

点击按钮可以弹出对话框,可以添加对应的按钮关联信号进行窗体关闭或控制。

二、使用QMessageBox显示不同的对话框

QMessageBox是通用的消息对话框,包括如下多种形式,不同的对话框有不同的图标和按钮,还可以根据自己需要微调样式。

  1. # _*_ coding:utf-8 _*_
  2. import sys
  3. from PyQt6.QtWidgets import QWidget
  4. from PyQt6.QtWidgets import QApplication
  5. from PyQt6.QtWidgets import QMainWindow
  6. from PyQt6.QtWidgets import QVBoxLayout
  7. from PyQt6.QtWidgets import QPushButton
  8. from PyQt6.QtWidgets import QMessageBox
  9. from PyQt6.QtGui import QIcon
  10. from PyQt6.QtCore import Qt
  11. class DemoQMessageBox(QMainWindow):
  12. """主窗体界面"""
  13. def __init__(self):
  14. """构造函数"""
  15. super().__init__()
  16. self.setWindowTitle("MainWindow")
  17. self.setWindowIcon(QIcon(r"./res/20 (3).ico"))
  18. self.resize(300, 200)
  19. self.setMinimumSize(600, 400)
  20. self.center()
  21. self.initui()
  22. def initui(self):
  23. """初始函数"""
  24. self.vboxlayout = QVBoxLayout(self)
  25. self.vboxlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
  26. self.main_widget = QWidget()
  27. self.main_widget.setLayout(self.vboxlayout)
  28. self.setCentralWidget(self.main_widget)
  29. btns = ["关于对话框", "错误对话框", "警告对话框", "提问对话框", "消息对话框",]
  30. for btnname in btns:
  31. """添加button"""
  32. btn = QPushButton(btnname)
  33. self.vboxlayout.addWidget(btn)
  34. btn.clicked.connect(self.show_dialog)
  35. def center(self):
  36. """居中显示"""
  37. win_rect = self.frameGeometry() # 获取窗口矩形
  38. screen_center = self.screen().availableGeometry().center() # 屏幕中心
  39. win_rect.moveCenter(screen_center) # 移动窗口矩形到屏幕中心
  40. self.move(win_rect.center()) # 移动窗口与窗口矩形重合
  41. def show_dialog(self):
  42. if type(self.sender()) is QPushButton:
  43. btn_text = self.sender().text()
  44. if btn_text == "关于对话框":
  45. QMessageBox.about(self, "关于", "这是关与对话框")
  46. elif btn_text == "错误对话框":
  47. QMessageBox.critical(self,"错误","程序发生了错误!",QMessageBox.StandardButton.Ignore | QMessageBox.StandardButton.Abort | QMessageBox.StandardButton.Retry,QMessageBox.StandardButton.Retry)
  48. elif btn_text == "警告对话框":
  49. QMessageBox.warning(
  50. self, "警告", "余量不足。", QMessageBox.StandardButton.Ok, QMessageBox.StandardButton.Ok)
  51. elif btn_text == "提问对话框":
  52. QMessageBox.question(self, "提问", "是否取消" ,QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,QMessageBox.StandardButton.Yes)
  53. elif btn_text == "消息对话框":
  54. QMessageBox.information(
  55. self, "消息", "这是通知消息", QMessageBox.StandardButton.Ok, QMessageBox.StandardButton.Ok)
  56. if __name__ == "__main__":
  57. app = QApplication(sys.argv)
  58. view = DemoQMessageBox()
  59. view.show()
  60. sys.exit(app.exec())

结果:

点击不同按钮,显示不同的消息窗口:

关于对话框:

错误对话框:

警告对话框:

提问对话框:

消息对话框:

三、输入对话框

输入对话框,用于弹窗获取用户的输入信息,包含输入列表,输入文本,输入数字等方式。

  • QInputDialog.getItem(self,"获取选项消息框", "名字列表", items),返回值Tuple[str, bool]

  • QInputDialog.getText(self,"获取文本消息框", "请输入文本信息:"),返回值Tuple[str, bool]

  • QInputDialog.getInt(self,"获取整数消息框", "请输入整数:"),返回值Tuple[int, bool]

  • QInputDialog.getMultiLineText(parent: QWidget, title: str, label: str, text: str = ..., flags: QtCore.Qt.WindowType = ..., inputMethodHints: QtCore.Qt.InputMethodHint = ...) -> typing.Tuple[str, bool]

  • QInputDialog.getDouble(parent: QWidget, title: str, label: str, value: float = ..., min: float = ..., max: float = ..., decimals: int = ..., flags: QtCore.Qt.WindowType = ..., step: float = ...) -> typing.Tuple[float, bool]

示例:

  1. # _*_ coding:utf-8 _*_
  2. import sys
  3. from PyQt6.QtWidgets import QApplication
  4. from PyQt6.QtWidgets import QWidget
  5. from PyQt6.QtWidgets import QMainWindow
  6. from PyQt6.QtWidgets import QFormLayout
  7. from PyQt6.QtWidgets import QPushButton
  8. from PyQt6.QtWidgets import QLineEdit
  9. from PyQt6.QtWidgets import QInputDialog
  10. from PyQt6.QtGui import QColor
  11. from PyQt6.QtGui import QIcon
  12. from PyQt6.QtCore import Qt
  13. class QInputDialogDemoView(QMainWindow):
  14. """输入消息框类"""
  15. def __init__(self):
  16. """构造函数"""
  17. super().__init__()
  18. self.setWindowTitle("MainWindow")
  19. self.setWindowIcon(QIcon(r"./res/20 (3).ico"))
  20. self.resize(200, 100)
  21. self.center()
  22. self.initui()
  23. def center(self):
  24. """居中显示"""
  25. win_rect = self.frameGeometry() # 获取窗口矩形
  26. screen_center = self.screen().availableGeometry().center() # 屏幕中心
  27. # 移动窗口矩形到屏幕中心
  28. win_rect.moveCenter(screen_center)
  29. # 移动窗口与窗口矩形重合
  30. self.move(win_rect.center())
  31. def initui(self):
  32. """初始函数"""
  33. # 创建表单布局作为底层布局
  34. self.formlayout = QFormLayout(self)
  35. self.formlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
  36. self.main_widget = QWidget()
  37. self.main_widget.setLayout(self.formlayout)
  38. self.setCentralWidget(self.main_widget)
  39. # 添加获取选项按钮
  40. self.btn_getitem = QPushButton("Get Item")
  41. self.btn_getitem.clicked.connect(self.get_item)
  42. self.ledit_getitem = QLineEdit()
  43. self.formlayout.addRow(self.btn_getitem, self.ledit_getitem)
  44. # 添加获取文本按钮
  45. self.btn_gettext = QPushButton("Get Text")
  46. self.btn_gettext.clicked.connect(self.get_text)
  47. self.ledit_gettext = QLineEdit()
  48. self.formlayout.addRow(self.btn_gettext, self.ledit_gettext)
  49. # 添加获取整数按钮
  50. self.btn_getint = QPushButton("Get Int")
  51. self.btn_getint.clicked.connect(self.get_int)
  52. self.ledit_getint = QLineEdit()
  53. self.formlayout.addRow(self.btn_getint, self.ledit_getint)
  54. def get_item(self):
  55. """获取选项槽"""
  56. items = ("小张", "小明", "小李", "小朱")
  57. item,result = QInputDialog.getItem(self,"获取选项消息框", "名字列表", items)
  58. print(f"item : {item}, ok : {result}, tpye : {type(result)}")
  59. if item and result:
  60. self.ledit_getitem.setText(item)
  61. def get_text(self):
  62. """获取文本槽"""
  63. text,result = QInputDialog.getText(self,"获取文本消息框", "请输入文本信息:")
  64. print(f"item : {text}, ok : {result}, tpye : {type(result)}")
  65. if text and result:
  66. self.ledit_gettext.setText(text)
  67. def get_int(self):
  68. """获取文本槽"""
  69. num,result = QInputDialog.getInt(self,"获取整数消息框", "请输入整数:")
  70. print(f"item : {num}, ok : {result}, tpye : {type(result)}")
  71. if num and result:
  72. self.ledit_getint.setText(str(num))
  73. if __name__ == "__main__":
  74. """主程序运行"""
  75. app = QApplication(sys.argv)
  76. window = QInputDialogDemoView()
  77. window.show()
  78. sys.exit(app.exec())

结果:

主界面:

输入选项:

输入文本:

输入整数:

四、字体对话框

字体对话框(QFontDialog)可以用来交互选择系统中的字体然后通过返回的QFont类型数据来设置相关的字体。

font, ok = QFontDialog.getFont()

示例:

  1. # _*_ coding:utf-8 _*_
  2. import sys
  3. from PyQt6.QtWidgets import QApplication
  4. from PyQt6.QtWidgets import QWidget
  5. from PyQt6.QtWidgets import QMainWindow
  6. from PyQt6.QtWidgets import QFontDialog
  7. from PyQt6.QtWidgets import QPushButton
  8. from PyQt6.QtWidgets import QLabel
  9. from PyQt6.QtWidgets import QVBoxLayout
  10. from PyQt6.QtGui import QFont
  11. from PyQt6.QtCore import Qt
  12. class QFontDialogDemo(QMainWindow):
  13. """字体对话框"""
  14. def __init__(self):
  15. """构造函数"""
  16. super(QFontDialogDemo,self).__init__()
  17. self.init_ui()
  18. def init_ui(self):
  19. self.setWindowTitle("QFontDialogDemo")
  20. self.resize(300, 200)
  21. # 获取中央控件
  22. self.centralwidget = QWidget()
  23. self.setCentralWidget(self.centralwidget)
  24. # 设置布局
  25. self.vboxlayout = QVBoxLayout()
  26. self.vboxlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
  27. self.centralwidget.setLayout(self.vboxlayout)
  28. # 添加标签和按钮
  29. self.label = QLabel("字体样式展示")
  30. self.vboxlayout.addWidget(self.label)
  31. self.label_fonttype = QLabel("字体类型")
  32. self.vboxlayout.addWidget(self.label_fonttype)
  33. self.btn_showfontdialog = QPushButton("选择字体")
  34. self.btn_showfontdialog.clicked.connect(self.getfont)
  35. self.vboxlayout.addWidget(self.btn_showfontdialog)
  36. def getfont(self):
  37. """获取字体"""
  38. font, ok = QFontDialog.getFont()
  39. if ok :
  40. self.label.setFont(font)
  41. self.label_fonttype.setText(f"字体名称:{font.family()},样式:{font.styleName()},字号:{font.pointSize()}")
  42. if __name__ == "__main__":
  43. """主程序运行"""
  44. app = QApplication(sys.argv)
  45. main = QFontDialogDemo()
  46. main.show()
  47. sys.exit(app.exec())

结果:

界面样式:

字体弹窗:

设置字体后:

五、颜色对话框

通过颜色对话框(QColorDialog)选择颜色,然后给给控件设置对应的颜色。

格式:

color, ok = QColorDialog.getColor()

示例:

  1. # _*_ coding:utf-8 _*_
  2. import sys
  3. from PyQt6.QtWidgets import QApplication
  4. from PyQt6.QtWidgets import QWidget
  5. from PyQt6.QtWidgets import QMainWindow
  6. from PyQt6.QtWidgets import QColorDialog
  7. from PyQt6.QtWidgets import QPushButton
  8. from PyQt6.QtWidgets import QLabel
  9. from PyQt6.QtWidgets import QVBoxLayout
  10. from PyQt6.QtGui import QPalette
  11. from PyQt6.QtCore import Qt
  12. class QColorDialogDemo(QMainWindow):
  13. """字体对话框"""
  14. def __init__(self):
  15. """构造函数"""
  16. super(QColorDialogDemo, self).__init__()
  17. self.init_ui()
  18. def init_ui(self):
  19. self.setWindowTitle("QColorDialogDemo")
  20. self.resize(300, 200)
  21. # 获取中央控件
  22. self.centralwidget = QWidget()
  23. self.setCentralWidget(self.centralwidget)
  24. # 设置布局
  25. self.vboxlayout = QVBoxLayout()
  26. self.vboxlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
  27. self.centralwidget.setLayout(self.vboxlayout)
  28. # 添加标签和按钮
  29. self.label = QLabel("字体颜色展示")
  30. self.vboxlayout.addWidget(self.label)
  31. self.label_fonttype = QLabel("颜色:")
  32. self.vboxlayout.addWidget(self.label_fonttype)
  33. self.btn_showcolordialog = QPushButton("选择字体颜色")
  34. self.btn_showcolordialog.clicked.connect(self.getcolor)
  35. self.vboxlayout.addWidget(self.btn_showcolordialog)
  36. self.btn_showcolordialog_background = QPushButton("选择背景颜色")
  37. self.btn_showcolordialog_background.clicked.connect(
  38. self.getcolor_background)
  39. self.vboxlayout.addWidget(self.btn_showcolordialog_background)
  40. def getcolor(self):
  41. """获取颜色"""
  42. color = QColorDialog.getColor()
  43. palette = QPalette()
  44. palette.setColor(QPalette.ColorRole.WindowText, color)
  45. self.label.setPalette(palette)
  46. self.label_fonttype.setText("""颜色:{0:x}""".format(color.rgb()))
  47. def getcolor_background(self):
  48. """获取背景颜色"""
  49. color = QColorDialog.getColor()
  50. palette = QPalette()
  51. palette.setColor(QPalette.ColorRole.Window, color)
  52. self.label.setAutoFillBackground(True)
  53. self.label.setPalette(palette)
  54. self.label_fonttype.setText("""颜色:{0:x}""".format(color.rgb()))
  55. if __name__ == "__main__":
  56. """主程序运行"""
  57. app = QApplication(sys.argv)
  58. main = QColorDialogDemo()
  59. main.show()
  60. sys.exit(app.exec())

结果:

界面:

调色板:

修改颜色字体:

修改背景颜色:

六、文件对话框

文件对话框(QFileDialog)用于浏览文件并获取文件路径。

    • 使用静态方法获取文件路径

  • getSaveFileName(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., filter: str = ..., initialFilter: str = ..., options: 'QFileDialog.Option' = ...) -> typing.Tuple[str, str]: ...

  • getOpenFileNames(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., filter: str = ..., initialFilter: str = ..., options: 'QFileDialog.Option' = ...) -> typing.Tuple[typing.List[str], str]: ...

  • getOpenFileName(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., filter: str = ..., initialFilter: str = ..., options: 'QFileDialog.Option' = ...) -> typing.Tuple[str, str]: ...

  • getExistingDirectoryUrl(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: QtCore.QUrl = ..., options: 'QFileDialog.Option' = ..., supportedSchemes: typing.Iterable[str] = ...) -> QtCore.QUrl: ...

  • getExistingDirectory(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., options: 'QFileDialog.Option' = ...) -> str: ...

示例:

  1. # _*_ coding:utf-8 _*_
  2. import sys
  3. from PyQt6.QtWidgets import QApplication
  4. from PyQt6.QtWidgets import QWidget
  5. from PyQt6.QtWidgets import QMainWindow
  6. from PyQt6.QtWidgets import QFileDialog
  7. from PyQt6.QtWidgets import QPushButton
  8. from PyQt6.QtWidgets import QLabel
  9. from PyQt6.QtWidgets import QLineEdit
  10. from PyQt6.QtWidgets import QFormLayout
  11. from PyQt6.QtGui import QPalette
  12. from PyQt6.QtCore import Qt
  13. class QFileDialogDemo(QMainWindow):
  14. """字体对话框"""
  15. def __init__(self):
  16. """构造函数"""
  17. super(QFileDialogDemo, self).__init__()
  18. self.init_ui()
  19. def init_ui(self):
  20. self.setWindowTitle("QColorDialogDemo")
  21. self.resize(400, 200)
  22. # 获取中央控件
  23. self.centralwidget = QWidget()
  24. self.setCentralWidget(self.centralwidget)
  25. # 设置布局
  26. self.formlayout = QFormLayout()
  27. self.formlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
  28. self.centralwidget.setLayout(self.formlayout)
  29. # 添加标签和按钮
  30. self.label = QLabel("文件路径:")
  31. self.ledit_filepath = QLineEdit()
  32. self.formlayout.addRow(self.label, self.ledit_filepath)
  33. self.btn_openfile = QPushButton("打开文件")
  34. self.btn_openfile.clicked.connect(self.openfile)
  35. self.formlayout.addWidget(self.btn_openfile)
  36. def openfile(self):
  37. """获取颜色"""
  38. # filename->返回的文件路径,filetypelist->设置的要打开的文件类型
  39. filename, filetypelist = QFileDialog.getOpenFileName(
  40. self, "Open File", r"D:\Desktop", "文本文件(*.txt *.csv)")
  41. self.ledit_filepath.setText(filename + ";" + filetypelist)
  42. if __name__ == "__main__":
  43. """主程序运行"""
  44. app = QApplication(sys.argv)
  45. main = QFileDialogDemo()
  46. main.show()
  47. sys.exit(app.exec())

结果:

    • 实例化对话框获取文件路径

实际使用过程中也可以通过自己需求实例化文件对话框后,配置文件对话框属性,然后再获取文件路径。

  1. filedialog = QFileDialog()
  2. filedialog.setFileMode(QFileDialog.FileMode.AnyFile)
  3. filedialog.setFilter(QDir.Filter.Files)
  4. if filedialog.exec():
  5. filenames = filedialog.selectedFiles()
  6. self.ledit_filepath.setText(filenames[0])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/124902
推荐阅读
相关标签
  

闽ICP备14008679号