問題描述
我在一個塊中使用一個信號和插槽連接.我的代碼如下
I am using one signal and slot connection in a block. My code as follows
在 a.cpp 中
{
QObject::connect(m_ptheFlange2Details,SIGNAL(GetFlang1DimAfterAnalysis()),
this,SLOT(GetFlang1DimAftrAnalysis()));
m_ptheFlange2Details->get();// one function inside which i am emiting
// GetFlang1DimAfterAnalysis() signal ;
QObject::disconnect(m_ptheFlange2Details,SIGNAL(GetFlang1DimAfterAnalysis()),
this,SLOT(GetFlang1DimAftrAnalysis()));
}
當這個emit 語句執(zhí)行時,在get() 函數(shù)中,槽被調(diào)用了很多次.根據(jù)我的說法,它應該只調(diào)用一次.
Inside the get() function when this emit statement executes, the slot is called lots of times. Where as according to me it should call only once.
推薦答案
正如一些評論中所述,這通常是由于多次調(diào)用 connect 造成的.每次建立連接時都會調(diào)用一次插槽.例如,下面的代碼將導致 slot()
在 signal()
被發(fā)射一次時被調(diào)用 3 次.
As stated in some of the comments, this is usually caused by calling the connect more the once. The slot will be called once for every time the connection is made. For example, the following code will result in slot()
being called 3 times when signal()
is emitted once.
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()));
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()));
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()));
如果您在可能運行多次的代碼中進行連接,通常使用 Qt::UniqueConnection
作為第 5 個參數(shù)是個好主意.以下代碼將導致 slot()
在 signal()
發(fā)出一次時被調(diào)用 1 次.
If you are doing connects in code that may be run more than once, it is generally a good idea to use Qt::UniqueConnection
as the 5th parameter. The following code will result in slot()
being called 1 time when signal()
is emitted once.
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()), Qt::UniqueConnection);
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()), Qt::UniqueConnection);
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()), Qt::UniqueConnection);
我猜你的代碼不能正常工作的原因是你省略了第 5 個參數(shù)并且連接默認為 Qt::DirectConnection
(對于單線程程序).這會立即調(diào)用插槽,就好像它是一個函數(shù)調(diào)用一樣.這意味著有可能在斷開連接之前再次調(diào)用 connect(如果您的程序中存在循環(huán)).
I'm guessing the reason your code is not working correctly is because you are omitting the 5th parameter and connect defaults to Qt::DirectConnection
(for single threaded programs). This immediately calls the slot as if it were a function call. This means that it is possible for connect to be called again before the disconnect happens (if there are loops in your program).
這篇關(guān)于每次發(fā)出信號時都會多次調(diào)用插槽的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!