PDA

View Full Version : Difficult Cast I cannot figure out!



jgrauman
23rd June 2010, 16:59
Hello, I've been having a really difficult time trying to figure out how to make the following cast work properly and haven't been able to. I want to assign one class into another class that is different, and yet has an identical definition. The two classes are QAbstractTextDocumentLayout::Selection and QTextEdit::ExtraSelection. They are identical structs so I should be able to assign one into the other with a proper cast, but I cannot figure it out. Here's what I want to do with all the cast operators I've tried taken out... I was able to get it to work by simply copying the QList into a QVector item by item, but it was bugging me that I couldn't figure out how to do it this way which is a lot cleaner ;)



QAbstractTextDocumentLayout::PaintContext ctx;
ctx.selections = QVector<QAbstractTextDocumentLayout::Selection>::fromList(textEdit.extraSelections());


Thanks!

Josh

Vit Stepanek
23rd June 2010, 17:14
You're trying to cast type QTextEdit::ExtraSelection to type QAbstractTextDocumentLayout::Selection.
See method definition from QAssistant:

QVector<T> QVector::fromList ( const QList<T> & list )
Vector type and list types should be same.

jgrauman
23rd June 2010, 17:49
I had tried this, but can't get it to work. What modifications would you make to my code to get it to compile?

SixDegrees
23rd June 2010, 23:20
You cannot cast different object types to one another unless casting operators are defined for them. Although both classes, in this case, have the same public variables, there is no guarantee that their internal, non-public structure is the same, or that it will remain so in the future. In short, you can't do this, because C++ won't allow you to compile such potentially dangerous and ill-structured code.

Also, since the constituent QTextCursor and QTextCharFormat classes do not possess assignment, copy or similar operators, you cannot perform the assignment manually. At best, all you can do is examine the classes involved to see if they provide any functionality that will allow you to perform this operation on an item-by-item basis. The effort, though, seems dubious.

jgrauman
26th June 2010, 08:56
Thanks, that makes good sense, I wasn't thinking about that. I guess Qt should have made them the same type...