tags:

views:

187

answers:

2

Hi,

I am very new to the QT; please help me to solve the problem.

I am using thread to perform intensive operation in back ground. Meanwhile I want to update the UI, so I am using SIGNALS and SLOTS. To update UI I emit a signal and update UI.

Let us consider bellow sample code,

struct sample
    {
    QString name;
    QString address;
    };

void Update(sample *);

void sampleFunction()
{
    sample a;
    a.name = "Sachin Tendulkar";
    a.address = "India"
    emit Update(&a);    
}

In the above code we are creating a local object and passing the address of local object. In the QT document, it says that when we emit a signal it will be placed in the queue and late it will be delivered to the windows. Since my object is in local scope it will be delete once it goes out of the scope.

Please tell me a way to send a pointer in a signal.

+5  A: 

You're insisting on doing the wrong thing, why? Just send the Sample itself:

void Update(sample);
//...
sample a("MSalters", "the Netherlands");
emit Update(a);
MSalters
In general, I'm not a big fan of passing struct's by value - especially when the structs are large or prone to bloat. But in this case you are right, passing by value may be a better way to go. How large is a QString?
Sam Post
The cost of a straightforward copy ctor will be far exceeded by the cost of a cross-thread signal, and the cost of that in turn is far exceeded by a GUI update. So, this copy doesn't really matter.
MSalters
The QString implementation is a ref-counted COW string, so its quite efficient for passing around.
rep_movsd
+2  A: 

Unless you've determined that this code is a performance bottleneck you would be better to just pass a copy of the object rather than a pointer.

Really, I mean it.

However, if you must use pointers then use a boost::shared_ptr and it will delete itself.

void Update(boost::shared_ptr<sample> s);

void sampleFunction()
{
    boost::shared_ptr<sample> a = boost::shared_ptr<sample>(new sample());
    a->name = "Sachin Tendulkar";
    a->address = "India"
    emit Update(a);    
}
Josh Knauer
You can't use the . operator on a pointer. You meant to say a->name and a->address. Just a nit pick ;-)
A. Levy
Deleting argument in slot is a bad idea, because if you connect the signal to more than one slot, you'll get segfault. Just send the Sample as value, anything else is premature optimization and adds unnecessary complexity to memory management.
chalup
Agreed. Deleting in a slow is bad. Updated answer to use shared_ptr ... but still, really, just pass by value and save yourself pain :)
Josh Knauer