软件课设已经过去一年多了,今天翻过去又看了下,发现当时并没有留下什么文字资料,凭着记忆并查看下资料还是回忆起了一些内容,在此简记;
Qt version: Qt5
Qt signals-slots机制
Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. Signals and slots are made possible by Qt’s meta-object system.
Introduction
In GUI programming, when we change one widget, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. For example, if a user clicks a Close button, we probably want the window’s close()
Other toolkits achieve this kind of communication using callbacks. A callback is a pointer to a function, so if you want a processing function to notify you about some event you pass a pointer to another function (the callback) to the processing function. The processing function then calls the callback when appropriate. While successful frameworks using this method do exist, callbacks can be unintuitive and may suffer from problems in ensuring the type-correctness of callback arguments.
MOC
moc(meta-Object-Complier)其实并不起到编译器的作用,只是在预处理之前,根据一些宏产生C++代码,并与源文件一起参与编译。
Using the Meta-Object Compiler (moc)
The Meta-Object Compiler, moc
, is the program that handles Qt’s C++ extensions.
The moc
tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.
The C++ source file generated by moc
must be compiled and linked with the implementation of the class.
If you use qmake to create your makefiles, build rules will be included that call the moc when required, so you will not need to use the moc directly. For more background information on moc
, see Why Does Qt Use Moc for Signals and Slots?
后记
- signals 与 slots 的控制访问权限
在使用 slots 的过程中,发现声明的 slots 的控制访问类型均为 private,但并没有发现 public,protected,private对于slots有什么区别,还有就是 signals 声明时为默认访问类型(private?) ,但使用 connect() 总能把 signals与slots连接起来;查看资料发现:
- Signals are protected in Qt4 but are public in Qt5, thus the contradictory information.
- Slots are functions and public/protected/private is honored when calling them as such, when connecting to a signal, the metaobject system ignores it though.
具体详见 Qt signals and slots: permissions
参考
更多内容可关注本人博客:老香椿(https://laoxiangchun.cn/)