例子
在下面的例子中,点击顶层窗口按钮的信号,连接的函数显示消息框对话框。
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")
setStandardButton() 函数显示所需的按钮。
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
buttonClicked() 信号连接到一个槽函数,该函数标识信号源的标题。
msg.buttonClicked.connect(msgbtn)
该示例的完整代码如下 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b = QPushButton(w)
b.setText("Show message!")
b.move(100,50)
b.clicked.connect(showdialog)
w.setWindowTitle("PyQt MessageBox demo")
w.show()
sys.exit(app.exec_())
def showdialog():
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msg.buttonClicked.connect(msgbtn)
retval = msg.exec_()
def msgbtn(i):
print ("Button pressed is:",i.text())
if __name__ == '__main__':
window()
上面的代码产生以下输出。单击主窗口按钮时弹出消息框 -
如果单击 MessageBox 上的 Ok 或 Cancel 按钮,控制台上会产生以下输出 -
Button pressed is: OK
Button pressed is: Cancel