[Qt-interest] QMetaType question

JD Guzman lostinthecode at googlemail.com
Mon Jan 18 09:15:15 CET 2010


Thiago Macieira wrote:
> Em Domingo 17. Janeiro 2010, às 16.49.18, JD Guzman escreveu:
>   
>> Good afternoon,
>>
>> I was trying to work with QMetaType to create a instance of a class that
>> I have made.  I followed the documentation and have gotten to the point
>> that I am doing the following:
>>
>>     int id = QMetaType::type("MyClass");
>>
>>     if (id != 0)
>>     {
>>         qDebug("MyClass found ...");
>>         void* controller = QMetaType::construct(id);
>>     }
>>
>> I do get the "MyClass found ..." message and there are no errors so I am
>> assuming that everything is good up to there.  My question is where do I
>> go from here?  Since controller is type void* I cannot call any of the
>> functions in MyClass.  I tried casting but that didn't work either.
>>     
>
> That's all there is. You can cast it to MyClass* and it should work:
>
> MyClass *c = static_cast<MyClass *>(controller);
>
> The only two other operations in QMetaType you can do are copy (construct with 
> a non-0 second argument) and destroy.
>
> Anything else is only available through the casting.
>   
Ok well I tried doing the static cast and I got a segmentation fault.  I 
must be doing something wrong.

Perhaps if I give some info on what I want to do it will help.  As an 
example lets say I have a console program and the user is asked what 
function he would like to do, and he chooses "calculator" this input 
would create a calculator instance.  He then says he would like to add 
2, 2.  This would call the add on the calculator instance and pass 2, 2 
as the arguments.

I realize that it would be trivial to do this with a switch statement 
however the final implementation of what I am trying to do could have a 
large amount of choices and that is why I was looking for something that 
used some of the "reflection" properties in Qt.

Is this possible at all?  Or should I look into using a reflection 
library and add it into my solution?

Regards,

JD



More information about the Qt-interest-old mailing list