我目前正在寻找一种方法,可以将TCP / IP通信添加到以pyQt编写的应用程序中。尽管我未测试的代码似乎都无法正常工作(在大多数情况下,它只是冻结了GUI),但我还是开始研究线程。
在堆栈上找到了一些代码,并增加了睡眠延迟。我已经阅读了一些有关按顺序运行的线程的信息,并且我认为我对线程的工作原理有所了解,但是得到的结果确实不是我期望的。
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()
我为什么得到:
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
代替
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
notify与notify2打印数量之比不等于时间延迟率吗?
答案 0 :(得分:0)
您将错误的方法连接到错误的信号。 process2
发出notify2
而不是notify
,因此您必须进行以下更改:
self.background.notify.connect(self.notify)
self.background.notify.connect(self.notify2)
到
self.background.notify.connect(self.notify)
self.background.notify2.connect(self.notify2)
它将正常工作。