QT4:
QMetaQbject::
Connection
QObject::
connect(
const
QObject*
sender,
const
char*
signal,
const
QObject*
receiver,
const
char*
slot,
Qt::
ConnectionType
type =
Qt::
AutoConnection)
QT5:
template<
typename
PointerToMemberFunction>
QMetaQbject::
Connection
QObject::
connect(
const
QObject*
sender,
PointerToMemberFunction
signal,
const
QObject*
receiver,
PointerToMemberFunction
slot,
Qt::
ConnectionType
type =
Qt::
AutoConnection)
示例:
QT4:connect(sender, SIGNAL(sigTest(int, double)), receiver, SLOT(slotTest(int, double)))
QT5:connect(sender, &QObject::sigTest, receiver, &QObject::slotTest);
QT5较QT4在使用上,信号和槽不需要指明参数列表,使用第二种连接方式则要求信号或槽不允许存在同名重载函数
【connect连接方式】
type为连接方式,共五种
-
Qt::AutoConnection:自动连接,默认值。如果sender发送信号和receiver位于不同线程,则使用Qt::QueuedConnection;位于同个线程则使用Qt::DirectConnection
-
Qt::DirectConnection:直连。同个线程上同步执行,emit后的代码将在槽函数执行后继续执行,本质上就是函数调用
-
Qt::QueuedConnection:队列连接。支持跨线程操作,emit后信号会放入队列,接收对象所属线程的事件循环从队列获取信号再执行对应的槽函数
-
Qt::BlockingQueuedConnection:阻塞队列连接。信号发送后当前线程会阻塞,直到槽函数执行完成,禁止在sender和receiver位于同一线程时使用,避免死锁
-
Qt::UniqueConnection:唯一连接。用“|”与其余信号一起使用,指明同一个信号只与同一个槽进行连接,避免多次连接导致调用多次槽函数
注意:QThread对象依附在主线程中,QThread对象的slot函数在主线程中执行,而非QThread管理的子线程。若需在子线程中执行slot函数可以通过moveToThread