开发者

Signals in PyQT4

I have I GUI and I want to estamblish some communication between two class

    .
    .
    .
    mainWidget = QtGui.QWidget()
    mainWidget.setLayout( mainLayout )
    self.setCentralWidget( mainWidget )
    self.show()

    """        Creating class        """
    self.server = MCCommunication.MCCommunication()
    self.connect( self.server, QtCore.SIGNAL( "textUpdated" ), self.insertText );
    sys.exit( self.app.exec_() )

the MCCommunication class is the following:

class MCCommunication( QtCore.QObject ): ''' classdocs '''

def __init__( self ):
    '''
    Constructor
    '''
    HOST, PORT = socket.gethostbyname( socket.gethostname() ), 31000
    self.server = SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )
    ip, port = self.server.server_address

    # Start a thread with the server
    # Future task: Make the server a QT-Thread...
    self.server_thread = threading.Thread( target = self.server.serve_forever )
    self.server_thread.start()
    self.emit( QtCore.SIGNAL( "textUpdated" ), ( "TCPServer listening on" ) )

but I get the following error:

self.emit( QtCore.SIGNAL( "textUpdated" ),开发者_JAVA技巧 ( "TCPServer listening on" ) )
RuntimeError: underlying C/C++ object has been deleted


You need to initialize the underlying QObject in your MCCommunication class. Add this line to the beginning of the __init__ method:

super(MCCommunication,self).__init__()


I don't use old style syntax for Signal and Slots.
You can use the new style:

class MCCommunication( QtCore.QObject ):
    textUpdated = pyqtSignal(str)
    def __init__( self ):
        super(MCCommunication,self).__init__()
        ...
        self.textUpdated.emit("TCPServer listening on")

In GUI instance:

self.server.textUpdated.connect(self.insertText)

UPDATED: I added the Stephen Terry's suggestion.

P.S. ( "TCPServer listening on" ) is not a tuple. It lacks a comma.
( "TCPServer listening on" ,) is a one-element tuple.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜