// 发送信号的类
class Sender : public QObject
{
Q_OBJECT
signals:
void mySignal();
};
// 接收信号的类
class Receiver : public QObject
{
Q_OBJECT
public slots:
void mySlot()
{
qDebug() << "Slot executed";
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Sender sender;
Receiver receiver;
// 使用不同的连接类型连接信号和槽
QObject::connect(&sender, SIGNAL(mySignal()), &receiver, SLOT(mySlot()), Qt::AutoConnection);
QObject::connect(&sender, SIGNAL(mySignal()), &receiver, SLOT(mySlot()), Qt::DirectConnection);
QObject::connect(&sender, SIGNAL(mySignal()), &receiver, SLOT(mySlot()), Qt::QueuedConnection);
QObject::connect(&sender, SIGNAL(mySignal()), &receiver, SLOT(mySlot()), Qt::BlockingQueuedConnection);
QObject::connect(&sender, SIGNAL(mySignal()), &receiver, SLOT(mySlot()), Qt::UniqueConnection);
// 发射信号
emit sender.mySignal();
return app.exec();
}
运行上述示例代码,可以看到不同连接类型的效果。请注意,示例代码是使用C++编写的,但在Qt的Python绑定中,connect函数的用法是相同的。