如何在QMessageBox中更改按钮顺序

时间:2016-05-13 20:52:21

标签: python qt pyqt qmessagebox

代码使用单个QDialog创建QPushButton窗口。单击该按钮将显示带有三个按钮的QMessageBox窗口。有没有办法重新安排按钮顺序?

enter image description here

from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.resize(300, 100)
        self.setLayout(QtGui.QVBoxLayout())

        button = QtGui.QPushButton('Submit')
        button.clicked.connect(self.onclick)
        self.layout().addWidget(button)

    def onclick(self):
        self.close()
        messagebox = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "Title text", "body text", buttons = QtGui.QMessageBox.Ok |  QtGui.QMessageBox.No |  QtGui.QMessageBox.Cancel, parent=self)
        messagebox.setDefaultButton(QtGui.QMessageBox.No)
        exe = messagebox.exec_()
        print exe

dialog = Dialog()
dialog.show()
app.exec_()

1 个答案:

答案 0 :(得分:2)

QMessageBox.addButton()重载可用于按钮排序。默认排序因平台而异。在调用exec()之后使用QMessageBox.clickedButton()来查询使用了什么按钮。

enter image description here

from PyQt4 import QtGui, QtCore
import sys
app = QtGui.QApplication([])

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.resize(300, 100)
        self.setLayout(QtGui.QVBoxLayout())

        button = QtGui.QPushButton('Submit')
        button.clicked.connect(self.onclick)
        self.layout().addWidget(button)

    def onclick(self):
        self.close()
        message = "<font size = 5 color = gray > Rich Html Title </font> <br/><br/>The clickable link <a href='http://www.google.com'>Google.</a> The lower and upper case text."
        messagebox = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "title", message, parent=self)
        messagebox.addButton("ResetRole Left Most", QtGui.QMessageBox.ResetRole)
        messagebox.addButton("ApplyRole Left", QtGui.QMessageBox.ApplyRole)
        messagebox.addButton("RejectRole Right", QtGui.QMessageBox.RejectRole)
        messagebox.addButton("NoRole Right Most", QtGui.QMessageBox.NoRole)
        exe = messagebox.exec_()
        print 'exe: %s  clickedButton: %s'%(exe, messagebox.clickedButton())

dialog = Dialog()
dialog.show()     
app.exec_()