PySide/ PyQt

PySide/ PyQt Statusbar with colored Popup

I recently wrote an PySide UI where I needed Feedback for the user when an exception occured. I did not catch the underlying functions in any special way and just let them propagate to the top. But since the command line was hidden I looked for a way to make those exceptions visible to the user – and especially in a readable and noticable way.

So I implemented this Statusbar. Nothing fancy and coded real quick but maybe it helps someone else

<pre>from PySide import QtGui, QtCore

class ExceptionStatusBar(QtGui.QStatusBar):
    EXCEPTION_COLOR = QtGui.QColor("red")

    def __init__(self, level, **kwargs):
        super(ExceptionStatusBar, self).__init__(**kwargs)

        # Prepare background
        self.setAutoFillBackground(True)

        # Insert exception hook
        import sys
        sys.excepthook = self.create_excepthook(sys.excepthook)

    #
    # Background Property
    # -----------------

    def set_color(self, color):
        self.setStyleSheet("background-color: rgb({0}, {1}, {2});"
                           .format(color.red(), color.green(), color.blue()))

    def get_color(self):
        # Will not be used
        return self.palette().color(QtGui.QPalette.Background)

    backgroundColor = QtCore.Property(QtGui.QColor, get_color, set_color)

    def create_excepthook(self, sys_hook):
        def custom_hook(exc_type, exc_value, tb):
            self.handle_exception(exc_type, exc_value)
            return sys_hook(exc_type, exc_value, tb)

        return custom_hook

    def handle_exception(self, exc_type, msg):
        # Need to make it a property of the instance instead it is garbage collected
        self._anim = QtCore.QPropertyAnimation(self, "backgroundColor")
        self._anim.setDuration(800)
        self._anim.setStartValue(QtGui.QColor(self.EXCEPTION_COLOR))
        self._anim.setEndValue(self.palette().color(QtGui.QPalette.Background))

        # Actually showing the message
        self.showMessage("{0}: {1}".format(exc_type.__name__, msg), timeout=2000)

        self._anim.start()</pre>

By inserting my own excepthook in the sys.excepthook I get access to all Exceptions that will eventually happen. The QPropertyAnimation animates the Background Color.

Advertisements
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s