在哪里将Reactor.run()放在PyQt应用中?

时间:2019-07-11 03:15:30

标签: python pyqt twisted

难以显示窗口/无法连接到服务器,具体取决于Reactor.run()的位置

如果我在 retranslateUi(自我,MainWindow)之前或之后放置reactor.run(),则聊天服务器会将连接记录为成功,但不会加载UI。如果将 reactor.run()放在 sys.exit(app.exec _())之后,即使UI已加载,客户端也无法连接。

最佳解决方案是什么?

from __future__ import print_function
from PyQt5 import QtCore, QtGui, QtWidgets
from twisted.internet import protocol
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

from twisted.application import service, internet

class Ui_MainWindow(object):

    #Note actual code lives here

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

    #prepare the chat 
    reactor.connectTCP("localhost",1025,ChatClientFactory())
    reactor.run()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.lineEdit_2.setText(_translate("MainWindow", "    Search "))
        self.pushButton.setText(_translate("MainWindow", "Send"))





class ChatClient(LineReceiver):

    def __init__(self, factory):
        self.factory = factory

    def lineReceived(self, data):
        self.factory.text_from_patient = "{:>10}".format(data) # store the data so we can write to textedit

        self.textEdit.appendPlainText("\n"+ self.factory.text_from_patient)


class ChatClientFactory(protocol.ClientFactory):
    text_from_patient = " " # text to contain data sent from the user

    def buildProtocol(self, addr):
        return ChatClient(self)


    def clientConnectionFailed(self, connector, reason):
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        reactor.stop()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()


    sys.exit(app.exec_())

2 个答案:

答案 0 :(得分:1)

这是我在文档中找到的。

Twisted可以在QApplication.exec_()之后通过调用来初始化 reactor.runReturn()。呼叫reactor.stop()会解除扭曲,但 保持您的Qt应用程序运行。

您的执行代码应如下所示

gui_app.exec_()
twisted.internet.reactor.runReturn()

答案 1 :(得分:0)

按常规方式使用qt5reactorreactor.run