开发者

QMetaType and inheritance

OK, so I'm new to both Qt and C++ for that matter. I'm trying to use QMetaType with my own classes, and I can't get it to work with subclasses. Here's what I have (there're probably tons of problems, sorry):

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)

And here's test1.h:

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

class Test1 : public TestParent
{
public:
    Test1(开发者_如何学C);
    ~Test1();
    Test1(const Test1 &t);
    int getSomething();          // int test1.cpp, just one line returning 67
};

Q_DECLARE_METATYPE(Test1)

... (Unless otherwise indicated, all the members declared here are defined to do nothing (just open bracket, close bracket) in testparent.cpp or test1.cpp) Here's 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;
}

As you can see I was trying to test out some polymorphism stuff with ptr2, but then I realized ptr1 doesn't even work. (EDIT: prev sentence makes no sense. Oh well, problem resolved (EDIT: nvm it does make sense)) What happens when I run this is the first qDebug prints 67, as expected, and then it gets stuck for a few seconds and eventually exits with code -1073741819.

Thanks so much.


Type has to be registered! Macro Q_DECLARE_METATYPE is not sufficient. You are missing one line at start of main function:

qRegisterMetaType<Test1>("Test1");

now you can get id that is not zero (which means that type is registered):

int id = QMetaType::type("Test1");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜