2

So part of my script in PyQGIS is this:

QMessageBox.warning(None,"Warning","bla bla bla")

The box apperas just fine but i want it to close after a few seconds so i am looking for something like this:

QMessageBox.warning(None,"Warning","bla bla bla")
time.sleep(2)
(command that closes the box without clicking ok or hitting X)

Any ideas?

2 Answers 2

6

Nathan W is correct. But, if you still want to display a QMessageBox with autoclose behaviour. You can do it bu subclassing the QMessageBox like this:

class CustomMessageBox(QMessageBox):

def __init__(self, *__args):
    QMessageBox.__init__(self)
    self.timeout = 0
    self.autoclose = False
    self.currentTime = 0

def showEvent(self, QShowEvent):
    self.currentTime = 0
    if self.autoclose:
        self.startTimer(1000)

def timerEvent(self, *args, **kwargs):
    self.currentTime += 1
    if self.currentTime >= self.timeout:
        self.done(0)

@staticmethod
def showWithTimeout(timeoutSeconds, message, title, icon=QMessageBox.Information, buttons=QMessageBox.Ok):
    w = CustomMessageBox()
    w.autoclose = True
    w.timeout = timeoutSeconds
    w.setText(message)
    w.setWindowTitle(title)
    w.setIcon(icon)
    w.setStandardButtons(buttons)
    w.exec_()

And call it like this:

CustomMessageBox.showWithTimeout(3, "Auto close in 3 seconds", "QMessageBox with autoclose", icon=QMessageBox.Warning)

This code is an adaptation from this answer in stackoverflow.

2
  • But don't, because that is mean to your users.
    – Nathan W
    Commented Mar 4, 2015 at 11:31
  • 2
    @NathanW the only user of this is me and my professor so no worries! Thanks for the answers they really helped. I got another question gis.stackexchange.com/questions/137537/… Go to my last comment to save some time
    – Stelios M
    Commented Mar 4, 2015 at 13:38
6

Don't use a message box for this. It is not what they are for and will make people cry. Use the message bar.

iface.messageBar().pushWarning("title", "message")

or

iface.messageBar().pushMessage("title", "message")

http://qgis.org/api/classQgsMessageBar.html

1
  • @Stelios what is your version? an alternative is to avoid the shortcut e.g. iface.messageBar().pushMessage("title", "message", QgsMessageBar.WARNING) and study this class: qgis.org/api/classQgsMessageBar.html Commented Mar 4, 2015 at 12:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.