• 9433阅读
  • 6回复

Signal 和  Slot 能否有返回值? [复制链接]

上一主题 下一主题
离线rs779068092
 

只看楼主 倒序阅读 楼主  发表于: 2017-01-13
— 本帖被 圣域天子 设置为精华(2017-01-13) —
Signal 和  Slot 能否有返回值?
离线bran_lee

只看该作者 1楼 发表于: 2017-01-13
signal是不能有返回值得,slot可以有,可以把它看做是普通的c++函数那样用,不过用signal的方式调用的时候返回值没用
当你只有锤子时,你看什么都像是钉子!
离线rs779068092

只看该作者 2楼 发表于: 2017-01-13
回 bran_lee 的帖子
bran_lee:signal是不能有返回值得,slot可以有,可以把它看做是普通的c++函数那样用,不过用signal的方式调用的时候返回值没用
 (2017-01-13 10:37) 

我自己尝试了一下, 居然发现, 在Qt::DirectConnection 模式 下连接的信号和槽是有返回值得.
无意间发现了 一个博文的说明如下
QT信号槽 - 鸟语的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/zmy3376365/article/details/7590987

带返回值的信号槽

槽函数有返回值
可通过  value = emit mysignal() 得到返回值。

这里说明信号槽可以有返回值.
在Qt Creator 里面这样的写法是会被错误表示的,但是编译和运行没有问题
离线rs779068092

只看该作者 3楼 发表于: 2017-01-13
Qt 的API文档中对信号的解释
Signals
Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses.
When a signal is emitted, the slots connected to it are usually executed immediately, just like a normal function call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop. Execution of the code following the emit statement will occur once all slots have returned. The situation is slightly different when using queued connections; in such a case, the code following the emit keyword will continue immediately, and the slots will be executed later.
If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.
Signals are automatically generated by the moc and must not be implemented in the .cpp file. They can never have return types (i.e. use void).
A note about arguments: Our experience shows that signals and slots are more reusable if they do not use special types. If QScrollBar::valueChanged() were to use a special type such as the hypothetical QScrollBar::Range, it could only be connected to slots designed specifically for QScrollBar. Connecting different input widgets together would be impossible.

英文不是特别好, 这里他没有直接说明signal 和 slot 能否支持返回值得传递, 只是说 信号可以永远没有返回值,返回值可以是Void 类型
离线rs779068092

只看该作者 4楼 发表于: 2017-01-13
做了一个实验
// 简单的型号和槽
public slots:    int add(int a, int b){return a+b;}signals:    int doAdd(int a, int b);

再连接他们 :
connect(this,&MainWindow::doAdd,this,&MainWindow::add);
离线rs779068092

只看该作者 5楼 发表于: 2017-01-13
实现如下: 结果我得到返回值 7 了
int result = 0;    result = emit doAdd(2,5);
离线bran_lee

只看该作者 6楼 发表于: 2017-01-13
回 rs779068092 的帖子
rs779068092:做了一个实验
// 简单的型号和槽
public slots:    int add(int a, int b){return a+b;}signals:    int doAdd(int a, int b);
再连接他们 :
....... (2017-01-13 10:56) 

文档不是说“可以永远没有返回值”,是“永远不能有返回值”。文档这么写是有道理的,你现在的版本可以编译出想要的结果,不保证以后的Qt版本会得到同样的结果。
当你只有锤子时,你看什么都像是钉子!
快速回复
限100 字节
 
上一个 下一个