0

I want to write a simple server/client chat application. On the client side I create a thread and listen to message from server and when I receive message I call updateChatHistory function to append message to a QPlainTextEdit object in gui.

But the worker class never emits to main thread

class Ui_MainWindow(object):
    ...

    def updateChatHistory(self, text):
        print(text)
        self.worker = WorkerThread(text)
        self.worker.finishSignal.connect(self.appendToChatHistory)
        self.worker.start()


    def appendToChatHistory(self, text):
        # nothing prints and this function will not be called
        print('test', text)
        self.chatHistory.appendPlainText(text)


    # I call this method in setupUi function
    def connect_to_server(self):
        self.sckt = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
        self.sckt.connect((socket.gethostname(), self.port))

        t = threading.Thread(target=self.listen_for_message)
        t.daemon = True
        t.start()

    
    def listen_for_message(self):
        while True:
            msg = self.sckt.recv(1024).decode('utf-8')
            self.updateChatHistory(msg)

    ...


class WorkerThread(QThread):
    finishSignal = QtCore.pyqtSignal(str)

    def __init__(self, text):
        super(WorkerThread, self).__init__()
        self.text = text

    def run(self):
        self.finishSignal.emit(self.text)

I also tried without using worker class but I get this Error and I can't append anymore.

QObject::connect: Cannot queue arguments of type 'QTextBlock'
(Make sure 'QTextBlock' is registered using qRegisterMetaType().)
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)

EDIT: added extra code for cleararity

Alleh parast
  • 63
  • 1
  • 6
  • Your code is theoretically correct, but it's missing parts that could be the source of the error, so, please provide a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – musicamante Mar 24 '21 at 14:52
  • I added some code to question. I think it should be enough. – Alleh parast Mar 24 '21 at 15:08
  • Using a python Thread *and* a QThread is not really useful. Implement the socket receive in the QThread instead. – musicamante Mar 24 '21 at 15:10

0 Answers0