QMetaType和继承

Joh*_*th0 3 c++ inheritance qt introspection qt4

好的,所以我对Qt和C++都不熟悉.我正在尝试将QMetaType与我自己的类一起使用,我无法让它与子类一起使用.这就是我所拥有的(可能有很多问题,抱歉):

testparent.h:

#include <QMetaType>

class TestParent
{
public:
    TestParent();
    ~TestParent();
    TestParent(const TestParent &t);
    virtual int getSomething(); // in testparent.cpp, just one line returning 42
    int getAnotherThing();      // in testparent.cpp, just one line returning 99
};

Q_DECLARE_METATYPE(TestParent)
Run Code Online (Sandbox Code Playgroud)

这是test1.h:

#include <QMetaType>
#include "testparent.h"

class Test1 : public TestParent
{
public:
    Test1();
    ~Test1();
    Test1(const Test1 &t);
    int getSomething();          // int test1.cpp, just one line returning 67
};

Q_DECLARE_METATYPE(Test1)
Run Code Online (Sandbox Code Playgroud)

...(除非另有说明,否则此处声明的所有成员都被定义为在testparent.cpp或test1.cpp中不执行任何操作(只需打开括号,右括号).这是main.cpp:

#include <QtGui/QApplication>
#include "test1.h"
#include "testparent.h"
#include <QDebug>

int main(int argc, char *argv[])
{
    int id = QMetaType::type("Test1");

    TestParent *ptr = new Test1;
    Test1 *ptr1 = (Test1*)(QMetaType::construct(id));
//    TestParent *ptr2 = (TestParent*)(QMetaType::construct(id));

    qDebug() << ptr->getSomething();
    qDebug() << ptr1->getSomething();     // program fails here
//    qDebug() << ptr2->getAnotherThing();
//    qDebug() << ptr2->getSomething();

    delete ptr;
    delete ptr1;
//    delete ptr2;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你可以看到我试图用ptr2测试一些多态性的东西,但后来我意识到ptr1甚至不起作用.(编辑:上一句话毫无意义.好吧,问题解决了(编辑:nvm它确实有意义))当我运行这个时发生的是第一个qDebug打印67,如预期的那样,然后它会卡住几秒钟最终以代码-1073741819退出.

非常感谢.

siv*_*vic 6

类型必须注册!宏Q_DECLARE_METATYPE还不够.您在主函数的开头缺少一行:

qRegisterMetaType<Test1>("Test1");
Run Code Online (Sandbox Code Playgroud)

现在你可以得到id的不是零(这意味着注册了类型):

int id = QMetaType::type("Test1");
Run Code Online (Sandbox Code Playgroud)