Updating pointer using signals and slots

醉酒当歌 提交于 2020-01-02 13:44:05

问题


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

I am using a thread to perform intensive operations in the background. 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 below 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 a 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.

Is there a way to send a pointer in a signal?


回答1:


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);



回答2:


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);    
}


来源:https://stackoverflow.com/questions/2637218/updating-pointer-using-signals-and-slots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!