如何将 Pika 与 Qt 集成?

How to integrate Pika with Qt?

最近有用户问如何在Qt中使用Pika,没想到我正要post回答的时候被用户删了,这让我有机会用自动回答的方式提出这个问题where我尝试公开各种解决方案:

使用BlockingConnectionstart_consuming()方法必须在另一个线程中执行,此外必须知道回调是在辅助线程中执行的,所以如果你想更新GUI然后发出信号必须发射

import threading

from PyQt5 import QtCore, QtWidgets
# or
# from PySide2 import QtCore, QtWidgets

import pika


class RabbitMQManager(QtCore.QObject):
    messageChanged = QtCore.pyqtSignal(str)
    # or
    # messageChanged = QtCore.Signal(str)

    def __init__(self, *, parameters=None, parent=None):
        super().__init__(parent)

        self._connection = pika.BlockingConnection(parameters)

    @property
    def connection(self):
        return self._connection

    def start(self):
        channel = self.connection.channel()
        channel.queue_declare(queue="hello")
        channel.basic_consume(
            queue="hello", on_message_callback=self._callback, auto_ack=True,
        )
        threading.Thread(target=channel.start_consuming, daemon=True).start()

        print(" [*] Waiting for messages. To exit press CTRL+C")

    def _callback(self, ch, method, properties, body):
        print(" [x] Received %r" % body)
        self.messageChanged.emit(body.decode())


def main():

    import signal
    import sys

    # 
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QTextEdit()
    w.resize(640, 480)
    w.show()

    credentials = pika.PlainCredentials("user", "user")
    parameters = pika.ConnectionParameters("127.0.0.1", 5672, "/", credentials)

    rabbit_manager = RabbitMQManager(parameters=parameters)
    rabbit_manager.start()

    rabbit_manager.messageChanged.connect(w.append)

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()