Thursday, 16 January 2020

qgis - How to programmatically close a QMessagebox without clicking ok or X?



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?



Answer



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.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...