Search code examples
c++qtqt4downcastqlist

C++ QT Casting to child classes for items in a QList


I have a QList of type PrintableObject* like:

QList<PrintableObject*> drawables;

This list contains objects of type PrintableX which are subclasses of PrintableObject inserted like:

drawables += &PrintableLine( x, y, x2, y2 );

After this I use the list a loop where I do determine the actual type, make a cast and try to use it:

foreach(PrintableObject* drawable, drawables){

       if(drawable->myClassName == "PrintableLine") {

           PrintableLine* line = (PrintableLine*) drawable;
           painter.drawLine(line->x, line->y, line->x2, line->y2);

       } else if (drawable->myClassName == "PrintableString") {

           PrintableString* string = (PrintableString*) drawable;
           font.setPointSize(string->fontSize);
           painter.setFont(font);

           painter.drawText(string->x, string->y, string->width, string->height, Qt::AlignHCenter | Qt::AlignTop, string->string "if I say?");

       }

   }

Except for, when I try to use my new shiny downcasted object it make a segmentation fault...

Any suggestions?


Solution

  • It seems that you insert a pointer to a dead temporary object into the list:

    drawables += &PrintableLine( x, y, x2, y2 );
    

    Try:

    drawables += new PrintableLine( x, y, x2, y2 );
    

    You may want also to consider adding a virtual draw method into your PrintableObject class to avoid the need of the RTTI and downcast.