gpt4 book ai didi

python - 如何将 Pika 与 Qt 集成?

转载 作者:行者123 更新时间:2023-12-03 08:44:59 25 4
gpt4 key购买 nike

最近,一位用户询问如何在 Qt 中使用 Pika,但出乎意料的是,当我正要发布答案时,该用户删除了,这让我有机会通过自动回答提出这个问题,并尝试公开各种解决方案:

最佳答案

使用 BlockingConnection 时,start_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

# https://stackoverflow.com/a/6072360
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()

关于python - 如何将 Pika 与 Qt 集成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61842449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com