I'm currently looking for a way to add TCP/IP communication to my application written in pyQt. While none of code i have tested appeared to work(in most cases it just freezed GUI) i started to investigate threading.

Found some code on stack and added sleep delays to it. I've read some information about threads running sequentially and i think i understand a bit how threading works, but the result i get is really not what i would expect.

import sys
from PyQt5 import QtWidgets, QtCore, QtGui
import time
import threading

class Example(QtWidgets.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        QtWidgets.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        btn = QtWidgets.QPushButton('Button', self)
        self.show()
        self.background = MyThread(self)
        t = threading.Thread(target=self.background.process)
        t2 = threading.Thread(target=self.background.process2)
        t.start()
        t2.start()
        self.background.notify.connect(self.notify)
        self.background.notify2.connect(self.notify2)

    @QtCore.pyqtSlot()
    def notify(self):
        print("I have been notified")

    @QtCore.pyqtSlot()
    def notify2(self):
        print("I have been notified two")

class MyThread(QtCore.QObject):

    notify = QtCore.pyqtSignal()
    notify2 = QtCore.pyqtSignal()

    def __init__(self, parent):
        super(MyThread, self).__init__(parent)
        self.should_continue = True

    def process(self):
        while self.should_continue:
            # Here, do your server stuff.
            time.sleep(0.001)
            self.notify.emit()

    def process2(self):
        while self.should_continue:
            # Here, do your server stuff.
            time.sleep(0.1)
            self.notify2.emit()

def main():

    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Why do i get:

I have been notified
I have been notified two
I have been notified two
I have been notified
I have been notified
I have been notified two
I have been notified
I have been notified two

instead of something like

I have been notified
I have been notified two
I have been notified
I have been notified
I have been notified
I have been notified
I have been notified

Shouldn't be the ratio of notify to notify2 prints number equal to time delays ratio ?

1 Answers

0
Community On Best Solutions

You have connected wrong method to the wrong signal. process2 emits notify2, not notify, so you have to change:

self.background.notify.connect(self.notify)
self.background.notify.connect(self.notify2)

to

self.background.notify.connect(self.notify)
self.background.notify2.connect(self.notify2)

And it will work as it should.