Python PyQt5标准对话框用法示例

本文实例讲述了Python PyQt5标准对话框用法。分享给大家供大家参考,具体如下:

很全的Qt的标准对话框,包含QInputDialog、QColorDialog、QFontDialog、QMessageBox、QOpenFileDialog...

全部是由官网的C++版本,转换成PyQt5版本。

有些细节忽略了,因为实在不知怎么转换过来。捣鼓了一晚上,总算完成了,好累啊,不过很开心!

效果图:

完整代码:

# -*- coding: utf-8 -*-
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class DialogOptionsWidget(QWidget):
 def __init__(self, parent=None):
  super(DialogOptionsWidget,self).__init__(parent)
 def addCheckBox(self, text, value):
  pass
 def addSpacer():
  pass
 def value():
  pass
class StandardDialog(QDialog):
 def __init__(self,parent=None):
  super(StandardDialog,self).__init__(parent)
  self.setWindowTitle("Standard Dialog")
  frameStyle = QFrame.Sunken | QFrame.Panel
  mainLayout = QVBoxLayout(self)
  toolbox = QToolBox()
  mainLayout.addWidget(toolbox)
  self.errorMessageDialog = QErrorMessage(self)
  pushButton_integer = QPushButton("QInputDialog.get&Int()")
  pushButton_double = QPushButton("QInputDialog.get&Double()")
  pushButton_item = QPushButton("QInputDialog.getIte&m()")
  pushButton_text = QPushButton("QInputDialog.get&Text()")
  pushButton_multiLineText = QPushButton("QInputDialog.get&MultiLineText()")
  pushButton_color = QPushButton("QColorDialog.get&Color()")
  pushButton_font = QPushButton("QFontDialog.get&Font()")
  pushButton_directory = QPushButton("QFileDialog.getE&xistingDirectory()")
  pushButton_openFileName = QPushButton("QFileDialog.get&OpenFileName()")
  pushButton_openFileNames = QPushButton("QFileDialog.&getOpenFileNames()")
  pushButton_saveFileName = QPushButton("QFileDialog.get&SaveFileName()")
  pushButton_critical = QPushButton("QMessageBox.critica&l()")
  pushButton_information = QPushButton("QMessageBox.i&nformation()")
  pushButton_question = QPushButton("QQMessageBox.&question()")
  pushButton_warning = QPushButton("QMessageBox.&warning()")
  pushButton_error = QPushButton("QErrorMessage.showM&essage()")
  self.label_integer = QLabel()
  self.label_double = QLabel()
  self.label_item = QLabel()
  self.label_text = QLabel()
  self.label_multiLineText = QLabel()
  self.label_color = QLabel()
  self.label_font = QLabel()
  self.label_directory = QLabel()
  self.label_openFileName = QLabel()
  self.label_openFileNames = QLabel()
  self.label_saveFileName = QLabel()
  self.label_critical = QLabel()
  self.label_information = QLabel()
  self.label_question = QLabel()
  self.label_warning = QLabel()
  self.label_error = QLabel()
  self.label_integer.setFrameStyle(frameStyle)
  self.label_double.setFrameStyle(frameStyle)
  self.label_item.setFrameStyle(frameStyle)
  self.label_text.setFrameStyle(frameStyle)
  self.label_multiLineText.setFrameStyle(frameStyle)
  self.label_color.setFrameStyle(frameStyle)
  self.label_font.setFrameStyle(frameStyle)
  self.label_directory.setFrameStyle(frameStyle)
  self.label_openFileName.setFrameStyle(frameStyle)
  self.label_openFileNames.setFrameStyle(frameStyle)
  self.label_saveFileName.setFrameStyle(frameStyle)
  self.label_critical.setFrameStyle(frameStyle)
  self.label_information.setFrameStyle(frameStyle)
  self.label_question.setFrameStyle(frameStyle)
  self.label_warning.setFrameStyle(frameStyle)
  self.label_error.setFrameStyle(frameStyle)
  page = QWidget()
  layout = QGridLayout(page)
  layout.setColumnStretch(1,1)
  layout.setColumnMinimumWidth(1,250)
  layout.addWidget(pushButton_integer,0,0)
  layout.addWidget(self.label_integer,0,1)
  layout.addWidget(pushButton_double,1,0)
  layout.addWidget(self.label_double,1,1)
  layout.addWidget(pushButton_item,2,0)
  layout.addWidget(self.label_item,2,1)
  layout.addWidget(pushButton_text,3,0)
  layout.addWidget(self.label_text,3,1)
  layout.addWidget(pushButton_multiLineText,4,0)
  layout.addWidget(self.label_multiLineText,4,1)
  layout.addItem(QSpacerItem(0,0,QSizePolicy.Ignored,QSizePolicy.MinimumExpanding),5,0)
  toolbox.addItem(page, "Input Dialog")
  page = QWidget()
  layout = QGridLayout(page)
  layout.setColumnStretch(1,1)
  #layout.setColumnMinimumWidth(1,250)
  layout.addWidget(pushButton_color,0,0)
  layout.addWidget(self.label_color,0,1)
  colorDialogOptionsWidget = DialogOptionsWidget()
  colorDialogOptionsWidget.addCheckBox("Do not use native dialog", QColorDialog.DontUseNativeDialog)
  colorDialogOptionsWidget.addCheckBox("Show alpha channel" , QColorDialog.ShowAlphaChannel)
  colorDialogOptionsWidget.addCheckBox("No buttons" , QColorDialog.NoButtons)
  layout.addItem(QSpacerItem(0,0,QSizePolicy.Ignored,QSizePolicy.MinimumExpanding),1,0)
  layout.addWidget(colorDialogOptionsWidget, 2, 0, 1 ,2)
  toolbox.addItem(page, "Color Dialog")
  page = QWidget()
  layout = QGridLayout(page)
  layout.setColumnStretch(1, 1)
  layout.addWidget(pushButton_font, 0, 0)
  layout.addWidget(self.label_font, 0, 1)
  fontDialogOptionsWidget = DialogOptionsWidget()
  fontDialogOptionsWidget.addCheckBox("Do not use native dialog", QFontDialog.DontUseNativeDialog)
  fontDialogOptionsWidget.addCheckBox("No buttons", QFontDialog.NoButtons)
  layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 1, 0)
  layout.addWidget(fontDialogOptionsWidget, 2, 0, 1 ,2)
  toolbox.addItem(page, "Font Dialog")
  page = QWidget()
  layout = QGridLayout(page)
  layout.setColumnStretch(1, 1)
  layout.addWidget(pushButton_directory, 0, 0)
  layout.addWidget(self.label_directory, 0, 1)
  layout.addWidget(pushButton_openFileName, 1, 0)
  layout.addWidget(self.label_openFileName, 1, 1)
  layout.addWidget(pushButton_openFileNames, 2, 0)
  layout.addWidget(self.label_openFileNames, 2, 1)
  layout.addWidget(pushButton_saveFileName, 3, 0)
  layout.addWidget(self.label_saveFileName, 3, 1)
  fileDialogOptionsWidget = DialogOptionsWidget()
  fileDialogOptionsWidget.addCheckBox("Do not use native dialog", QFileDialog.DontUseNativeDialog)
  fileDialogOptionsWidget.addCheckBox("Show directories only", QFileDialog.ShowDirsOnly)
  fileDialogOptionsWidget.addCheckBox("Do not resolve symlinks", QFileDialog.DontResolveSymlinks)
  fileDialogOptionsWidget.addCheckBox("Do not confirm overwrite", QFileDialog.DontConfirmOverwrite)
  fileDialogOptionsWidget.addCheckBox("Do not use sheet", QFileDialog.DontUseSheet)
  fileDialogOptionsWidget.addCheckBox("Readonly", QFileDialog.ReadOnly)
  fileDialogOptionsWidget.addCheckBox("Hide name filter details", QFileDialog.HideNameFilterDetails)
  layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 4, 0)
  layout.addWidget(fileDialogOptionsWidget, 5, 0, 1 ,2)
  toolbox.addItem(page, "File Dialogs")
  page = QWidget()
  layout = QGridLayout(page)
  layout.setColumnStretch(1, 1)
  layout.addWidget(pushButton_critical, 0, 0)
  layout.addWidget(self.label_critical, 0, 1)
  layout.addWidget(pushButton_information, 1, 0)
  layout.addWidget(self.label_information, 1, 1)
  layout.addWidget(pushButton_question, 2, 0)
  layout.addWidget(self.label_question, 2, 1)
  layout.addWidget(pushButton_warning, 3, 0)
  layout.addWidget(self.label_warning, 3, 1)
  layout.addWidget(pushButton_error, 4, 0)
  layout.addWidget(self.label_error, 4, 1)
  layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 5, 0)
  toolbox.addItem(page, "Message Boxes")
  pushButton_integer.clicked.connect(self.setInteger)
  pushButton_double.clicked.connect(self.setDouble)
  pushButton_item.clicked.connect(self.setItem)
  pushButton_text.clicked.connect(self.setText)
  pushButton_multiLineText.clicked.connect(self.setMultiLineText)
  pushButton_color.clicked.connect(self.setColor)
  pushButton_font.clicked.connect(self.setFont)
  pushButton_directory.clicked.connect(self.setExistingDirectory)
  pushButton_openFileName.clicked.connect(self.setOpenFileName)
  pushButton_openFileNames.clicked.connect(self.setOpenFileNames)
  pushButton_saveFileName.clicked.connect(self.setSaveFileName)
  pushButton_critical.clicked.connect(self.criticalMessage)
  pushButton_information.clicked.connect(self.informationMessage)
  pushButton_question.clicked.connect(self.questionMessage)
  pushButton_warning.clicked.connect(self.warningMessage)
  pushButton_error.clicked.connect(self.errorMessage)
 #输入对话框 取整数
 def setInteger(self):
  intNum, ok = QInputDialog.getInt(self, "QInputDialog.getInteger()","Percentage:", 25, 0, 100, 1)
  if ok:
   self.label_integer.setText(str(intNum))
 #输入对话框 取实数
 def setDouble(self):
  doubleNum, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()", "Amount:", 37.56, -10000, 10000, 2)
  if ok:
   self.label_double.setText(str(doubleNum))
 #输入对话框 取列表项
 def setItem(self):
  items = ["Spring", "Summer", "Fall", "Winter"]
  item, ok = QInputDialog.getItem(self, "QInputDialog.getItem()","Season:", items, 0, False)
  if ok and item:
   self.label_item.setText(item)
 #输入对话框 取文本
 def setText(self):
  text, ok = QInputDialog.getText(self, "QInputDialog.getText()", "User name:", QLineEdit.Normal, QDir.home().dirName())
  if ok and text:
   self.label_text.setText(text)
 #输入对话框 取多行文本
 def setMultiLineText(self):
  text, ok = QInputDialog.getMultiLineText(self, "QInputDialog.getMultiLineText()", "Address:", "John Doe\nFreedom Street")
  if ok and text:
   self.label_multiLineText.setText(text)
 #颜色对话框 取颜色
 def setColor(self):
  #options = QColorDialog.ColorDialogOptions(QFlag.QFlag(colorDialogOptionsWidget.value()))
  color = QColorDialog.getColor(Qt.green, self, "Select Color")
  if color.isValid():
   self.label_color.setText(color.name())
   self.label_color.setPalette(QPalette(color))
   self.label_color.setAutoFillBackground(True)
 #字体对话框 取字体
 def setFont(self):
  #options = QFontDialog.FontDialogOptions(QFlag(fontDialogOptionsWidget.value()))
  #font, ok = QFontDialog.getFont(ok, QFont(self.label_font.text()), self, "Select Font",options)
  font, ok = QFontDialog.getFont()
  if ok:
   self.label_font.setText(font.key())
   self.label_font.setFont(font)
 #目录对话框 取目录
 def setExistingDirectory(self):
  #options = QFileDialog.Options(QFlag(fileDialogOptionsWidget->value()))
  #options |= QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
  directory = QFileDialog.getExistingDirectory(self,
         "QFileDialog.getExistingDirectory()",
         self.label_directory.text())
  if directory:
   self.label_directory.setText(directory)
 #打开文件对话框 取文件名
 def setOpenFileName(self):
  #options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
  #selectedFilter
  fileName, filetype = QFileDialog.getOpenFileName(self,
         "QFileDialog.getOpenFileName()",
         self.label_openFileName.text(),
         "All Files (*);;Text Files (*.txt)")
  if fileName:
   self.label_openFileName.setText(fileName)
 #打开文件对话框 取一组文件名
 def setOpenFileNames(self):
  #options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
  #selectedFilter
  openFilesPath = "D:/documents/pyMarksix/draw/"
  files, ok = QFileDialog.getOpenFileNames(self,
         "QFileDialog.getOpenFileNames()",
         openFilesPath,
         "All Files (*);;Text Files (*.txt)")
  if len(files):
   self.label_openFileNames.setText(", ".join(files))
 #保存文件对话框 取文件名
 def setSaveFileName(self):
  #options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
  #selectedFilter
  fileName, ok = QFileDialog.getSaveFileName(self,
         "QFileDialog.getSaveFileName()",
         self.label_saveFileName.text(),
         "All Files (*);;Text Files (*.txt)")
  if fileName:
   self.label_saveFileName.setText(fileName)
 def criticalMessage(self):
  #reply = QMessageBox.StandardButton()
  MESSAGE = "批评!"
  reply = QMessageBox.critical(self,
         "QMessageBox.critical()",
         MESSAGE,
         QMessageBox.Abort | QMessageBox.Retry | QMessageBox.Ignore)
  if reply == QMessageBox.Abort:
   self.label_critical.setText("Abort")
  elif reply == QMessageBox.Retry:
   self.label_critical.setText("Retry")
  else:
   self.label_critical.setText("Ignore")
 def informationMessage(self):
  MESSAGE = "信息"
  reply = QMessageBox.information(self, "QMessageBox.information()", MESSAGE)
  if reply == QMessageBox.Ok:
   self.label_information.setText("OK")
  else:
   self.label_information.setText("Escape")
 def questionMessage(self):
  MESSAGE = "疑问"
  reply = QMessageBox.question(self, "QMessageBox.question()",
         MESSAGE,
         QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
  if reply == QMessageBox.Yes:
   self.label_question.setText("Yes")
  elif reply == QMessageBox.No:
   self.label_question.setText("No")
  else:
   self.label_question.setText("Cancel")
 def warningMessage(self):
  MESSAGE = "警告文本"
  msgBox = QMessageBox(QMessageBox.Warning,
       "QMessageBox.warning()",
        MESSAGE,
        QMessageBox.Retry | QMessageBox.Discard | QMessageBox.Cancel,
        self)
  msgBox.setDetailedText("详细信息。。。")
  #msgBox.addButton("Save &Again", QMessageBox.AcceptRole)
  #msgBox.addButton("&Continue", QMessageBox.RejectRole)
  if msgBox.exec() == QMessageBox.AcceptRole:
   self.label_warning.setText("Retry")
  else:
   self.label_warning.setText("Abort")
 def errorMessage(self):
  self.errorMessageDialog.showMessage(
     "This dialog shows and remembers error messages. "
     "If the checkbox is checked (as it is by default), "
     "the shown message will be shown again, "
     "but if the user unchecks the box the message "
     "will not appear again if QErrorMessage.showMessage() "
     "is called with the same message.")
  self.label_error.setText("If the box is unchecked, the message "
        "won't appear again.")
app=QApplication(sys.argv)
form=StandardDialog()
form.show()
app.exec_()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

(0)

相关推荐

  • python在windows下创建隐藏窗口子进程的方法

    本文实例讲述了python在windows下创建隐藏窗口子进程的方法.分享给大家供大家参考.具体实现方法如下: import subprocess IS_WIN32 = 'win32' in str(sys.platform).lower() def subprocess_call(*args, **kwargs): #also works for Popen. #It creates a new *hidden* window, #so it will work in frozen apps

  • 关于python pyqt5安装失败问题的解决方法

    前言 最近在工作中遇到一个问题,python pyqt5在安装的时候居然提示失败了,无奈只能找解决的办法,发现网上有同样遇到这个问题的同学,所以就总结了解决的方法分享出来,下面话不多说了,来一起看看详细的介绍: 发现问题 以前装命令都是pip一条命令搞定,会自动安装依赖的库,但在安装pyqt5时却遇到了问题 在下载完pyqt5时,会提示找不到合适的SIP版本 Could not find a version that satisfies the requirement sip>=4.19 (fr

  • Python tkinter模块弹出窗口及传值回到主窗口操作详解

    本文实例讲述了Python tkinter模块弹出窗口及传值回到主窗口操作.分享给大家供大家参考,具体如下: 有些时候,我们需要使用弹出窗口,对程序的运行参数进行设置.有两种选择 一.标准窗口 如果只对一个参数进行设置(或者说从弹出窗口取回一个值),那么可以使用simpledialog,导入方法: from tkinter.simpledialog import askstring, askinteger, askfloat 完整例子 import tkinter as tk from tkin

  • python中pygame针对游戏窗口的显示方法实例分析(附源码)

    本文实例讲述了python中pygame针对游戏窗口的显示方法.分享给大家供大家参考,具体如下: 在这篇教程中,我将给出一个demo演示: 当我们按下键盘的'f'键的时候,演示的窗口会切换到全屏显示和默认显示两种显示模式 并且在后台我们可以看到相关的信息输出: 上面给出了一个简单的例子,当然在pygame的官方文档中有对显示策略的更权威的说明: http://www.pygame.org/docs/ref/display.html#pygame.display.set_mode ''' pyga

  • python 创建弹出式菜单的实现代码

    python 创建弹出式菜单的实现代码            实现效果图: Python代码  import win32ui import win32api from win32con import * from pywin.mfc import window class MyWnd(window.Wnd): def __init__ (self): window.Wnd.__init__(self,win32ui.CreateWnd()) self._obj_.CreateWindowEx(W

  • wxPython窗口的继承机制实例分析

    本文实例讲述了wxPython窗口的继承机制,分享给大家供大家参考.具体分析如下: 示例代码如下: import wx class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(None, title = "My Main Frame jb51.net") self.SetTopWindow(self.frame) self.frame.Show() return True class MyFrame(wx.Frame):

  • python3.5 + PyQt5 +Eric6 实现的一个计算器代码

    目前可以实现简单的计算.计算前请重置,设计的时候默认数字是0,学了半天就做出来个这么个结果,bug不少. python3.5 + PyQt5 +Eric6 在windows7 32位系统可以完美运行 计算器,简单学了半天就画个图实现的存在bug,部分按钮还未实现,后续优化. 代码结构如图: jisuan.py import re #匹配整数或小数的乘除法,包括了开头存在减号的情况 mul_div=re.compile("(-?\d+)(\.\d+)?(\*|/)(-?\d+)(\.\d+)?&q

  • python实现的简单窗口倒计时界面实例

    本文实例讲述了python实现的简单窗口倒计时界面.分享给大家供大家参考.具体分析如下: 下面的代码通过Tkinter制作windows窗口界面,然后时间了一个简单的倒计时功能,代码可以直接运行 # Countdown using Tkinter from Tkinter import * import time import tkMessageBox class App: def __init__(self,master): frame = Frame(master) frame.pack()

  • Python PyQt5实现的简易计算器功能示例

    本文实例讲述了Python PyQt5实现的简易计算器功能.分享给大家供大家参考,具体如下: 这里剩下计算函数(self.calculator)未实现,有兴趣的朋友可以实现它 [知识点] 1.利用循环添加按钮部件,及给每个按钮设置信号/槽 2.给按钮设置固定大小:button.setFixedSize(QtCore.QSize(60,30)) 3.取事件的的发送者(此例为各个按钮)的文本: self.sender().text() [效果图] [源代码] import sys from PyQt

  • python3+PyQt5实现使用剪贴板做复制与粘帖示例

    本文是对<Python Qt GUI快速编程>的第10章的例子剪贴板用Python3+PyQt5进行改写,分别对文本,图片和html文本的复制与粘帖,三种做法大同小异. #!/usr/bin/env python3 import os import sys from PyQt5.QtCore import (QMimeData, Qt) from PyQt5.QtWidgets import (QApplication, QDialog, QGridLayout, QLabel, QPushB

随机推荐