以下是有问题的代码
from PyQt5.QtCore import QThread, pyqtSignal, QByteArray
from PyQt5.QtNetwork import QTcpServer, QHostAddress
import numpy as np
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class TcpThread(QThread):
# connected = pyqtSignal(str)
def __init__(self, parent=None):
print("init")
super(TcpThread, self).__init__(parent)
self.timer = QTimer(self)
self.timer.timeout.connect(self.timerFunction)
def connectedSlot(self):
print("服务器建立连接")
self.socket = self.tcpServer.nextPendingConnection()
# self.timer.start(100)
def connectErrorSlot(self):
print("服务器出错")
def timerFunction(self):
print("timer")
if not hasattr(self.timerFunction, 'x'): # hasattr函数的第一个变量为当前函数名,第二个为变量名,加单引号
self.timerFunction.x = 0
a = np.sin(np.pi / 50 * self.timerFunction.x) * 1300
self.timerFunction.x += 1
self.socket.write(a)
def run(self):
print("发送数据多线程启动")
self.tcpServer = QTcpServer()
self.tcpServer.setObjectName("server")
self.tcpServer.newConnection.connect(self.connectedSlot)
self.tcpServer.acceptError.connect(self.connectErrorSlot)
self.tcpServer.listen(QHostAddress("127.0.0.1"), 9407)
原先的代码,tcpserver初始化在多线程的run函数里面,这样绑定的槽函数就不会触发
from PyQt5.QtCore import QThread, pyqtSignal, QByteArray
from PyQt5.QtNetwork import QTcpServer, QHostAddress
import numpy as np
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class TcpThread(QThread):
# connected = pyqtSignal(str)
def __init__(self, parent=None):
print("init")
super(TcpThread, self).__init__(parent)
self.tcpServer = QTcpServer()
self.tcpServer.setObjectName("server")
self.tcpServer.newConnection.connect(self.connectedSlot)
self.tcpServer.acceptError.connect(self.connectErrorSlot)
self.tcpServer.listen(QHostAddress("127.0.0.1"), 9407)
self.timer = QTimer(self)
self.timer.timeout.connect(self.timerFunction)
def connectedSlot(self):
print("服务器建立连接")
self.socket = self.tcpServer.nextPendingConnection()
# self.timer.start(100)
def connectErrorSlot(self):
print("服务器出错")
def timerFunction(self):
print("timer")
if not hasattr(self.timerFunction, 'x'): # hasattr函数的第一个变量为当前函数名,第二个为变量名,加单引号
self.timerFunction.x = 0
a = np.sin(np.pi / 50 * self.timerFunction.x) * 1300
self.timerFunction.x += 1
self.socket.write(a)
def run(self):
print("发送数据多线程启动")
# self.timer.start(100)
现在的代码,tcpserver初始化放在类的构造函数中,这样绑定的槽函数才能触发,原因我没想通,如果有知道的请留言给我,共同学习进步