简体   繁体   中英

PyQt4 signal does not emit

I try to build a udp server to receive binary messages, the socket emits processMsg signal when it received message and the processMsg function tries to emit different signal according to the message type. The QDefines object defines the message type and signal to be generated. I use dict to work around the missing switch/case in python. The problem is that the setRfRsp function didn't execute when UCSI_SET_RF_RSP_E message recevied.

Main.py file:

class mainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
    super(mainWindow, self).__init__()
    self.ui = Ui_MainWindow()
    self.defines = QDefines()
    self.connect(self.defines,QtCore.SIGNAL("signalSetRfRsp(PyQt_PyObject)"), self.setRfRsp)
    self.socket = QUdp(self.localIp, self.localPort, self.remoteIp, self.remotePort)
    self.connect(self.socket, QtCore.SIGNAL("processMsg(int,PyQt_PyObject)"), self.processMsg)
def setRfRsp(self, msg):
    if msg == 0x00000000:
        print "open"
    else:
        print "closed"
def processMsg(self, msgType, msg):
    defines = QDefines()
    msg_dict = defines.msgDictGen();
    msg_dict[msgType](msg)

defines.py file:

class QDefines(QtCore.QObject):
UCSI_SET_RF_RSP_E = 0x000d
def __init__(self, parent = None):
    super(QDefines, self).__init__()

def UCSI_SET_RF_RSP(self, msg):
    self.emit(QtCore.SIGNAL("signalSetRfRsp(PyQt_PyObject)"), msg) 

def msgDictGen(self):
    self.msgDict = {
        self.UCSI_SET_RF_RSP_E : self.UCSI_SET_RF_RSP
    } 
    return self.msgDict

The instance of QDefines that emits the signal never has any of its signals connected to anything, and it just gets garbage-collected when processMsg returns.

Perhaps you meant to write:

    def processMsg(self, msgType, msg):
        msg_dict = self.defines.msgDictGen()
        msg_dict[msgType](msg)

You should also consider getting rid of that nasty, old-style signal syntax, and use the nice, clean new-style instead:

class QDefines(QtCore.QObject):
    signalSetRfRsp = QtCore.pyqtSignal(object)
    ...

    def UCSI_SET_RF_RSP(self, msg):
        self.signalSetRfRsp.emit(msg) 

class mainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        ...
        self.defines = QDefines()
        self.defines.signalSetRfRsp.connect(self.setRfRsp)

Also, I would advise you to forget about trying to replicate switch statements in python, and just use if/elif instead. You'd need a very large number of branches before this started to become a significant performance issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM