查看完整版本: [-- Signal 和  Slot 能否有返回值? --]

QTCN开发网 -> Qt基础编程 -> Signal 和  Slot 能否有返回值? [打印本页] 登录 -> 注册 -> 回复主题 -> 发表主题

rs779068092 2017-01-13 10:14

Signal 和  Slot 能否有返回值?

Signal 和  Slot 能否有返回值?

bran_lee 2017-01-13 10:37
signal是不能有返回值得,slot可以有,可以把它看做是普通的c++函数那样用,不过用signal的方式调用的时候返回值没用

rs779068092 2017-01-13 10:42
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 2017-01-13 10:49
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 2017-01-13 10:56
做了一个实验
// 简单的型号和槽
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 2017-01-13 11:01
实现如下: 结果我得到返回值 7 了
int result = 0;    result = emit doAdd(2,5);

bran_lee 2017-01-13 11:04
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版本会得到同样的结果。


查看完整版本: [-- Signal 和  Slot 能否有返回值? --] [-- top --]



Powered by phpwind v8.7 Code ©2003-2011 phpwind
Gzip disabled