Connect signals with parameters to lambda functions



  • Hi,
    i connect some singals to a lambda function/slot. Can i also use the parameter of the signal in the lambda functions?

    My current code:

    if (mbServer->state() != QModbusDevice::UnconnectedState)
    {
    	mbServer->disconnectDevice();
    
    	QEventLoop loop;
    	connect(mbServer, &QModbusDevice::stateChanged, this, [this, &loop]
    	{
    		if (mbServer->state() == QModbusDevice::UnconnectedState)
    			loop.quit();
    	});
    
    	loop.exec();
    }
    
    

    The signal QModbusDevice::stateChange has the parameter QModbusDevice::State state (http://doc.qt.io/qt-5/qmodbusdevice.html#stateChanged).

    Thanks!


  • Qt Champions 2016

    @beecksche

    Can i also use the paramater of the signals in the lambda functions?

    You can, but your lambda should have parameters as well ... :)

    QEventLoop loop;
    
    auto lambda = [&loop] (QModbusDevice::State state) -> void
    {
        if (state == QModbusDevice::UnconnectedState)
            loop.quit();
    }
    
    connect(mbServer, &QModbusDevice::stateChanged, lambda);
    

    Kind regards.



  • @kshegunov

    Works perfectly, thanks a lot!


  • Qt Champions 2016

    @beecksche
    No problem. May I ask something? Is modbus communication synchronous, I didn't see any async API in the docs?



  • @kshegunov
    Modbus clients have a asynchronous API (http://doc.qt.io/qt-5/qmodbusclient.html#details).

    For modbus servers it is not specified in the docs. But as far as i used the class, all calls are also asynchronous. In my case i want to ensure that server is not connected, before connect again. If i understood the docs of the QModbusDevice correctly, it is also possible to inherit from QModbusDevice and override the open() and close() function to ensure that.


  • Qt Champions 2016

    @beecksche said:

    Modbus clients have a asynchronous API

    Thanks. I skipped the description and went directly to the signals, but the way the API is organized is a bit different from QTcpSocket, so I got tangled up ... :D



  • @kshegunov said:

    the way the API is organized is a bit different from QTcpSocket

    You're right. I was also a little bit confused, when i used the QSerialBus module the first time (see my topic https://forum.qt.io/topic/65572/qmodbusmaster-example).

    Like i said, i think you can built your own class by inherit from QModbusDevice to have a synchronous API. The QSerialBus module is marked as technical preview in Qt 5.6, maybe they add some new functions in future releases similar to QTcpSocket like waitForConnected etc.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.