Important: Please read the Qt Code of Conduct -

Adding custom ID String to Signal/Slot Event?

  • Hallo,

    I have a Problem with QModbusServer. I want to pass an custom Identification string for every ModbusServer Instance.

    void QModbusManager::onServerAddClick()
    	QModbusServer* device = new QModbusTcpServer(this);
    	QModbusDataUnitMap reg;
    	reg.insert(QModbusDataUnit::Coils, { QModbusDataUnit::Coils,0,20 });
    	reg.insert(QModbusDataUnit::DiscreteInputs, { QModbusDataUnit::DiscreteInputs,0,20 });
    	reg.insert(QModbusDataUnit::InputRegisters, { QModbusDataUnit::InputRegisters,0,20 });
    	reg.insert(QModbusDataUnit::HoldingRegisters, { QModbusDataUnit::HoldingRegisters,0,20 });
    	auto name = this->ui.tb_servername->text();
    	connect(device, &QModbusServer::dataWritten, this, [&](QModbusDataUnit::RegisterType type, int address, int size) { 
    		this->DataWrittenCallback(name, type, address, size);
    	//connect(device, &QModbusServer::dataWritten, this, &QModbusManager::DataWrittenCallbacktest);
    	connect(device, &QModbusServer::errorOccurred, this, [&](QModbusDevice::Error error) { this->ErrorCallback(name, error); });
    	//Setting UP IP
    	auto m = ui.lv_interfaces->currentIndex();
    	auto ip =;
    	device->setConnectionParameter(QModbusDevice::NetworkAddressParameter, ip);
    	device->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->ui.tb_port->text());
    	QPair<QModbusServer*, QString> p(device, this->ui.tb_target->text());
    	this->deviceMap.insert(name, p);

    When I click Add Server. It registers the Server Name and in the deviceMap there is the correct name. But when the Event is invoked name = ??? (Debugger Visual Studio 2019). Why does it forget the value?

    My Intention is to add a Sender Information like in C# Winforms eventcallback(object sender, EventArgs e) or POCO C++ eventCallback(void* sender, EventArgs& arg)

  • Lifetime Qt Champion

    it seems
    auto name = this->ui.tb_servername->text();
    is a local variable and you seems to capture it by referene so when
    onServerAddClick ends, its no longer valid. (and dataWritten fires much later)
    connect(device, &QModbusServer::dataWritten, this, [=]

  • Thanks,

    my bad, I misinterpreted the & inside the brackets. I thought [&] were for the lazies meaning include everything. Now I know it is = for values.

    If you wonder why I need multiple Modbus Servers It shall be a Modbus to UDP JSON connector.

  • Lifetime Qt Champion

    np :)
    I shot my foot of a few times capturing locals by reference.

Log in to reply