打开qt帮助文档,connect函数声明如下
1、connect函数声明
[static] QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
2、函数说明
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later
You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:
简单翻译一下:创建一个信号发送对象和接收对象之间的连接。返回一个指向链接的句柄,这个句柄可以稍后用来断开连接。
在指定信号和方法时,必须使用SIGNAL()和SLOT()宏。
然后帮助文档中给了一个例子
3、用例
QScrollBar *scrollBar = new QScrollBar;QObject::connect(scrollBar, SIGNAL(valueChanged(int)),label, SLOT(setNum(int)));
4、参数说明
结合上面的函数声明用例来说一下,函数的各个参数
4.1第一个参数 const QObject *sender 信号发送者
类型是QObject我们常用的QWidget,一些控件,定时器等都继承自QObject,都可以作为信号发送者。
4.2第二个参数 const char *signal 为发送者发送的一个信号
信号实际上是一类函数,这类函数声明在Q_SIGNALS:后面。当对象改变其状态时,信号就由该对象发射 (emit) 出去,而且对象只负责发送信号,它不知道另一端是谁在接收这个信号。这样就做到了真正的信息封装,能确保对象被当作一个真正的软件组件来使用。
4.3第三个参数 const QObject *receiver 信号接收者
4.4第四个参数 const char *method 接收对象里面的槽函数
第四个参数为接收对象里面的槽函数。一般我们使用发送者触发信号,然后执行接收者的槽函数。
4.5第五个参数 Qt::ConnectionType type连接类型,一般使用默认值
5、一个信号可以连接到多个信号或者槽。
一个信号可以连接到多个槽或者信号,当一个信号被连接到多个槽时,槽的**顺序与连接顺序一致。
A signal can be connected to many slots and signals. Many signals can be connected to one slot.
If a signal is connected to several slots, the slots are activated in the same order in which the connections were made, when the signal is emitted.
6、举列
一个简单的定时器功能,定时器在定时完成时,发送信号,接收槽函数里面实现获取当前时间显示。
调用connect函数,timer为发送者,发送信号timeout,当前窗口为接收者,接收槽函数为自定义的timerUpdate函数。
启动定时器以及连接信号发送者和接收者 QTimer* timer=new QTimer(this);connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));timer->start(1000);
自定义槽函数声明
private slots:void timerUpdate();
自定义槽函数实现 QDateTime time = QDateTime::currentDateTime();QString string=time.toString("yyyy-MM-dd hh:mm:ss dddd");ui->label->setText(string);
程序运行效果
我也是刚开始学习qt,有什么理解不对的地方欢迎朋友指正,共同学习,共同进步。