alphanumeric
alphanumeric

Reputation: 19379

How to change the buttons order in QMessageBox

The code creates a QDialog window with a single QPushButton. Clicking the button brings up the QMessageBox window with three buttons. Is there a way to re-arrange the buttons order?

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_()

Upvotes: 3

Views: 5289

Answers (1)

alphanumeric
alphanumeric

Reputation: 19379

QMessageBox.addButton() overload can be used for button ordering. The default ordering varies according to the platform. Use QMessageBox.clickedButton() after calling exec() to query what button was used.

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_()

Upvotes: 5

Related Questions