Create an array containing different types?
-
I've got a program that has four "windows" that are split in equal sizes inside the main window. They are randomly assigned either a type of QFrame or QTextEdit. My issue is that I either need to have a super long, messy code nest with tons of if statements to reference them correctly OR I need a vector of some sort. The issue is that I can't create a vector with BOTH QFrame and QTextEdit references inside. My question is therefore, is there a way to create an array/vector/etc containing both QFrame and QTextEdit? I've tried creating a vector array of type "any" with boost, but boost does not install on my computer for some reason
std::vector vector_of_windows<boost::any>; // does not work since I am using a mac that does not have boost installed (I've tried using homebrew, Mac ports and building it from source myself. Still does not work.)
All I want to achieve is the following
stack_of_windows[i]->resize(window_width, window_height);
-
@legitnameyo said in Create an array containing different types?:
The issue is that I can't create a vector with BOTH QFrame and QTextEdit references inside. My question is therefore, is there a way to create an array/vector/etc containing both QFrame and QTextEdit?
QTextEdit
indirectly inheritsQFrame
. So, you can store them both in astd::vector<QFrame*>
. -
hi @legitnameyo
resize is a function of QWidget, QFrame and QTextEdit both derive from QWidget.
So you can simply make an array/Vecotr/list of QWidget pointers, and you're good to go.
If you later on want to access function of the derived class you can do that as well, simply use qobject_cast<QFrame*>(widgetPointer),
the cast returns a nullptr if the cast fails. so make sure to check, if your mix different classes.
-
Created a vector of QFrame* worked!
-
@legitnameyo The problem you identified is the heterogeneous collection versus the homogeneous collection. Smalltalk had the former since is was late binding, but C++ is strongly typed early bound, so it only supports the later. In your case the classes were derived from the same superclass, so you were saved, but that will not always be the case.