I want to pass a QString into a lambda slot-function to modify it further. Unfortunately the QString goes out of scope before reaching the slot, so I cannot append text. How can I ensure that the QString is not running out of scope to process it inside the lambda? A class member is no option for me.
// main.cpp
#include <QObject>
#include <qtclass.h>
int main(int argc, char* argv[])
{
QtClass q;
q.foo();
emit q.bar();
}
// qtclass.h
#include <QObject>
class QtClass : public QObject
{
Q_OBJECT
public:
void foo()
{
QString msg = "Hello"; // the string is being modified depending on different situations
if (boolFunc1())
msg += " qt";
if (!boolFunc2())
msg += " 123";
QObject::connect(this, &QtClass::bar, this, [&msg]()
{
msg.append(" World"); // access violation reading position, msg is out of scope
});
};
signals:
void bar();
};
a class member is no option for me. What's the use case?QtClassleaves, then it should be either astaticmember ofQtClassor a non-static member of an instance ofQtClass.msg? Because it is locally defined insidefoo()so mutating it here is of no use because it is inaccessible outside offoo(). So first defined howmsgis meant to be used, who is supposed to read/write into it, and so on, and I bet the solution to your issue will appear as an evidence.