Pyqt 简明教程

PyQt - QDialog Class

QDialog 小部件提供顶层窗口,主要用于收集用户的响应。可以将其配置为 Modal (它会阻止其父窗口)或 Modeless (可以绕过该对话框窗口)。

A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed).

PyQt API 具有许多预配置的 Dialog 小部件,例如 InputDialog、FileDialog、FontDialog 等。

PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc.

Example

在以下示例中,Dialog 窗口的 WindowModality 特性决定它是否是模式对话框还是非模式对话框。可以将对话框上的任意一个按钮设置为默认按钮。当用户按下 Escape 键时,通过 QDialog.reject() 方法放弃该对话框。

In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key.

当顶层 QWidget 窗口上的 PushButton 被单击时,会生成一个 Dialog 窗口。Dialog 框的标题栏上没有最小化和最大化控件。

A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar.

用户无法将此对话框窗口置于后台,因为其 WindowModality 已设为 ApplicationModal。

The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal.

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Hello World!")
   b.move(50,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt Dialog demo")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   d = QDialog()
   b1 = QPushButton("ok",d)
   b1.move(50,50)
   d.setWindowTitle("Dialog")
   d.setWindowModality(Qt.ApplicationModal)
   d.exec_()

if __name__ == '__main__':
   window()

上述代码生成以下输出 -

The above code produces the following output −

qdialog class output