Qt Signals and Slot connected twice… what happens?

天涯浪子 提交于 2019-12-28 12:15:30

问题


What happens if the same signal and slot is connected twice?

How is the mechanism handled?


回答1:


A few weeks ago, we had an intern accidentally connect a signal to a slot more than once. The idea was that under one condition, you'd have the slot connected to the signal, and under another condition you'd disconnect it. When you changed modes, you'd do the appropriate work.

Well, he forgot to to disconnect when appropriate. So every time you changed modes, you had a new connection to the slot.

The end result? 1 connection == 1 call to slot. 2 connections == 2 calls to slot. 3 connections == 3 calls to slot, etc. These calls happened "simultaneously" (I know in actuality they did not since they are on the same event thread, but what I mean was all calls were processed in succession).

As @Job points out in one of his comments (he deserves credit, so please do not upvote me for his work), Qt::UniqueConnection will prevent this issue.




回答2:


Usually bad things. It's perfectly acceptable to connect the slot twice or even more times but when the signal gets fired your slot will be called for each connection you made which is probably not what you want.

Note that it is not necessarily wrong to have multiple connections. There are (probably) perfectly valid uses for it. They are quite rare, I certainly can't think of any time I've used it as a feature. All the situations I can recall where there was a multiple connection turned out to be a bug rather than intended.




回答3:


The slot is executed multiple times (as others said already).

Some more notes:

  • In former times, the pattern for "connect exactly once" in cases where there might have been a connection before, was to first call disconnect and then connect to enforce exactly one connection.
  • Now, since 4.6, there is also the more elegant Qt::UniqueConnection, see http://doc.qt.io/qt-5/qt.html#ConnectionType-enum


来源:https://stackoverflow.com/questions/3530590/qt-signals-and-slot-connected-twice-what-happens

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