user443850
user443850

Reputation: 279

PyQt prevent multiple instances of an application popping up the same dialog

I have an application which pops up a notification dialog to the front of all windows whenever new rss feeds are available. The user can have multiple instances of the application running though, and I only want a single notification dialog to pop up. Any thoughts on how to achieve this? Thanks.

Upvotes: 3

Views: 1985

Answers (1)

mata
mata

Reputation: 69082

You could simply place a lockfile somewhere to indicate that another process is showing a dialog, and check wheater that exists before displaying another one.

A more sophisticated way would be to use QSharedMemory to synchronize your access. I've done something similar using a context manager in a comparable situation, but for this case it could look something like:

from PyQt4.QtGui import QApplication, QMessageBox
from PyQt4.QtCore import QSharedMemory


class MemoryCondition:
    def __init__(self, key='memory_condition_key'):
        self._shm = QSharedMemory(key)
        if not self._shm.attach():
            if not self._shm.create(1):
                raise RuntimeError('error creating shared memory: %s' %
                                   self._shm.errorString())
        self.condition = False

    def __enter__(self):
        self._shm.lock()
        if self._shm.data()[0] == b'\x00':
            self.condition = True
            self._shm.data()[0] = b'\x01'
        self._shm.unlock()
        return self.condition

    def __exit__(self, exc_type, exc_value, traceback):
        if self.condition:
            self._shm.lock()
            self._shm.data()[0] = b'\x00'
            self._shm.unlock()


# usage example:
app = QApplication([])

with MemoryCondition() as condition:
    if condition:
        mb = QMessageBox()
        mb.setText("you'll only see one of me")
        mb.exec_()
    else:
        print("other process is doing it's stuff")

Upvotes: 4

Related Questions