簡體   English   中英

來自成員函數指針的QMetaMethod

[英]QMetaMethod from member function pointer

給定一個指向QObject派生類的方法的指針:有沒有辦法獲得指針所指向的方法的QMetaMethod 我基本上是在尋找像QMetaMethod::fromSignal這樣的函數,但是對於插槽。


注意:我嘗試使用QMetaObject::IndexOfMethod通過static_metacall獲取索引, QMetaObject::IndexOfMethod其用於QMetaObject::method

void(Class::*method)() = &Class::method;
int methodIndex = -1;
void *metaArgs[] = {&methodIndex, reinterpret_cast<void **>(&method)};
const QMetaObject mo = Class::staticMetaObject;
mo.static_metacall(QMetaObject::IndexOfMethod, 0, metaArgs);
qDebug() << methodIndex;
// QMetaMethod mm = mo.method(methodIndex)

輸出始終為-1。

目前,唯一的解決方案是修改moc 但補丁相當簡單,但是:

diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp
index d831edf..7dcefcc 100644
--- a/src/tools/moc/generator.cpp
+++ b/src/tools/moc/generator.cpp
@@ -1311,15 +1311,12 @@ void Generator::generateStaticMetacall()
             isUsed_a = true;
         }

-    }
-    if (!cdef->signalList.isEmpty()) {
-        Q_ASSERT(needElse); // if there is signal, there was method.
         fprintf(out, " else if (_c == QMetaObject::IndexOfMethod) {\n");
         fprintf(out, "        int *result = reinterpret_cast<int *>(_a[0]);\n");
         fprintf(out, "        void **func = reinterpret_cast<void **>(_a[1]);\n");
         bool anythingUsed = false;
-        for (int methodindex = 0; methodindex < cdef->signalList.size(); ++methodindex) {
-            const FunctionDef &f = cdef->signalList.at(methodindex);
+        for (int methodindex = 0; methodindex < methodList.size(); ++methodindex) {
+            const FunctionDef &f = methodList.at(methodindex);
             if (f.wasCloned || !f.inPrivateClass.isEmpty() || f.isStatic)
                 continue;
             anythingUsed = true;

然后按預期工作:

// https://github.com/KubaO/stackoverflown/tree/master/questions/metamethod-lookup-24577095
#include <QtCore>

class MyObject : public QObject {
   Q_OBJECT
public:
   Q_SLOT void aSlot() {}
   Q_SLOT void aSlot2(int) {}
   Q_SLOT int aSlot3(int) { return 0; }
   Q_SIGNAL void aSignal();
   Q_SIGNAL void aSignal2(int);
};

template <typename Func> int indexOfMethod(Func method)
{
   using FuncType = QtPrivate::FunctionPointer<Func>;
   int methodIndex = -1;
   void *metaArgs[] = {&methodIndex, reinterpret_cast<void **>(&method)};
   auto mo = FuncType::Object::staticMetaObject;
   mo.static_metacall(QMetaObject::IndexOfMethod, 0, metaArgs);
   return methodIndex;
}

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   qDebug() << indexOfMethod(&MyObject::aSlot)
            << indexOfMethod(&MyObject::aSlot3) << indexOfMethod(&MyObject::aSignal2);
   return 0;
}
#include "main.moc"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM