它对我有用。也许将您的实现与我在下面的实现进行比较,看看它可能会有所不同。我试图尽可能地遵循您的约定,猜测缺少的细节:
my_class.h
class MyClass : public QObject {
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0);
signals:
void mySignalToMainThread();
public slots:
void someCallback();
void doThisOnMainThread();
};
my_class.cpp
MyClass::MyClass(QObject *parent) :
QObject(parent) {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
OtherClass::getInstance().setCallback(this);
connect(this, SIGNAL(mySignalToMainThread()), SLOT(doThisOnMainThread()));
}
void MyClass::someCallback() {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
emit mySignalToMainThread();
}
void MyClass::doThisOnMainThread() {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
}
other_class.h
class OtherClass : public QObject {
Q_OBJECT
public:
static OtherClass& getInstance();
void setCallback(MyClass *cb);
public slots:
void doCallback();
private:
explicit OtherClass(QObject *parent = 0);
MyClass *cb_;
};
other_class.cpp
OtherClass::OtherClass(QObject *parent) : QObject(parent) {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
}
OtherClass& OtherClass::getInstance() {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
static OtherClass singleton;
return singleton;
}
void OtherClass::doCallback() {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
cb_->someCallback();
}
void OtherClass::setCallback(MyClass *cb) {
std::cout << Q_FUNC_INFO << QThread::currentThreadId() << std::endl;
cb_ = cb;
}
主文件
int main (int argc, char **argv) {
QApplication app(argc, argv);
MyClass c;
QThread other;
OtherClass::getInstance().moveToThread(&other);
other.connect(&other, SIGNAL(started()),
&OtherClass::getInstance(), SLOT(doCallback()));
other.start();
QMainWindow w;
w.show();
return app.exec();
}
样本输出:
__thiscall MyClass::MyClass(class QObject *)00001108
class OtherClass &__cdecl OtherClass::getInstance(void)00001108
__thiscall OtherClass::OtherClass(class QObject *)00001108
void __thiscall OtherClass::setCallback(class MyClass *)00001108
class OtherClass &__cdecl OtherClass::getInstance(void)00001108
class OtherClass &__cdecl OtherClass::getInstance(void)00001108
void __thiscall OtherClass::doCallback(void)000015AC
void __thiscall MyClass::someCallback(void)000015AC
void __thiscall MyClass::doThisOnMainThread(void)00001108