slot is called multiple times when signal is emitted

后端 未结 2 862
醉话见心
醉话见心 2021-01-29 10:38

Consider functions like below:

class1::class1()
{
    class3 obj3 = new class3(this);
}
void class1::function1()
{
    class2 *obj2 = new class2();

    connect(         


        
相关标签:
2条回答
  • 2021-01-29 11:05

    You should only call connect once. Move your code that calls connect to a different function that is only called once.

    0 讨论(0)
  • 2021-01-29 11:05

    So I´m not sure you understand what you are doing or what you want. So I´ll explain what is happening and then we can rethink what you want. Qt is working as expected. You said you want the slot to be called whenever the signal is emitted. That is exactly what your code is doing.

    Now the question is ... are you aware that you create a new instance of your class2 each time function1 is called? Are you sure you didn´t just want a single instance of class2? Because that would then behave more in the way that you want it to.

    class2 *obj = 0;
    void class1::function1()
    {
        if(!obj)
        {
            obj = new class2();
            connect(this, SIGNAL(sig()), obj, SLOT(slt()));
        }
    }
    
    void class2::function2()
    {
        emit sig();
    }
    

    Since I have no idea where you create an object of class1, I just gave you something based on what you gave us. This should behave in the way you want it to. If that confuses you, I would suggest you should google some tutorials on learning C++, or object oriented programming (OOP) for that matter. Unfortunately I cannot recommend you any books/tutorials or else I would.

    I hope this helps you.

    0 讨论(0)
提交回复
热议问题