Reputation: 41
I am developing a GUI with Qt5, and in the main window of this GUI, it contains at least 4 tab widgets, and each tab widget will contain serval different child QWidgets, such as QLineEdit, QSpinBox, QLCDnumber, etc. Then when I open the tab, all its child widgets will appear.
Thus, for each tab, I decided to create a QVector(or another container type) to contain its all child Widgets,e.g.:
QVector<QWidget*> wids;
for the first tab widget, if it has the following children:
QLineEdit* line=new QLineEdit(this);
QLCDNumber* lcd=new QLCDNumber(this);
QSpinBox* spn=new QSpinBox(this);
then somehow I would like to do
wids.append(line);
wids.append(lcd);
wids.append(spn);
and next,I want to operate each widget inside the tab,e.g.:
wids[0]->setText("good");
wids[1]->display(1);
wids[2]->setRange(0,10);
I know I need to use dynamic_cast<...>, but I DO NOT KNOW how to do that,is ther anyone could give me some advice?
many thanks!
Upvotes: 2
Views: 405
Reputation: 2817
QLineEdit
, QLCDNumber
and QSpinBox
already inherit from QWidget
. So if you put those in a QVector
(or any container for that matter, could be a std::vector<QWidget*>
) you have to deal with QWidget
pointers.
As you correctly stated:
wids.push_back(line);
wids.push_back(lcd);
wids.push_back(spn);
To get your respective classes back, for example QLineEdit
back, you need to downcast from QWidget
to QLineEdit
, QLCDNumber
or whatever else inherits from QWidget
.
QLineEdit * line = dynamic_cast<QLineEdit*>(wids[0]);
This of course assumes that you know exactly at which position the object is located. You can of course test if your cast was successful:
if( line == nullptr )
{
// cast failed, either wids[0] is invalid or does not derive from QWidget
}
else
{
// cast was successful, use 'line' as regular QLineEdit.
}
A one-liner, although being quite unsafe, would be:
dynamic_cast<QLineEdit*>(wids[0])->setText("myText");
Upvotes: 3