它不会在第二个线程中启动它。AFAIK,默认情况下它将是直接呼叫或排队等待处理。这种情况还取决于您如何管理线程。
您可以选择多种连接类型,但通常默认(直接或排队)应该没问题。
我将向您展示两个示例,以证明它还取决于确切发出信号的内容。
案例 1(由正在执行的插槽发出)
主文件
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QCoreApplication>
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0) : QObject(parent), counter(0)
{
connect(this, SIGNAL(mySignal()),
this, SLOT(mySlot()), Qt::QueuedConnection);
}
signals:
void mySignal();
public slots:
void mySlot()
{
if (counter >= 2) return;
++counter;
qDebug() << "mySlot started";
emit mySignal();
QThread::msleep(1000);
qDebug() << "mySlot quit";
}
private:
int counter;
};
#include "main.moc"
int main(int argc, char **argv)
{
QCoreApplication application(argc, argv);
MyClass myObject;
myObject.mySlot();
return application.exec();
}
主程序
TEMPLATE = app
TARGET = test
QT = core
SOURCES += main.cpp
构建并运行
moc -o main.moc main.cpp && qmake && make && ./test
输出
mySlot started
mySlot quit
mySlot started
mySlot quit
在我的示例中,您将在没有排队连接的情况下获得以下输出,表明这将是插槽执行过程中的直接调用:
mySlot started
mySlot started
mySlot quit
mySlot quit
情况 2(不是由正在执行的插槽发出)
主文件
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QCoreApplication>
#include <QTimer>
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0) : QObject(parent), counter(0), timer(new QTimer(this))
{
// Note: there is no need for queued connection in this case
connect(this, SIGNAL(mySignal()), this, SLOT(mySlot()));
connect(timer, SIGNAL(timeout()), this, SLOT(mySlot()));
timer->setSingleShot(true);
timer->start(200);
}
signals:
void mySignal();
public slots:
void mySlot()
{
++counter;
qDebug() << "mySlot started" << counter;
QThread::msleep(1000);
qDebug() << "mySlot quit" << counter;
}
private:
int counter;
QTimer *timer;
};
#include "main.moc"
int main(int argc, char **argv)
{
QCoreApplication application(argc, argv);
MyClass myObject;
myObject.mySlot();
return application.exec();
}
主程序
TEMPLATE = app
TARGET = test
QT = core
SOURCES += main.cpp
构建并运行
moc -o main.moc main.cpp && qmake && make && ./test
输出
mySlot started 1
mySlot quit 1
mySlot started 2
mySlot quit 2