对话框基本类型:
- 模态对话框:模态对话框是希望用户输入必需信息的对话框。在关闭模式对话框之前,此类型的对话框不允许用户使用应用程序的其他部分。也就是说,用户需要在模式对话框中输入所需的信息,并且在关闭对话框之后,用户可以访问应用程序的其余部分。
- 非模态或非模态对话框:这些对话框允许用户与应用程序和对话框的其他部分进行交互。也就是说,用户可以在保持无模式对话框打开的同时继续与应用程序的其余部分交互。这就是为什么非模态对话框通常用于从用户获取非重要或非关键信息。
输入对话框
- getInt():此方法显示用于接受整数的数字调整框。要从用户获取整数,需要使用以下语法
getInt(self, window title, label before LineEdit widget, default value, minimum, maximum and step size)
示例:quantity, ok = QInputDialog.getInt(self, "Order Quantity", "Enter quantity:", 2, 1, 100, 1)
- getDouble():此方法显示一个数字调整框,其中包含接受小数的浮点数。要从用户处获取小数,需要使用以下语法
getDouble(self, window title, label before LineEdit widget, default value, minimum, maximum and number of decimal places desired)
示例:price, ok = QInputDialog.getDouble(self, "Price of the product", "Enter price:", 1.50,0, 100, 2)
- getText():这个方法显示一个行编辑小部件来接受来自用户的文本。要从用户获取文本,需要使用以下语法
getText(self, window title, label before LineEdit widget)
示例:name, ok = QtGui.QInputDialog.getText(self, 'Get Customer Name', 'Enter your name:')
- getItem():此方法显示一个组合框,其中显示了几个可供选择的项。要从下拉框中获取项,需要使用以下语法
getItem(self, window title, label before combo box, array , current item, Boolean Editable)
示例:countryName, ok = QInputDialog.getItem(self, "Input Dialog", "List of countries", countries, 0, False)
使用输入对话框
- 创建Dialog without Buttons模板窗口
- 拖入一个Label,一个Line Edit, 一个Push Button
- 设定Label的text为Your Country,Push Button的text为Choose Country
- 设定Line Edit的objectName为lineEditCountry
- 设定Push Button的objectName为pushButtonCountry
- 保存为demoInputDialog.ui
- 使用pyuic生成demoInputDialog.py
- 创建demoInputDialog.py
import sys
from PyQt5.QtWidgets import QDialog,QApplication,QInputDialog
from cookbook_200501.demoInputDialog import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui=Ui_Dialog()
self.ui.setupUi(self)
self.ui.pushButtonCountry.clicked.connect(self.dispmessage)
self.show()
def dispmessage(self):
countries=("Albania","Algeria","Andorra","Angola","Antigua and Barbuda", "Argentina", "Armenia", "Aruba","Australia", "Austria", "Azerbaijan")
countryName,ok=QInputDialog.getItem(self,"Input Dialog","List of countries",countries,0,False)
if ok and countryName:
self.ui.lineEditCountry.setText(countryName)
if __name__=="__main__":
app=QApplication(sys.argv)
w=MyForm()
w.show()
sys.exit(app.exec())