聲明該指針到成員類型的typedef。
聲明並註冊該typedef的元類型。
只能使用typedef - 記住moc使用字符串比較來確定類型相等,它沒有C++類型的表達式解析器。
下面是一個例子。在調用a.exec()
時,事件隊列中有兩個QMetaCallEvent
事件。第一個是c.callSlot
,第二個是a.quit
。它們按順序執行。回想一下,排隊呼叫(不管是由於invokeMethod
還是由於信號激活)導致爲每個接收器發佈QMetaCallEvent
。
#include <QCoreApplication>
#include <QDebug>
#include <QMetaObject>
class Class : public QObject {
Q_OBJECT
public:
typedef void (Class::*Method)(const QString &);
private:
void method(const QString & text) { qDebug() << text; }
Q_SLOT void callSlot(const QString & text, Class::Method method) {
(this->*method)(text);
}
Q_SIGNAL void callSignal(const QString & text, Class::Method method);
public:
Class() {
connect(this, SIGNAL(callSignal(QString,Class::Method)),
SLOT(callSlot(QString,Class::Method)),
Qt::QueuedConnection);
emit callSignal("Hello", &Class::method);
}
};
Q_DECLARE_METATYPE(Class::Method)
int main(int argc, char *argv[])
{
qRegisterMetaType<Class::Method>();
QCoreApplication a(argc, argv);
Class c;
QMetaObject::invokeMethod(&a, "quit", Qt::QueuedConnection);
return a.exec();
}
#include "main.moc"
只是一個小問題:你爲什麼要傳遞一個指針作爲參數? –
你有什麼錯誤?可能,你忘了爲函數指針類型調用Q_DECLARE_METATYPE/qRegisterMetatype? –
[debug/moc_MainFrame.cpp]錯誤1. 不知道Q_DECLARE_METATYPE(我會看)。我知道我可以公開聲明這個函數的聲明並且它可以工作,但是由於這個錯誤我不能用它作爲SLOT。 我正在使用QTcpServer,當我收到一個答案時,我也得到了指針,它給了我下一個函數調用。 – user3429997